content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground import android.content.SharedPreferences import android.os.Looper import androidx.navigation.NavDirections import com.google.android.ground.repository.TermsOfServiceRepository import com.google.android.ground.repository.UserRepository import com.google.android.ground.system.auth.SignInState.Companion.error import com.google.android.ground.system.auth.SignInState.Companion.signingIn import com.google.android.ground.ui.common.Navigator import com.google.android.ground.ui.home.HomeScreenFragmentDirections import com.google.android.ground.ui.signin.SignInFragmentDirections import com.google.common.truth.Truth.assertThat import com.sharedtest.FakeData import com.sharedtest.TestObservers.observeUntilFirstChange import com.sharedtest.persistence.remote.FakeRemoteDataStore import com.sharedtest.system.auth.FakeAuthenticationManager import dagger.hilt.android.testing.HiltAndroidTest import io.reactivex.observers.TestObserver import java8.util.Optional import javax.inject.Inject import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows import org.robolectric.shadows.ShadowToast @HiltAndroidTest @RunWith(RobolectricTestRunner::class) class MainViewModelTest : BaseHiltTest() { @Inject lateinit var fakeAuthenticationManager: FakeAuthenticationManager @Inject lateinit var fakeRemoteDataStore: FakeRemoteDataStore @Inject lateinit var viewModel: MainViewModel @Inject lateinit var navigator: Navigator @Inject lateinit var sharedPreferences: SharedPreferences @Inject lateinit var tosRepository: TermsOfServiceRepository @Inject lateinit var userRepository: UserRepository private lateinit var navDirectionsTestObserver: TestObserver<NavDirections> @Before override fun setUp() { // TODO: Add a test for syncLois super.setUp() fakeAuthenticationManager.setUser(FakeData.USER) // Subscribe to navigation requests navDirectionsTestObserver = navigator.getNavigateRequests().test() } private fun setupUserPreferences() { sharedPreferences.edit().putString("foo", "bar").apply() } private fun verifyUserPreferencesCleared() { assertThat(sharedPreferences.all).isEmpty() } private fun verifyUserSaved() { userRepository.getUser(FakeData.USER.id).test().assertResult(FakeData.USER) } private fun verifyUserNotSaved() { userRepository.getUser(FakeData.USER.id).test().assertError(NoSuchElementException::class.java) } private fun verifyProgressDialogVisible(visible: Boolean) { observeUntilFirstChange(viewModel.signInProgressDialogVisibility) assertThat(viewModel.signInProgressDialogVisibility.value).isEqualTo(visible) } private fun verifyNavigationRequested(vararg navDirections: NavDirections) { navDirectionsTestObserver.assertNoErrors().assertNotComplete().assertValues(*navDirections) } @Test fun testSignInStateChanged_onSignedOut() { setupUserPreferences() fakeAuthenticationManager.signOut() Shadows.shadowOf(Looper.getMainLooper()).idle() verifyProgressDialogVisible(false) verifyNavigationRequested(SignInFragmentDirections.showSignInScreen()) verifyUserPreferencesCleared() verifyUserNotSaved() assertThat(tosRepository.isTermsOfServiceAccepted).isFalse() } @Test fun testSignInStateChanged_onSigningIn() { fakeAuthenticationManager.setState(signingIn()) Shadows.shadowOf(Looper.getMainLooper()).idle() verifyProgressDialogVisible(true) verifyNavigationRequested() verifyUserNotSaved() assertThat(tosRepository.isTermsOfServiceAccepted).isFalse() } @Test fun testSignInStateChanged_onSignedIn_whenTosAccepted() { tosRepository.isTermsOfServiceAccepted = true fakeRemoteDataStore.setTermsOfService(Optional.of(FakeData.TERMS_OF_SERVICE)) fakeAuthenticationManager.signIn() Shadows.shadowOf(Looper.getMainLooper()).idle() verifyProgressDialogVisible(false) verifyNavigationRequested(HomeScreenFragmentDirections.showHomeScreen()) verifyUserSaved() assertThat(tosRepository.isTermsOfServiceAccepted).isTrue() } @Test fun testSignInStateChanged_onSignedIn_whenTosNotAccepted() { tosRepository.isTermsOfServiceAccepted = false fakeRemoteDataStore.setTermsOfService(Optional.of(FakeData.TERMS_OF_SERVICE)) fakeAuthenticationManager.signIn() Shadows.shadowOf(Looper.getMainLooper()).idle() verifyProgressDialogVisible(false) verifyNavigationRequested( (SignInFragmentDirections.showTermsOfService() .setTermsOfServiceText(FakeData.TERMS_OF_SERVICE.text) as NavDirections) ) verifyUserSaved() assertThat(tosRepository.isTermsOfServiceAccepted).isFalse() } @Test fun testSignInStateChanged_onSignedIn_whenTosMissing() { tosRepository.isTermsOfServiceAccepted = false fakeRemoteDataStore.setTermsOfService(Optional.empty()) fakeAuthenticationManager.signIn() Shadows.shadowOf(Looper.getMainLooper()).idle() verifyProgressDialogVisible(false) verifyNavigationRequested(HomeScreenFragmentDirections.showHomeScreen()) verifyUserSaved() assertThat(tosRepository.isTermsOfServiceAccepted).isFalse() } @Test fun testSignInStateChanged_onSignInError() { setupUserPreferences() fakeAuthenticationManager.setState(error(Exception())) Shadows.shadowOf(Looper.getMainLooper()).idle() assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo("Sign in unsuccessful") verifyProgressDialogVisible(false) verifyNavigationRequested(SignInFragmentDirections.showSignInScreen()) verifyUserPreferencesCleared() verifyUserNotSaved() assertThat(tosRepository.isTermsOfServiceAccepted).isFalse() } }
ground/src/test/java/com/google/android/ground/MainViewModelTest.kt
2534576465
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.visualization enum class DisplayDensity { COMFORTABLE, NORMAL, COMPACT, NONE }
core/src/main/java/org/hisp/dhis/android/core/visualization/DisplayDensity.kt
3757912976
package externalReceiverInLambda fun main(args: Array<String>) { val sb = StringBuilder() // EXPRESSION: run { sb.append("Hello!").toString() } // RESULT: "Hello!": Ljava/lang/String; //Breakpoint! run { sb.append("Hello!").toString() } // EXPRESSION: buildString { append(sb.toString()) } // RESULT: "Hello!": Ljava/lang/String; //Breakpoint! buildString { append(sb.toString()) } }
plugins/kotlin/jvm-debugger/test/testData/evaluation/multipleBreakpoints/externalReceiverInLambda.kt
3767613390
// "Make '<init>' internal" "false" // DISABLE-ERRORS // ACTION: Enable a trailing comma by default in the formatter // ACTION: Introduce import alias // ACTION: Make 'My' public internal class My annotation class Your(val x: <caret>My)
plugins/kotlin/idea/tests/testData/quickfix/decreaseVisibility/exposedTypeInAnnotation.kt
109658893
package com.theah64.mock_api.database import com.theah64.mock_api.models.Route import com.theah64.webengine.database.BaseTable import com.theah64.webengine.database.Connection import com.theah64.webengine.database.querybuilders.QueryBuilderException import java.sql.PreparedStatement import java.sql.SQLException import java.util.ArrayList /** * Created by theapache64 on 14/5/17. */ class Routes private constructor() : BaseTable<Route>("routes") { @Throws(SQLException::class) override fun addv3(route: Route): String { var error: String? = null var id: String? = null val query = "INSERT INTO routes (project_id, name, default_response, description, is_secure, delay,external_api_url,updated_at_in_millis,method,request_body_type,json_req_body) VALUES (?,?,?,?,?,?,?,?,?,?,?);" val con = Connection.getConnection() try { val ps0 = con.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS) ps0.setString(1, route.projectId) ps0.setString(2, route.name) ps0.setString(3, route.defaultResponse) ps0.setString(4, route.description) ps0.setBoolean(5, route.isSecure) ps0.setLong(6, route.delay) ps0.setString(7, route.externalApiUrl) ps0.setLong(8, System.currentTimeMillis()) ps0.setString(9, route.method) ps0.setString(10, route.requestBodyType) ps0.setString(11, route.jsonReqBody) ps0.executeUpdate() val rs = ps0.generatedKeys if (rs.first()) { id = rs.getString(1) } rs.close() ps0.close() route.id = id Params.instance.addParamsFromRoute(route) } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) return id!! } @Throws(SQLException::class) fun getAll(projectId: String): List<Route> { val jsonList = ArrayList<Route>() val query = "SELECT id, name,request_body_type,status_code, external_api_url FROM routes WHERE project_id = ? AND is_active = 1 ORDER BY id DESC" var error: String? = null val con = Connection.getConnection() try { val ps = con.prepareStatement(query) ps.setString(1, projectId) val rs = ps.executeQuery() if (rs.first()) { do { val id = rs.getString(BaseTable.COLUMN_ID) val route = rs.getString(BaseTable.COLUMN_NAME) val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE) val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL) val statusCode = rs.getInt(COLUMN_STATUS_CODE) jsonList.add(Route(id, projectId, route, requestBodyType, null, null, null, externalApiUrl, null, null, false, 0, -1, statusCode)) } while (rs.next()) } rs.close() ps.close() } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) return jsonList } @Throws(SQLException::class) fun getAllDetailed(projectId: String): List<Route> { var routeList: MutableList<Route> = ArrayList() val query = "SELECT r.id,r.name,r.request_body_type,r.json_req_body,r.status_code, r.updated_at_in_millis,r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE p.id = ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id;" var error: String? = null val con = Connection.getConnection() try { val ps = con.prepareStatement(query) ps.setString(1, projectId) val rs = ps.executeQuery() if (rs.first()) { routeList = ArrayList() do { val id = rs.getString(BaseTable.COLUMN_ID) val routeName = rs.getString(BaseTable.COLUMN_NAME) val response = rs.getString(COLUMN_DEFAULT_RESPONSE) val description = rs.getString(COLUMN_DESCRIPTION) val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY) val isSecure = rs.getBoolean(COLUMN_IS_SECURE) val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE) val delay = rs.getLong(COLUMN_DELAY) val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL) val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS) val method = rs.getString(COLUMN_METHOD) val statusCode = rs.getInt(COLUMN_STATUS_CODE) val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id) routeList.add(Route(id, projectId, routeName, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode)) } while (rs.next()) } rs.close() ps.close() } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) return routeList } @Throws(SQLException::class) fun getRouteFrom(packageName: String, routeName: String): Route? { var error: String? = null var route: Route? = null val query = "SELECT r.id,r.status_code, r.updated_at_in_millis,r.request_body_type,r.json_req_body, r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE p.package_name = ? AND r.name = ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id LIMIT 1;" val con = Connection.getConnection() try { val ps = con.prepareStatement(query) ps.setString(1, packageName) ps.setString(2, routeName) val rs = ps.executeQuery() if (rs.first()) { val id = rs.getString(BaseTable.COLUMN_ID) val response = rs.getString(COLUMN_DEFAULT_RESPONSE) val description = rs.getString(COLUMN_DESCRIPTION) val isSecure = rs.getBoolean(COLUMN_IS_SECURE) val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY) val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE) val delay = rs.getLong(COLUMN_DELAY) val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL) val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS) val method = rs.getString(COLUMN_METHOD) val statusCode = rs.getInt(COLUMN_STATUS_CODE) val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id) route = Route(id, null, routeName, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode) } rs.close() ps.close() } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) if (route == null) { throw SQLException("No response found for $packageName:$routeName") } return route } @Throws(SQLException::class) override fun get(projectName: String?, routeName: String?): Route? { var error: String? = null var route: Route? = null val query = "SELECT r.id, r.status_code,r.updated_at_in_millis,r.request_body_type,r.json_req_body, r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE p.name = ? AND r.name = ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id LIMIT 1;" val con = Connection.getConnection() try { val ps = con.prepareStatement(query) ps.setString(1, projectName) ps.setString(2, routeName) val rs = ps.executeQuery() if (rs.first()) { val id = rs.getString(BaseTable.COLUMN_ID) val response = rs.getString(COLUMN_DEFAULT_RESPONSE) val description = rs.getString(COLUMN_DESCRIPTION) val isSecure = rs.getBoolean(COLUMN_IS_SECURE) val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY) val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE) val delay = rs.getLong(COLUMN_DELAY) val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL) val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS) val method = rs.getString(COLUMN_METHOD) val statusCode = rs.getInt(COLUMN_STATUS_CODE) val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id) route = Route(id, null, routeName!!, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode) } rs.close() ps.close() } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) if (route == null) { throw SQLException("No response found for $projectName:$routeName") } return route } @Throws(SQLException::class) fun getRouteBy(column: String, value: String): Route { var error: String? = null var route: Route? = null val query = String.format("SELECT r.id,r.status_code,r.name,r.request_body_type, r.json_req_body, r.updated_at_in_millis,r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE r.%s = ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id LIMIT 1;", column) val con = Connection.getConnection() try { val ps = con.prepareStatement(query) ps.setString(1, value) val rs = ps.executeQuery() if (rs.first()) { val id = rs.getString(BaseTable.COLUMN_ID) val routeName = rs.getString(BaseTable.COLUMN_NAME) val response = rs.getString(COLUMN_DEFAULT_RESPONSE) val description = rs.getString(COLUMN_DESCRIPTION) val isSecure = rs.getBoolean(COLUMN_IS_SECURE) val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE) val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY) val delay = rs.getLong(COLUMN_DELAY) val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL) val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS) val method = rs.getString(COLUMN_METHOD) val statusCode = rs.getInt(COLUMN_STATUS_CODE) val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id) route = Route(id, null, routeName, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode) } rs.close() ps.close() } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) if (route == null) { throw SQLException("No response found for " + route!!) } return route } override fun update(route: Route): Boolean { var isUpdated = false val query = "UPDATE routes SET default_response = ?, description = ? , is_secure = ? , delay = ?, external_api_url = ?, updated_at_in_millis = ?, method = ?,request_body_type=?, json_req_body = ?, status_code = ? WHERE name = ? AND project_id = ?;" val con = Connection.getConnection() try { val ps = con.prepareStatement(query) val r = if (route.defaultResponse == null) get(BaseTable.COLUMN_ID, route.id!!, COLUMN_DEFAULT_RESPONSE, true) else route.defaultResponse //set ps.setString(1, r) ps.setString(2, route.description) ps.setBoolean(3, route.isSecure) ps.setLong(4, route.delay) ps.setString(5, route.externalApiUrl) ps.setLong(6, System.currentTimeMillis()) ps.setString(7, route.method) ps.setString(8, route.requestBodyType) ps.setString(9, route.jsonReqBody) ps.setInt(10, route.statusCode) // where ps.setString(11, route.name) ps.setString(12, route.projectId) Params.instance.updateParamFromRoute(route) isUpdated = ps.executeUpdate() == 1 ps.close() } catch (e: SQLException) { e.printStackTrace() } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } if (!isUpdated) { throw IllegalArgumentException("Failed to update json") } return true } @Throws(SQLException::class) fun updateBaseOGAPIURL(projectId: String, oldBaseUrl: String, newBaseUrl: String) { val query = String.format("UPDATE routes SET %s = REPLACE(%s, ?, ?) WHERE INSTR(%s, ?) > 0 AND project_id = ?;", COLUMN_EXTERNAL_API_URL, COLUMN_EXTERNAL_API_URL, COLUMN_EXTERNAL_API_URL) val con = Connection.getConnection() var error: String? = null try { val ps = con.prepareStatement(query) ps.setString(1, oldBaseUrl) ps.setString(2, newBaseUrl) ps.setString(3, oldBaseUrl) ps.setString(4, projectId) ps.executeUpdate() ps.close() } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) } @Throws(SQLException::class) fun getRouteLike(projectName: String, routeNameStarting: String): Route? { var error: String? = null var route: Route? = null val query = "SELECT r.id,r.name,r.status_code, r.updated_at_in_millis,r.request_body_type,r.json_req_body, r.method, r.description, r.is_secure, r.delay, r.default_response, external_api_url FROM routes r INNER JOIN projects p ON p.id = r.project_id WHERE p.name = ? AND r.name LIKE ? AND p.is_active = 1 AND r.is_active = 1 GROUP BY r.id LIMIT 1;" val con = Connection.getConnection() try { val ps = con.prepareStatement(query) ps.setString(1, projectName) ps.setString(2, "$routeNameStarting%") val rs = ps.executeQuery() if (rs.first()) { val id = rs.getString(BaseTable.COLUMN_ID) val routeName = rs.getString(BaseTable.COLUMN_NAME) val response = rs.getString(COLUMN_DEFAULT_RESPONSE) val description = rs.getString(COLUMN_DESCRIPTION) val isSecure = rs.getBoolean(COLUMN_IS_SECURE) val jsonReqBody = rs.getString(COLUMN_JSON_REQ_BODY) val requestBodyType = rs.getString(COLUMN_REQUEST_BODY_TYPE) val delay = rs.getLong(COLUMN_DELAY) val externalApiUrl = rs.getString(COLUMN_EXTERNAL_API_URL) val updatedInMillis = rs.getLong(COLUMN_UPDATED_AT_IN_MILLIS) val method = rs.getString(COLUMN_METHOD) val statusCode = rs.getInt(COLUMN_STATUS_CODE) val allParams = Params.instance.getAll(Params.COLUMN_ROUTE_ID, id) route = Route(id, null, routeName!!, requestBodyType, jsonReqBody, response, description, externalApiUrl, method, allParams, isSecure, delay, updatedInMillis, statusCode) } rs.close() ps.close() } catch (e: SQLException) { e.printStackTrace() error = e.message } finally { try { con.close() } catch (e: SQLException) { e.printStackTrace() } } BaseTable.manageError(error) if (route == null) { throw SQLException("No response found with starting $projectName:$routeNameStarting") } return route } companion object { const val COLUMN_ID = "id" const val COLUMN_NAME = "name" const val COLUMN_REQUEST_BODY_TYPE = "request_body_type" const val COLUMN_JSON_REQ_BODY = "json_req_body" const val COLUMN_DEFAULT_RESPONSE = "default_response" const val COLUMN_PROJECT_ID = "project_id" const val COLUMN_DESCRIPTION = "description" const val COLUMN_IS_SECURE = "is_secure" const val COLUMN_DELAY = "delay" const val COLUMN_EXTERNAL_API_URL = "external_api_url" const val COLUMN_UPDATED_AT_IN_MILLIS = "updated_at_in_millis" const val KEY_PARAMS = "params" const val COLUMN_STATUS_CODE = "status_code" const val COLUMN_METHOD = "method" val instance = Routes() } }
src/com/theah64/mock_api/database/Routes.kt
3032905022
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.ide.CopyProvider import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.EDT import com.intellij.openapi.project.Project import com.intellij.ui.SpeedSearchComparator import com.intellij.ui.TableSpeedSearch import com.intellij.ui.TableUtil import com.intellij.ui.table.JBTable import com.intellij.util.ui.UIUtil import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ActionsColumn import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.NameColumn import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeColumn import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.VersionColumn import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint import com.jetbrains.packagesearch.intellij.plugin.ui.util.onMouseMotion import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import com.jetbrains.packagesearch.intellij.plugin.util.uiStateSource import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import java.awt.Cursor import java.awt.Dimension import java.awt.KeyboardFocusManager import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.ListSelectionModel import javax.swing.event.ListSelectionListener import javax.swing.table.DefaultTableCellRenderer import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer import javax.swing.table.TableColumn import kotlin.math.roundToInt internal typealias SearchResultStateChangeListener = (PackageModel.SearchResult, NormalizedPackageVersion<*>?, PackageScope?) -> Unit @Suppress("MagicNumber") // Swing dimension constants internal class PackagesTable( private val project: Project, private val operationExecutor: OperationExecutor, private val onSearchResultStateChanged: SearchResultStateChangeListener ) : JBTable(), CopyProvider, DataProvider { private var lastSelectedDependency: UnifiedDependency? = null private val operationFactory = PackageSearchOperationFactory() private val tableModel: PackagesTableModel get() = model as PackagesTableModel var transferFocusUp: () -> Unit = { transferFocusBackward() } private val columnWeights = listOf( .5f, // Name column .2f, // Scope column .2f, // Version column .1f // Actions column ) private val nameColumn = NameColumn() private val scopeColumn = ScopeColumn { packageModel, newScope -> updatePackageScope(packageModel, newScope) } private val versionColumn = VersionColumn { packageModel, newVersion -> updatePackageVersion(packageModel, newVersion) } private val actionsColumn = ActionsColumn(project, operationExecutor = ::executeActionColumnOperations) private val actionsColumnIndex: Int private val autosizingColumnsIndices: List<Int> private var targetModules: TargetModules = TargetModules.None private var knownRepositoriesInTargetModules = KnownRepositories.InTargetModules.EMPTY val selectedPackageStateFlow = MutableStateFlow<UiPackageModel<*>?>(null) private val listSelectionListener = ListSelectionListener { val item = getSelectedTableItem() if (selectedIndex >= 0 && item != null) { TableUtil.scrollSelectionToVisible(this) updateAndRepaint() selectedPackageStateFlow.tryEmit(item.uiPackageModel) } else { selectedPackageStateFlow.tryEmit(null) } } val hasInstalledItems: Boolean get() = tableModel.items.any { it is PackagesTableItem.InstalledPackage } val firstPackageIndex: Int get() = tableModel.items.indexOfFirst { it is PackagesTableItem.InstalledPackage } var selectedIndex: Int get() = selectedRow set(value) { if (tableModel.items.isNotEmpty() && (0 until tableModel.items.count()).contains(value)) { setRowSelectionInterval(value, value) } else { clearSelection() } } init { require(columnWeights.sum() == 1.0f) { "The column weights must sum to 1.0" } model = PackagesTableModel( nameColumn = nameColumn, scopeColumn = scopeColumn, versionColumn = versionColumn, actionsColumn = actionsColumn ) val columnInfos = tableModel.columnInfos actionsColumnIndex = columnInfos.indexOf(actionsColumn) autosizingColumnsIndices = listOf( columnInfos.indexOf(scopeColumn), columnInfos.indexOf(versionColumn), actionsColumnIndex ) setTableHeader(InvisibleResizableHeader()) getTableHeader().apply { reorderingAllowed = false resizingAllowed = true } columnSelectionAllowed = false setShowGrid(false) rowHeight = 20.scaled() background = UIUtil.getTableBackground() foreground = UIUtil.getTableForeground() selectionBackground = UIUtil.getTableSelectionBackground(true) selectionForeground = UIUtil.getTableSelectionForeground(true) setExpandableItemsEnabled(false) selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION putClientProperty("terminateEditOnFocusLost", true) intercellSpacing = Dimension(0, 2) // By default, JTable uses Tab/Shift-Tab for navigation between cells; Ctrl-Tab/Ctrl-Shift-Tab allows to break out of the JTable. // In this table, we don't want to navigate between cells - so override the traversal keys by default values. setFocusTraversalKeys( KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) ) setFocusTraversalKeys( KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS) ) addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent?) { if (tableModel.rowCount > 0 && selectedRows.isEmpty()) { setRowSelectionInterval(0, 0) } } }) PackageSearchUI.overrideKeyStroke(this, "jtable:RIGHT", "RIGHT") { transferFocus() } PackageSearchUI.overrideKeyStroke(this, "jtable:ENTER", "ENTER") { transferFocus() } PackageSearchUI.overrideKeyStroke(this, "shift ENTER") { clearSelection() transferFocusUp() } selectionModel.addListSelectionListener(listSelectionListener) addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent?) { if (selectedIndex == -1) { selectedIndex = firstPackageIndex } } }) TableSpeedSearch(this) { item, _ -> if (item is PackagesTableItem<*>) { val rawIdentifier = item.packageModel.identifier.rawValue val name = item.packageModel.remoteInfo?.name?.takeIf { !it.equals(rawIdentifier, ignoreCase = true) } if (name != null) rawIdentifier + name else rawIdentifier } else { "" } }.apply { comparator = SpeedSearchComparator(false) } addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { applyColumnSizes(columnModel.totalColumnWidth, columnModel.columns.toList(), columnWeights) removeComponentListener(this) } }) onMouseMotion( onMouseMoved = { mouseEvent -> val point = mouseEvent.point val hoverColumn = columnAtPoint(point) val hoverRow = rowAtPoint(point) if (tableModel.items.isEmpty() || hoverRow < 0) { cursor = Cursor.getDefaultCursor() return@onMouseMotion } val isHoveringActionsColumn = hoverColumn == actionsColumnIndex cursor = if (isHoveringActionsColumn) Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) else Cursor.getDefaultCursor() } ) project.uiStateSource.selectedDependencyFlow.onEach { lastSelectedDependency = it } .onEach { setSelection(it) } .flowOn(Dispatchers.EDT) .launchIn(project.lifecycleScope) } private fun setSelection(lastSelectedDependencyCopy: UnifiedDependency): Boolean { val index = tableModel.items.map { it.uiPackageModel } .indexOfFirst { it is UiPackageModel.Installed && it.selectedVersion.displayName == lastSelectedDependencyCopy.coordinates.version && it.packageModel.artifactId == lastSelectedDependencyCopy.coordinates.artifactId && it.packageModel.groupId == lastSelectedDependencyCopy.coordinates.groupId && (it.selectedScope.displayName == lastSelectedDependencyCopy.scope || (it.selectedScope.displayName == "[default]" && lastSelectedDependencyCopy.scope == null)) } val indexFound = index >= 0 if (indexFound) setRowSelectionInterval(index, index) return indexFound } override fun getCellRenderer(row: Int, column: Int): TableCellRenderer = tableModel.columns.getOrNull(column)?.getRenderer(tableModel.items[row]) ?: DefaultTableCellRenderer() override fun getCellEditor(row: Int, column: Int): TableCellEditor? = tableModel.columns.getOrNull(column)?.getEditor(tableModel.items[row]) internal data class ViewModel( val items: TableItems, val onlyStable: Boolean, val targetModules: TargetModules, val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules, ) { data class TableItems( val items: List<PackagesTableItem<*>>, ) : List<PackagesTableItem<*>> by items { companion object { val EMPTY = TableItems(items = emptyList()) } } } fun display(viewModel: ViewModel) { knownRepositoriesInTargetModules = viewModel.knownRepositoriesInTargetModules targetModules = viewModel.targetModules // We need to update those immediately before setting the items, on EDT, to avoid timing issues // where the target modules or only stable flags get updated after the items data change, thus // causing issues when Swing tries to render things (e.g., targetModules doesn't match packages' usages) versionColumn.updateData(viewModel.onlyStable, viewModel.targetModules) actionsColumn.updateData( viewModel.onlyStable, viewModel.targetModules, viewModel.knownRepositoriesInTargetModules ) selectionModel.removeListSelectionListener(listSelectionListener) tableModel.items = viewModel.items // TODO size columns selectionModel.addListSelectionListener(listSelectionListener) lastSelectedDependency?.let { lastSelectedDependencyCopy -> if (setSelection(lastSelectedDependencyCopy)) { lastSelectedDependency = null } } updateAndRepaint() } override fun getData(dataId: String): Any? = when { PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this else -> null } override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun performCopy(dataContext: DataContext) { getSelectedTableItem()?.performCopy(dataContext) } override fun isCopyEnabled(dataContext: DataContext) = getSelectedTableItem()?.isCopyEnabled(dataContext) ?: false override fun isCopyVisible(dataContext: DataContext) = getSelectedTableItem()?.isCopyVisible(dataContext) ?: false private fun getSelectedTableItem(): PackagesTableItem<*>? { if (selectedIndex == -1) { return null } return tableModel.getValueAt(selectedIndex, 0) as? PackagesTableItem<*> } private fun updatePackageScope(uiPackageModel: UiPackageModel<*>, newScope: PackageScope) { when (uiPackageModel) { is UiPackageModel.Installed -> { val operations = operationFactory.createChangePackageScopeOperations( packageModel = uiPackageModel.packageModel, newScope = newScope, targetModules = targetModules, repoToInstall = null ) logDebug("PackagesTable#updatePackageScope()") { "The user has selected a new scope for ${uiPackageModel.identifier}: '$newScope'. This resulted in ${operations.size} operation(s)." } operationExecutor.executeOperations(operations) } is UiPackageModel.SearchResult -> { val selectedVersion = uiPackageModel.selectedVersion onSearchResultStateChanged(uiPackageModel.packageModel, selectedVersion, newScope) logDebug("PackagesTable#updatePackageScope()") { "The user has selected a new scope for search result ${uiPackageModel.identifier}: '$newScope'." } updateAndRepaint() } } } private fun updatePackageVersion(uiPackageModel: UiPackageModel<*>, newVersion: NormalizedPackageVersion<*>) { when (uiPackageModel) { is UiPackageModel.Installed -> { val operations = uiPackageModel.packageModel.usageInfo.flatMap { val repoToInstall = knownRepositoriesInTargetModules.repositoryToAddWhenInstallingOrUpgrading( project = project, packageModel = uiPackageModel.packageModel, selectedVersion = newVersion.originalVersion ) operationFactory.createChangePackageVersionOperations( packageModel = uiPackageModel.packageModel, newVersion = newVersion.originalVersion, targetModules = targetModules, repoToInstall = repoToInstall ) } logDebug("PackagesTable#updatePackageVersion()") { "The user has selected a new version for ${uiPackageModel.identifier}: '$newVersion'. " + "This resulted in ${operations.size} operation(s)." } operationExecutor.executeOperations(operations) } is UiPackageModel.SearchResult -> { onSearchResultStateChanged(uiPackageModel.packageModel, newVersion, uiPackageModel.selectedScope) logDebug("PackagesTable#updatePackageVersion()") { "The user has selected a new version for search result ${uiPackageModel.identifier}: '$newVersion'." } updateAndRepaint() } } } private fun executeActionColumnOperations(operations: Deferred<List<PackageSearchOperation<*>>>) { logDebug("PackagesTable#executeActionColumnOperations()") { "The user has clicked the action for a package. This resulted in many operation(s)." } operationExecutor.executeOperations(operations) } private fun applyColumnSizes(tW: Int, columns: List<TableColumn>, weights: List<Float>) { require(columnWeights.size == columns.size) { "Column weights count != columns count! We have ${columns.size} columns, ${columnWeights.size} weights" } for (column in columns) { column.preferredWidth = (weights[column.modelIndex] * tW).roundToInt() } } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTable.kt
2228532490
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.moveClassesOrPackages import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.moveClassesOrPackages.JavaMoveClassesOrPackagesHandler class KotlinAwareJavaMoveClassesOrPackagesHandler : JavaMoveClassesOrPackagesHandler() { override fun createMoveClassesOrPackagesToNewDirectoryDialog( directory: PsiDirectory, elementsToMove: Array<out PsiElement>, moveCallback: MoveCallback? ) = KotlinAwareMoveClassesOrPackagesToNewDirectoryDialog(directory, elementsToMove, moveCallback) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveClassesOrPackages/KotlinAwareJavaMoveClassesOrPackagesHandler.kt
1452429756
package org.intellij.markdown.parser.markerblocks.providers import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.MarkerProcessor import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider import org.intellij.markdown.parser.markerblocks.impl.LinkReferenceDefinitionMarkerBlock import org.intellij.markdown.parser.sequentialparsers.SequentialParser import java.util.* import kotlin.text.Regex public class LinkReferenceDefinitionProvider : MarkerBlockProvider<MarkerProcessor.StateInfo> { override fun createMarkerBlocks(pos: LookaheadText.Position, productionHolder: ProductionHolder, stateInfo: MarkerProcessor.StateInfo): List<MarkerBlock> { if (!MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints)) { return emptyList() } val matchResult = matchLinkDefinition(pos.textFromPosition) ?: return emptyList() for ((i, range) in matchResult.withIndex()) { productionHolder.addProduction(listOf(SequentialParser.Node( addToRangeAndWiden(range, pos.offset), when (i) { 0 -> MarkdownElementTypes.LINK_LABEL 1 -> MarkdownElementTypes.LINK_DESTINATION 2 -> MarkdownElementTypes.LINK_TITLE else -> throw AssertionError("There are no more than three groups in this regex") }))) } val matchLength = matchResult.last().endInclusive + 1 val endPosition = pos.nextPosition(matchLength) if (endPosition != null && !isEndOfLine(endPosition)) { return emptyList() } return listOf(LinkReferenceDefinitionMarkerBlock(stateInfo.currentConstraints, productionHolder.mark(), pos.offset + matchLength)) } override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean { return false } companion object { val WHSP = "[ \\t]*" val NOT_CHARS = { c: String -> val nonWhitespace = "(?:\\\\[$c]|[^ \\t\\n$c])" val anyChar = "(?:\\\\[$c]|[^$c\\n])" "$anyChar*(?:\\n$anyChar*$nonWhitespace$WHSP)*(?:\\n$WHSP)?" } val NONCONTROL = "(?:\\\\[\\(\\)]|[^ \\n\\t\\(\\)])" val LINK_DESTINATION = "(?:<(?:\\\\[<>]|[^<>\\n])*>|${NONCONTROL}*\\(${NONCONTROL}*\\)${NONCONTROL}*|${NONCONTROL}+)" val LINK_TITLE = "(?:\"${NOT_CHARS("\"")}\"|'${NOT_CHARS("'")}'|\\(${NOT_CHARS("\\)")}\\))" fun addToRangeAndWiden(range: IntRange, t: Int): IntRange { return IntRange(range.start + t, range.endInclusive + t + 1) } fun isEndOfLine(pos: LookaheadText.Position): Boolean { return pos.offsetInCurrentLine == -1 || pos.charsToNonWhitespace() == null } fun matchLinkDefinition(text: CharSequence): List<IntRange>? { var offset = 0 repeat(3) { if (offset < text.length && text[offset] == ' ') { offset++ } } val linkLabel = matchLinkLabel(text, offset) ?: return null offset = linkLabel.endInclusive + 1 if (offset >= text.length || text[offset] != ':') return null offset++ offset = passOneNewline(text, offset) val destination = Regex("^$LINK_DESTINATION").find(text.subSequence(offset, text.length)) ?: return null val destinationRange = IntRange(destination.range.start + offset, destination.range.endInclusive + offset) offset += destination.range.endInclusive - destination.range.start + 1 offset = passOneNewline(text, offset) val title = Regex("^$LINK_TITLE").find(text.subSequence(offset, text.length)) val result = ArrayList<IntRange>() result.add(linkLabel) result.add(destinationRange) if (title != null) { val titleRange = IntRange(title.range.start + offset, title.range.endInclusive + offset) offset += title.range.endInclusive - title.range.start + 1 while (offset < text.length && text[offset].let { it == ' ' || it == '\t' }) offset++ if (offset >= text.length || text[offset] == '\n') { result.add(titleRange) } } return result } fun matchLinkLabel(text: CharSequence, start: Int): IntRange? { var offset = start if (offset >= text.length || text[offset] != '[') { return null } offset++ var seenNonWhitespace = false for (i in 1..999) { if (offset >= text.length) return null var c = text[offset] if (c == '[' || c == ']') break if (c == '\\') { offset++ if (offset >= text.length) return null c = text[offset] } if (!c.isWhitespace()) { seenNonWhitespace = true } offset++ } if (!seenNonWhitespace || offset >= text.length || text[offset] != ']') { return null; } return start..offset } private fun passOneNewline(text: CharSequence, start: Int): Int { var offset = start while (offset < text.length && text[offset].let { it == ' ' || it == '\t' }) offset++ if (offset < text.length && text[offset] == '\n') { offset++ while (offset < text.length && text[offset].let { it == ' ' || it == '\t' }) offset++ } return offset } } }
src/org/intellij/markdown/parser/markerblocks/providers/LinkReferenceDefinitionProvider.kt
567002590
// "Create member function 'A.plusAssign'" "true" class A<T>(val n: T) fun test() { A(1) <caret>+= 2 }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/binaryOperations/plusAssignOnUserType.kt
1574569370
// PROBLEM: none // WITH_STDLIB fun test(i: Int?, m: MutableMap<String, Int>) { i ?: m.<caret>put("", 1) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replacePutWithAssignment/afterElvis.kt
2206961114
package one.two object KotlinObject { lateinit var lateinitVar<caret>iable: KotlinObject }
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/lateinit/KotlinObject.kt
1963013408
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("FoldingTestUtil") package com.intellij.codeInsight import com.intellij.openapi.editor.Editor fun Editor.assertFolded(foldedText: String, placeholder: String) { val foldingRegions = foldingModel.allFoldRegions val matchingRegion = foldingRegions.firstOrNull { it.placeholderText == placeholder && it.document.text.substring(it.startOffset, it.endOffset) == foldedText } if (matchingRegion == null) { val existingFoldingsString = foldingRegions.joinToString { "'${it.document.text.substring(it.startOffset, it.endOffset)}' -> '${it.placeholderText}'" } throw AssertionError("no folding '$foldedText' -> '$placeholder' found in $existingFoldingsString") } }
java/testFramework/src/com/intellij/codeInsight/FoldingTestUtil.kt
1990537485
package com.walterscarborough.libspacey data class FlashcardWrapper( val repetition: Int = 0, val interval: Int = 1, val easinessFactor: Float = 2.5F, val previousDate: Long, val nextDate: Long )
platforms/android/libspaceywrapper/src/main/kotlin/com/walterscarborough/libspacey/FlashcardWrapper.kt
2695072721
package net.pagejects.core.forms import com.codeborne.selenide.SelenideElement import net.pagejects.core.Element import net.pagejects.core.UserAction import net.pagejects.core.annotation.FillForm import net.pagejects.core.annotation.FormObject import net.pagejects.core.error.FillFormUserActionException import net.pagejects.core.reflaction.pageObjectName import net.pagejects.core.service.SelectorService import net.pagejects.core.service.SelenideElementService import org.openqa.selenium.By import java.lang.reflect.Method import kotlin.reflect.KClass /** * User action implementation for @[FillForm] annotation * * @author Andrey Paslavsky * @since 0.1 */ class FillFormUserAction( private val `interface`: KClass<out Any>, private val userActionMethod: Method, private val selenideElementService: SelenideElementService, private val selectorService: SelectorService ) : UserAction<Unit> { override fun perform(params: Array<out Any?>): Unit { if (params.size == 0) { throw FillFormUserActionException("Method ${userActionMethod.name} has no arguments: form object is required") } else if (params.size > 2) { throw FillFormUserActionException("Method ${userActionMethod.name} has too many arguments") } val formObject = findFormObject(params) val formObjectClass = formObject.javaClass val formObjectAnnotation = formObjectClass.getAnnotation(FormObject::class.java) val formElementName = if (formObjectAnnotation.value == FormObject.DEFAULT_NAME) { formObjectClass.simpleName } else { formObjectAnnotation.value } val element = findSelenideElementInArguments(params) ?: selenideElementService.get(`interface`.pageObjectName, formElementName) Processor(formObject, formObjectClass, `interface`.pageObjectName, formElementName, element).execute() } private fun findFormObject(params: Array<out Any?>): Any { params.forEach { if (it != null) { val javaClass = it.javaClass if (javaClass.isAnnotationPresent(FormObject::class.java)) { return it } } } throw FillFormUserActionException("Form object is not listed in arguments of the method ${userActionMethod.name} or form object is null") } private fun findSelenideElementInArguments(params: Array<out Any?>): SelenideElement? { params.forEach { if (it is Element) { return it.selenideElement } else if (it is SelenideElement) { return it } else if (it is By) { return selenideElementService.getBy(it) } else if (it is String) { return selenideElementService.get(`interface`.pageObjectName, it) } } return null } private inner class Processor( val formObject: Any, val formObjectClass: Class<Any>, val pageObjectName: String, val formElementName: String, val selenideElement: SelenideElement ) { fun execute() { formObjectClass.kotlin.formFields.forEach { try { val elementName = it.elementName val fullElementName = if (!formElementName.isBlank()) formElementName + ">" + elementName else elementName val selector = if (selectorService.contains(pageObjectName, fullElementName)) { selectorService.selector(pageObjectName, fullElementName) } else { selectorService.selector(pageObjectName, elementName) } val element = selenideElement.find(selector) val handler = FormFieldHandlers[it.formField] val value = it.getter.invoke(formObject) handler.fillValue(element, value) } catch(e: Exception) { throw FillFormUserActionException("Failed to set ${it.name} to the form", e) } } } } }
src/main/kotlin/net/pagejects/core/forms/FillFormUserAction.kt
3243828026
package co.smartreceipts.android.search.delegates import android.view.View import android.widget.ImageView import androidx.annotation.DrawableRes import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.drawable.DrawableCompat import co.smartreceipts.android.R import co.smartreceipts.android.model.Receipt import co.smartreceipts.core.sync.provider.SyncProvider import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateLayoutContainer import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.item_receipt_card.* fun receiptAdapterDelegate(itemClickedListener: (Receipt) -> Unit, syncProvider: SyncProvider) = adapterDelegateLayoutContainer<Receipt, Any>(R.layout.item_receipt_card) { itemView.setOnClickListener { itemClickedListener(item) } bind { card_menu.visibility = View.GONE title.text = item.name price.text = item.price.currencyFormattedPrice card_category.visibility = View.VISIBLE card_category.text = item.category.name if (item.hasPDF()) { setIcon(card_image, R.drawable.ic_file_black_24dp) } else if (item.hasImage() && item.file != null) { card_image.setPadding(0, 0, 0, 0) Picasso.get() .load(item.file!!) .fit() .centerCrop() .into(card_image) } else { setIcon(card_image, R.drawable.ic_receipt_white_24dp) } if (syncProvider == SyncProvider.GoogleDrive) { when { item.syncState.isSynced(SyncProvider.GoogleDrive) -> card_sync_state.setImageResource(R.drawable.ic_cloud_done_24dp) else -> card_sync_state.setImageResource(R.drawable.ic_cloud_queue_24dp) } } } } private fun setIcon(view: ImageView, @DrawableRes drawableRes: Int) { val context = view.context val drawable = ResourcesCompat.getDrawable(context.resources, drawableRes, context.getTheme()) if (drawable != null) { drawable.mutate() // hack to prevent fab icon tinting (fab has drawable with the same src) DrawableCompat.setTint(drawable, ResourcesCompat.getColor(context.resources, R.color.card_image_tint, null)) val pixelPadding = context.resources.getDimensionPixelOffset(R.dimen.card_image_padding) view.setImageDrawable(drawable) view.setPadding(pixelPadding, pixelPadding, pixelPadding, pixelPadding) } }
app/src/main/java/co/smartreceipts/android/search/delegates/ReceiptAdapterDelegate.kt
23589061
package urn.conductor import org.apache.logging.log4j.LogManager import org.reflections.Reflections import org.reflections.scanners.SubTypesScanner import org.reflections.scanners.TypeAnnotationsScanner import org.reflections.util.ConfigurationBuilder import urn.conductor.registers.CanUseReflections import urn.conductor.ssh.TransportComplexElementHandler import java.lang.reflect.Modifier import java.net.URLClassLoader import java.nio.file.Files import java.nio.file.Paths import javax.xml.bind.JAXBContext import javax.xml.bind.JAXBElement import javax.xml.bind.annotation.XmlRegistry import javax.xml.bind.annotation.XmlRootElement import javax.xml.bind.annotation.XmlSchema import javax.xml.namespace.QName class ExecutionManager(pluginsDir: String) { private val logger = LogManager.getLogger("Internal") private val attributeHandlers = HashMap<QName, AttributeHandler>() private val simpleElementHandlers = HashMap<QName, SimpleElementHandler>() private val complexElementHandlers = ElementHandlerMap() private val preloaders = ArrayList<Preloader>() private val objectFactories = HashSet<Class<*>>() val Class<*>.xmlNamespace: String? get() = this.getAnnotation(XmlRootElement::class.java)?.namespace?.takeIf { it != "##default" } ?: this.`package`?.getAnnotation(XmlSchema::class.java)?.namespace val Class<*>.xmlElementName: String? get() = this.getAnnotation(XmlRootElement::class.java)?.name init { logger.info("Scanning for plugins...") val paths = pluginsDir.let { Paths.get(it) }.let { attempt { Files.newDirectoryStream(it) } ?: error("Directory stream failed") }.use { it.filter { it.fileName.toString().endsWith(".jar") }.filterNotNull() } val classloaders = paths.map { attempt { it.toAbsolutePath().toUri().toURL() } }.filterNotNull().map { arrayOf(it) }.map(::URLClassLoader) logger.info("Found ${classloaders.size} packages...") classloaders.map { it.urLs.singleOrNull()?.toString() }.filterNotNull().forEach(logger::debug) val reflectionsConfig = ConfigurationBuilder.build(this.javaClass.classLoader, *classloaders.toTypedArray(), SubTypesScanner(), TypeAnnotationsScanner()) val reflections = Reflections(reflectionsConfig) reflections.getTypesAnnotatedWith(XmlRegistry::class.java) .forEach { objectFactories.add(it) } reflections.getSubTypesOf(ComponentRegistration::class.java).filter { it.modifiers.let { mod -> listOf(Modifier::isAbstract, Modifier::isInterface, Modifier::isPrivate, Modifier::isProtected, Modifier::isStatic) .map { it.invoke(mod) } .filter { it } .none() } }.map { attempt { it.newInstance() } }.filterNotNull().forEach { logger.debug("Found ComponentRegistration: ${it.javaClass.name}") if (it is CanUseReflections) { it.injectReflections(reflections) } it.init() it.getAttributeHandlers().forEach { attributeHandlers[it.handles] = it } it.getComplexElementHandlers().forEach { complexElementHandlers[it.handles] = it } it.getSimpleElementHandlers().forEach { simpleElementHandlers[it.handles] = it } it.getPreloaders().forEach { preloaders.add(it) } } fun logDetails(name: String, getCount: () -> Int, debugLines: () -> List<String>) { logger.info("Found ${getCount()} $name...") debugLines().sorted().forEach(logger::debug) } logger.info("Found ${attributeHandlers.size} attribute handlers...") attributeHandlers.keys .map(QName::toString) .sorted() .forEach(logger::debug) logger.info("Found ${simpleElementHandlers.size} simple element handlers...") simpleElementHandlers.keys .map(QName::toString) .sorted() .forEach(logger::debug) logger.info("Found ${complexElementHandlers.size} complex element handlers...") complexElementHandlers.keys .map { QName(it.xmlNamespace, it.xmlElementName).toString() } .sorted() .forEach(logger::debug) logger.info("Found ${preloaders.size} preloaders...") preloaders.sortedBy { it.priority } .map { "[${it.priority}] ${it.friendlyName}" } .forEach(logger::debug) } fun runHandlerFor(element: Any, engine: Engine, proceed: (Any) -> Unit) { when { element is JAXBElement<*> -> { simpleElementHandlers[element.name]?.process(element.value, engine) ?: error("Unknown handler for simple element: ${element.name}") } else -> { val handler = complexElementHandlers[element.javaClass] ?: error("Unknown handler for complex element: ${element.javaClass.name}") @Suppress("UNCHECKED_CAST") val elementAttributeHandler = handler as? CustomAttributeHandler<Any> ?: AutoAttributeHandler val attributes = elementAttributeHandler.getAttributes(element) val attributeOrder = attributes .map { this.attributeHandlers[it.key] } .filterNotNull() .sortedBy { it.priority } .map { it.handles } .toMutableList() fun processNextAttribute() { if (attributeOrder.isNotEmpty()) { val attributeName = attributeOrder.removeAt(0) val attributeHandler = attributeHandlers[attributeName] ?: error("No attribute handler found for: $attributeName") val attributeValue = attributes[attributeName] ?: "" attributeHandler.process(element, attributeValue, engine, ::processNextAttribute) } else { when (handler) { is TransportComplexElementHandler<Any> -> { val host = handler.getHostRef(element) .let(engine::interpolate) .let(engine::get) .let { it as Host } val identity = handler.getIdentityRef(element) .let(engine::interpolate) .let(engine::get) .let { it as Identity } val transport = engine.sessionProvider.getTransport(host, identity) handler.process(element, engine, proceed, transport) } is StandardComplexElementHandler<Any> -> handler.process(element, engine, proceed) else -> error("Unknown element handler type: ${handler.javaClass.name}") } } } processNextAttribute() } } } fun createJaxbContext() = this.objectFactories.toTypedArray().let { JAXBContext.newInstance(*it) } fun executePreloaders(engine: Engine) { this.preloaders.sortedBy { it.priority }.forEach { it.configure(engine) } } }
conductor-engine/src/main/java/urn/conductor/ExecutionManager.kt
1709449683
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.api typealias Arguments = List<Argument>
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/api/api.kt
4203073490
package se.barsk.park.analytics import com.google.firebase.analytics.FirebaseAnalytics /** * A share car event, sent when sharing cars from the manage cars activity. */ class ShareCarEvent(carsShared: Int) : AnalyticsEvent() { override val name: String = FirebaseAnalytics.Event.SHARE init { parameters.putInt(Param.CARS_SHARED, carsShared) parameters.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "car") } }
app/src/main/java/se/barsk/park/analytics/ShareCarEvent.kt
3126152289
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet interface VFUEntity : WorkspaceEntity { val data: String val fileProperty: VirtualFileUrl //region generated code @GeneratedCodeApiVersion(1) interface Builder : VFUEntity, ModifiableWorkspaceEntity<VFUEntity>, ObjBuilder<VFUEntity> { override var entitySource: EntitySource override var data: String override var fileProperty: VirtualFileUrl } companion object : Type<VFUEntity, Builder>() { operator fun invoke(data: String, fileProperty: VirtualFileUrl, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): VFUEntity { val builder = builder() builder.data = data builder.fileProperty = fileProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: VFUEntity, modification: VFUEntity.Builder.() -> Unit) = modifyEntity( VFUEntity.Builder::class.java, entity, modification) //endregion interface VFUWithTwoPropertiesEntity : WorkspaceEntity { val data: String val fileProperty: VirtualFileUrl val secondFileProperty: VirtualFileUrl //region generated code @GeneratedCodeApiVersion(1) interface Builder : VFUWithTwoPropertiesEntity, ModifiableWorkspaceEntity<VFUWithTwoPropertiesEntity>, ObjBuilder<VFUWithTwoPropertiesEntity> { override var entitySource: EntitySource override var data: String override var fileProperty: VirtualFileUrl override var secondFileProperty: VirtualFileUrl } companion object : Type<VFUWithTwoPropertiesEntity, Builder>() { operator fun invoke(data: String, fileProperty: VirtualFileUrl, secondFileProperty: VirtualFileUrl, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): VFUWithTwoPropertiesEntity { val builder = builder() builder.data = data builder.fileProperty = fileProperty builder.secondFileProperty = secondFileProperty builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: VFUWithTwoPropertiesEntity, modification: VFUWithTwoPropertiesEntity.Builder.() -> Unit) = modifyEntity( VFUWithTwoPropertiesEntity.Builder::class.java, entity, modification) //endregion interface NullableVFUEntity : WorkspaceEntity { val data: String val fileProperty: VirtualFileUrl? //region generated code @GeneratedCodeApiVersion(1) interface Builder : NullableVFUEntity, ModifiableWorkspaceEntity<NullableVFUEntity>, ObjBuilder<NullableVFUEntity> { override var entitySource: EntitySource override var data: String override var fileProperty: VirtualFileUrl? } companion object : Type<NullableVFUEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): NullableVFUEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: NullableVFUEntity, modification: NullableVFUEntity.Builder.() -> Unit) = modifyEntity( NullableVFUEntity.Builder::class.java, entity, modification) //endregion interface ListVFUEntity : WorkspaceEntity { val data: String val fileProperty: List<VirtualFileUrl> //region generated code @GeneratedCodeApiVersion(1) interface Builder : ListVFUEntity, ModifiableWorkspaceEntity<ListVFUEntity>, ObjBuilder<ListVFUEntity> { override var entitySource: EntitySource override var data: String override var fileProperty: MutableList<VirtualFileUrl> } companion object : Type<ListVFUEntity, Builder>() { operator fun invoke(data: String, fileProperty: List<VirtualFileUrl>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ListVFUEntity { val builder = builder() builder.data = data builder.fileProperty = fileProperty.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ListVFUEntity, modification: ListVFUEntity.Builder.() -> Unit) = modifyEntity( ListVFUEntity.Builder::class.java, entity, modification) //endregion interface SetVFUEntity : WorkspaceEntity { val data: String val fileProperty: Set<VirtualFileUrl> //region generated code @GeneratedCodeApiVersion(1) interface Builder : SetVFUEntity, ModifiableWorkspaceEntity<SetVFUEntity>, ObjBuilder<SetVFUEntity> { override var entitySource: EntitySource override var data: String override var fileProperty: MutableSet<VirtualFileUrl> } companion object : Type<SetVFUEntity, Builder>() { operator fun invoke(data: String, fileProperty: Set<VirtualFileUrl>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SetVFUEntity { val builder = builder() builder.data = data builder.fileProperty = fileProperty.toMutableWorkspaceSet() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: SetVFUEntity, modification: SetVFUEntity.Builder.() -> Unit) = modifyEntity( SetVFUEntity.Builder::class.java, entity, modification) //endregion fun MutableEntityStorage.addVFUEntity( data: String, fileUrl: String, virtualFileManager: VirtualFileUrlManager, source: EntitySource = SampleEntitySource("test") ): VFUEntity { val vfuEntity = VFUEntity(data, virtualFileManager.fromUrl(fileUrl), source) this.addEntity(vfuEntity) return vfuEntity } fun MutableEntityStorage.addVFU2Entity( data: String, fileUrl: String, secondFileUrl: String, virtualFileManager: VirtualFileUrlManager, source: EntitySource = SampleEntitySource("test") ): VFUWithTwoPropertiesEntity { val vfuWithTwoPropertiesEntity = VFUWithTwoPropertiesEntity(data, virtualFileManager.fromUrl(fileUrl), virtualFileManager.fromUrl(secondFileUrl), source) this.addEntity(vfuWithTwoPropertiesEntity) return vfuWithTwoPropertiesEntity } fun MutableEntityStorage.addNullableVFUEntity( data: String, fileUrl: String?, virtualFileManager: VirtualFileUrlManager, source: EntitySource = SampleEntitySource("test") ): NullableVFUEntity { val nullableVFUEntity = NullableVFUEntity(data, source) { this.fileProperty = fileUrl?.let { virtualFileManager.fromUrl(it) } } this.addEntity(nullableVFUEntity) return nullableVFUEntity } fun MutableEntityStorage.addListVFUEntity( data: String, fileUrl: List<String>, virtualFileManager: VirtualFileUrlManager, source: EntitySource = SampleEntitySource("test") ): ListVFUEntity { val listVFUEntity = ListVFUEntity(data, fileUrl.map { virtualFileManager.fromUrl(it) }, source) this.addEntity(listVFUEntity) return listVFUEntity }
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/vfu.kt
1351987107
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.actions import com.intellij.icons.AllIcons import com.intellij.ide.GeneralSettings import com.intellij.ide.IdeBundle import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.impl.runBlockingUnderModalProgress import com.intellij.ide.lightEdit.* import com.intellij.ide.util.PsiNavigationSupport import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.EDT import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileChooser.PathChooserDialog import com.intellij.openapi.fileChooser.impl.FileChooserUtil import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider import com.intellij.openapi.fileTypes.ex.FileTypeChooser import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame import com.intellij.openapi.wm.impl.welcomeScreen.NewWelcomeScreen import com.intellij.platform.PlatformProjectOpenProcessor import com.intellij.projectImport.ProjectOpenProcessor.Companion.getImportProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import java.nio.file.Files open class OpenFileAction : AnAction(), DumbAware, LightEditCompatible { companion object { @JvmStatic fun openFile(filePath: String, project: Project) { val file = LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath) if (file != null && file.isValid) { openFile(file, project) } } @JvmStatic fun openFile(file: VirtualFile, project: Project) { NonProjectFileWritingAccessProvider.allowWriting(listOf(file)) if (LightEdit.owns(project)) { LightEditService.getInstance().openFile(file) LightEditFeatureUsagesUtil.logFileOpen(project, LightEditFeatureUsagesUtil.OpenPlace.LightEditOpenAction) } else { PsiNavigationSupport.getInstance().createNavigatable(project, file, -1).navigate(true) } } } override fun actionPerformed(e: AnActionEvent) { val project = e.project val showFiles = project != null || PlatformProjectOpenProcessor.getInstanceIfItExists() != null val descriptor: FileChooserDescriptor = if (showFiles) ProjectOrFileChooserDescriptor() else ProjectOnlyFileChooserDescriptor() var toSelect: VirtualFile? = null if (!GeneralSettings.getInstance().defaultProjectDirectory.isNullOrEmpty()) { toSelect = VfsUtil.findFileByIoFile(File(GeneralSettings.getInstance().defaultProjectDirectory), true) } descriptor.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, toSelect == null && showFiles) FileChooser.chooseFiles(descriptor, project, toSelect ?: pathToSelect) { files -> for (file in files) { if (!descriptor.isFileSelectable(file)) { val message = IdeBundle.message("error.dir.contains.no.project", file.presentableUrl) Messages.showInfoMessage(project, message, IdeBundle.message("title.cannot.open.project")) return@chooseFiles } } runBlockingUnderModalProgress { for (file in files) { doOpenFile(project, file) } } } } internal class OnWelcomeScreen : OpenFileAction() { override fun update(e: AnActionEvent) { val presentation = e.presentation if (!NewWelcomeScreen.isNewWelcomeScreen(e)) { presentation.isEnabledAndVisible = false return } if (FlatWelcomeFrame.USE_TABBED_WELCOME_SCREEN) { presentation.icon = AllIcons.Welcome.Open presentation.selectedIcon = AllIcons.Welcome.OpenSelected presentation.text = ActionsBundle.message("action.Tabbed.WelcomeScreen.OpenProject.text") } else { presentation.icon = AllIcons.Actions.MenuOpen } } } protected val pathToSelect: VirtualFile? get() = VfsUtil.getUserHomeDir() override fun update(e: AnActionEvent) { if (NewWelcomeScreen.isNewWelcomeScreen(e)) { e.presentation.icon = AllIcons.Actions.MenuOpen } } override fun getActionUpdateThread() = ActionUpdateThread.BGT } private class ProjectOnlyFileChooserDescriptor : OpenProjectFileChooserDescriptor(true) { init { title = IdeBundle.message("title.open.project") } } // vanilla OpenProjectFileChooserDescriptor only accepts project files; this one is overridden to accept any files private class ProjectOrFileChooserDescriptor : OpenProjectFileChooserDescriptor(true) { private val myStandardDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor().withHideIgnored(false) init { title = IdeBundle.message("title.open.file.or.project") } override fun isFileVisible(file: VirtualFile, showHiddenFiles: Boolean): Boolean { return if (file.isDirectory) super.isFileVisible(file, showHiddenFiles) else myStandardDescriptor.isFileVisible(file, showHiddenFiles) } override fun isFileSelectable(file: VirtualFile?): Boolean { if (file == null) { return false } return if (file.isDirectory) super.isFileSelectable(file) else myStandardDescriptor.isFileSelectable(file) } override fun isChooseMultiple() = true } private suspend fun doOpenFile(project: Project?, file: VirtualFile) { val filePath = file.toNioPath() if (Files.isDirectory(filePath)) { @Suppress("TestOnlyProblems") ProjectUtil.openExistingDir(filePath, project) return } // try to open as a project - unless the file is an .ipr of the current one if ((project == null || file != project.projectFile) && OpenProjectFileChooserDescriptor.isProjectFile(file)) { val answer = shouldOpenNewProject(project, file) if (answer == Messages.CANCEL) { return } else if (answer == Messages.YES) { val openedProject = ProjectUtil.openOrImportAsync(filePath, OpenProjectTask { projectToClose = project }) openedProject?.let { FileChooserUtil.setLastOpenedFile(it, filePath) } return } } LightEditUtil.markUnknownFileTypeAsPlainTextIfNeeded(project, file) FileTypeChooser.getKnownFileTypeOrAssociate(file, project) ?: return if (project != null && !project.isDefault) { NonProjectFileWritingAccessProvider.allowWriting(listOf(file)) if (LightEdit.owns(project)) { LightEditService.getInstance().openFile(file) LightEditFeatureUsagesUtil.logFileOpen(project, LightEditFeatureUsagesUtil.OpenPlace.LightEditOpenAction) } else { val navigatable = PsiNavigationSupport.getInstance().createNavigatable(project, file, -1) withContext(Dispatchers.EDT) { navigatable.navigate(true) } } } else { PlatformProjectOpenProcessor.createTempProjectAndOpenFileAsync(filePath, OpenProjectTask { projectToClose = project }) } } @Messages.YesNoCancelResult private suspend fun shouldOpenNewProject(project: Project?, file: VirtualFile): Int { if (file.fileType is ProjectFileType) { return Messages.YES } val provider = getImportProvider(file) ?: return Messages.CANCEL return withContext(Dispatchers.EDT) { provider.askConfirmationForOpeningProject(file, project) } }
platform/platform-impl/src/com/intellij/ide/actions/OpenFileAction.kt
3265110208
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.structureView import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.impl.common.PsiTreeElementBase import com.intellij.navigation.ItemPresentation import com.intellij.openapi.application.runReadAction import com.intellij.openapi.project.DumbService import com.intellij.openapi.ui.Queryable import com.intellij.psi.NavigatablePsiElement import com.intellij.psi.PsiElement import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.psi.* import javax.swing.Icon import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty class KotlinStructureViewElement( override val element: NavigatablePsiElement, private val isInherited: Boolean = false ) : PsiTreeElementBase<NavigatablePsiElement>(element), Queryable, AbstractKotlinStructureViewElement { private var kotlinPresentation by AssignableLazyProperty { KotlinStructureElementPresentation(isInherited, element, countDescriptor()) } var visibility by AssignableLazyProperty { Visibility(countDescriptor()) } private set constructor(element: NavigatablePsiElement, descriptor: DeclarationDescriptor, isInherited: Boolean) : this(element, isInherited) { if (element !is KtElement) { // Avoid storing descriptor in fields kotlinPresentation = KotlinStructureElementPresentation(isInherited, element, descriptor) visibility = Visibility(descriptor) } } override val accessLevel: Int? get() = visibility.accessLevel override val isPublic: Boolean get() = visibility.isPublic override fun getPresentation(): ItemPresentation = kotlinPresentation override fun getLocationString(): String? = kotlinPresentation.locationString override fun getIcon(open: Boolean): Icon? = kotlinPresentation.getIcon(open) override fun getPresentableText(): String? = kotlinPresentation.presentableText @TestOnly override fun putInfo(info: MutableMap<in String, in String?>) { // Sanity check for API consistency assert(presentation.presentableText == presentableText) { "Two different ways of getting presentableText" } assert(presentation.locationString == locationString) { "Two different ways of getting locationString" } info["text"] = presentableText info["location"] = locationString } override fun getChildrenBase(): Collection<StructureViewTreeElement> { val children = when (val element = element) { is KtFile -> element.declarations is KtClass -> element.getStructureDeclarations() is KtClassOrObject -> element.declarations is KtFunction, is KtClassInitializer, is KtProperty -> element.collectLocalDeclarations() else -> emptyList() } return children.map { KotlinStructureViewElement(it, false) } } private fun PsiElement.collectLocalDeclarations(): List<KtDeclaration> { val result = mutableListOf<KtDeclaration>() acceptChildren(object : KtTreeVisitorVoid() { override fun visitClassOrObject(classOrObject: KtClassOrObject) { result.add(classOrObject) } override fun visitNamedFunction(function: KtNamedFunction) { result.add(function) } }) return result } private fun countDescriptor(): DeclarationDescriptor? { val element = element return when { !element.isValid -> null element !is KtDeclaration -> null element is KtAnonymousInitializer -> null else -> runReadAction { if (!DumbService.isDumb(element.getProject())) { element.resolveToDescriptorIfAny() } else null } } } class Visibility(descriptor: DeclarationDescriptor?) { private val visibility = (descriptor as? DeclarationDescriptorWithVisibility)?.visibility val isPublic: Boolean get() = visibility == DescriptorVisibilities.PUBLIC val accessLevel: Int? get() = when { visibility == DescriptorVisibilities.PUBLIC -> 1 visibility == DescriptorVisibilities.INTERNAL -> 2 visibility == DescriptorVisibilities.PROTECTED -> 3 visibility?.let { DescriptorVisibilities.isPrivate(it) } == true -> 4 else -> null } } } private class AssignableLazyProperty<in R, T : Any>(val init: () -> T) : ReadWriteProperty<R, T> { private var _value: T? = null override fun getValue(thisRef: R, property: KProperty<*>): T { return _value ?: init().also { _value = it } } override fun setValue(thisRef: R, property: KProperty<*>, value: T) { _value = value } } fun KtClassOrObject.getStructureDeclarations() = buildList { primaryConstructor?.let { add(it) } primaryConstructorParameters.filterTo(this) { it.hasValOrVar() } addAll(declarations) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structureView/KotlinStructureViewElement.kt
3591524357
package codesample.kotlin.jwtexample.security.config import codesample.kotlin.jwtexample.security.AuthExceptionsEntry import codesample.kotlin.jwtexample.security.filter.JwtAuthFilter import codesample.kotlin.jwtexample.security.service.DbUserDetailsService import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.config.BeanIds import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.builders.WebSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.CorsConfigurationSource import org.springframework.web.cors.CorsUtils import org.springframework.web.cors.UrlBasedCorsConfigurationSource import org.springframework.web.servlet.config.annotation.CorsRegistration import org.springframework.web.servlet.config.annotation.CorsRegistry import java.util.* @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( prePostEnabled = true // Allow usage of Pre and Post authorize annotations ) class SecurityConfig (val authExceptionsEntry: AuthExceptionsEntry, val dbUserDetailsService: DbUserDetailsService, val jwtAuthFilter: JwtAuthFilter) : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http .cors().configurationSource(corsConfigurationSource()) .and() // Route all auth exceptions to this class. See it's comment for more info .exceptionHandling().authenticationEntryPoint(authExceptionsEntry) .and() // Do not store any session info. We are going to authenticate each request with JWT token .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() // Add custom JWT auth filter (this is the part which actually checks and authenticate user base on JWT // token passed .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter::class.java) .authorizeRequests() .antMatchers(HttpMethod.OPTIONS,"/auth/**/**").permitAll() .antMatchers(HttpMethod.POST,"/auth/**/**").permitAll() .antMatchers("/**").authenticated() } override fun configure(web: WebSecurity) { /* This config excludes /h2-console from security filterChain, allowing everyone to access it. * Note that adding this URL to HttpSecurity config will yield no result! (And a currently do not know why... * Presumably it has something to do with H2 trying to identify you as user which can be authenticated) */ web .ignoring().antMatchers("/h2-console/**/**") .and() /* Do not use security on token endpoint. Note that this will also exclude CORS configuration * for /auth, so we have to configure CORS for this mapping specifically * which we do in WebConfig class */ .ignoring().antMatchers(HttpMethod.POST, "/auth/**/**") .and() .ignoring().antMatchers(HttpMethod.OPTIONS, "/auth/**/**") .and() .ignoring().antMatchers( HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js" ) } @Autowired fun configureGlobal(auth: AuthenticationManagerBuilder) { auth .userDetailsService<UserDetailsService>(dbUserDetailsService) .passwordEncoder(passwordEncoderBean()) } /* We need this in order to authenticate user after call to http endpoint * in SecurityController */ @Bean(BeanIds.AUTHENTICATION_MANAGER) override fun authenticationManagerBean(): AuthenticationManager { return super.authenticationManagerBean() } /* CORS config for locally deployed angular app */ @Bean fun corsConfigurationSource() : CorsConfigurationSource { val configuration = CorsConfiguration().apply { allowedOrigins = Arrays.asList("http://localhost:4200") allowedMethods = Arrays.asList("GET", "POST", "OPTIONS") /* We are going to pass token in AUTHORIZATION header */ addAllowedHeader(HttpHeaders.AUTHORIZATION) } return UrlBasedCorsConfigurationSource().apply { registerCorsConfiguration("/**", configuration) } } @Bean fun passwordEncoderBean() = BCryptPasswordEncoder() }
code-sample-angular-kotlin/code-sample-jwt-token-example/kotlin-backend/src/main/kotlin/codesample/kotlin/jwtexample/security/config/SecurityConfig.kt
915590159
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.replaceWith import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.js.descriptorUtils.getJetTypeFqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.resolve.source.getPsi class ReplaceProtectedToPublishedApiCallFix( element: KtExpression, private val classOwnerPointer: SmartPsiElementPointer<KtClass>, private val originalName: String, private val paramNames: Map<String, String>, private val newSignature: String, private val isProperty: Boolean, private val isVar: Boolean, private val isPublishedMemberAlreadyExists: Boolean ) : KotlinQuickFixAction<KtExpression>(element) { override fun getFamilyName() = KotlinBundle.message("replace.with.publishedapi.bridge.call") override fun getText() = KotlinBundle.message( "replace.with.generated.publishedapi.bridge.call.0", originalName.newNameQuoted + if (!isProperty) "(...)" else "" ) override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val psiFactory = KtPsiFactory(project) if (!isPublishedMemberAlreadyExists) { val classOwner = classOwnerPointer.element ?: return val newMember: KtDeclaration = if (isProperty) { psiFactory.createProperty( "@kotlin.PublishedApi\n" + "internal " + newSignature + "\n" + "get() = $originalName\n" + if (isVar) "set(value) { $originalName = value }" else "" ) } else { psiFactory.createFunction( "@kotlin.PublishedApi\n" + "internal " + newSignature + " = $originalName(${paramNames.keys.joinToString(", ") { it }})" ) } ShortenReferences.DEFAULT.process(classOwner.addDeclaration(newMember)) } element.replace(psiFactory.createExpression(originalName.newNameQuoted)) } companion object : KotlinSingleIntentionActionFactory() { private val signatureRenderer = IdeDescriptorRenderers.SOURCE_CODE.withOptions { defaultParameterValueRenderer = null startFromDeclarationKeyword = true withoutReturnType = true } override fun createAction(diagnostic: Diagnostic): IntentionAction? { val psiElement = diagnostic.psiElement as? KtExpression ?: return null val descriptor = DiagnosticFactory.cast( diagnostic, Errors.PROTECTED_CALL_FROM_PUBLIC_INLINE.warningFactory, Errors.PROTECTED_CALL_FROM_PUBLIC_INLINE.errorFactory ).a.let { if (it is CallableMemberDescriptor) DescriptorUtils.getDirectMember(it) else it } val isProperty = descriptor is PropertyDescriptor val isVar = descriptor is PropertyDescriptor && descriptor.isVar val signature = signatureRenderer.render(descriptor) val originalName = descriptor.name.asString() val newSignature = if (isProperty) { signature.replaceFirst("$originalName:", "${originalName.newNameQuoted}:") } else { signature.replaceFirst("$originalName(", "${originalName.newNameQuoted}(") } val paramNameAndType = descriptor.valueParameters.associate { it.name.asString() to it.type.getJetTypeFqName(false) } val classDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return null val source = classDescriptor.source.getPsi() as? KtClass ?: return null val newName = Name.identifier(originalName.newName) val contributedDescriptors = classDescriptor.unsubstitutedMemberScope.getDescriptorsFiltered { it == newName } val isPublishedMemberAlreadyExists = contributedDescriptors.filterIsInstance<CallableMemberDescriptor>().any { signatureRenderer.render(it) == newSignature } return ReplaceProtectedToPublishedApiCallFix( psiElement, source.createSmartPointer(), originalName, paramNameAndType, newSignature, isProperty, isVar, isPublishedMemberAlreadyExists ) } val String.newName: String get() = "access\$$this" val String.newNameQuoted: String get() = "`$newName`" } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceProtectedToPublishedApiCallFix.kt
3268995431
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.codelabs import com.google.samples.apps.iosched.shared.data.ConferenceDataRepository import com.google.samples.apps.iosched.shared.data.codelabs.CodelabsRepository import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage import com.google.samples.apps.iosched.shared.domain.codelabs.GetCodelabsInfoCardShownUseCase import com.google.samples.apps.iosched.shared.domain.codelabs.LoadCodelabsUseCase import com.google.samples.apps.iosched.shared.domain.codelabs.SetCodelabsInfoCardShownUseCase import com.google.samples.apps.iosched.test.data.MainCoroutineRule import com.google.samples.apps.iosched.test.util.fakes.FakeAppDatabase import com.google.samples.apps.iosched.test.util.fakes.FakeConferenceDataSource import com.google.samples.apps.iosched.test.util.fakes.FakePreferenceStorage import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test /** * Unit tests for [CodelabsViewModel] */ class CodelabsViewModelTest { // Overrides Dispatchers.Main used in Coroutines @get:Rule var coroutineRule = MainCoroutineRule() @Test fun testData_codelabInfoShown() = runTest { val prefs = FakePreferenceStorage(codelabsInfoShown = true) val viewModel = createCodelabsViewModel( getCodelabsInfoCardShownUseCase = createTestGetCodelabsInfoCardShownUseCase(prefs) ) val codelabs = viewModel.screenContent.first() // codelabs does not contain the info card assertFalse(codelabs.contains(CodelabsInformationCard)) // We have other codelabs apart from the header item assertTrue(codelabs.size > 1) } @Test fun testData_codelabInfoNotShown() = runTest { val prefs = FakePreferenceStorage(codelabsInfoShown = false) val viewModel = createCodelabsViewModel( getCodelabsInfoCardShownUseCase = createTestGetCodelabsInfoCardShownUseCase(prefs) ) val codelabs = viewModel.screenContent.first() // codelabs contain the info card assertTrue(codelabs.contains(CodelabsInformationCard)) // We have other codelabs apart from the header item and info card assertTrue(codelabs.size > 2) } @Test fun testData_dismissCodelabInfoCard() = runTest { val prefs = FakePreferenceStorage(codelabsInfoShown = false) val viewModel = createCodelabsViewModel( getCodelabsInfoCardShownUseCase = createTestGetCodelabsInfoCardShownUseCase(prefs), setCodelabsInfoCardShownUseCase = createTestSetCodelabsInfoCardShownUseCase(prefs) ) val initialCodelabs = viewModel.screenContent.first() // codelabs contain the info card assertTrue(initialCodelabs.contains(CodelabsInformationCard)) viewModel.dismissCodelabsInfoCard() val newCodelabs = viewModel.screenContent.first() assertFalse(newCodelabs.contains(CodelabsInformationCard)) } private fun createCodelabsViewModel( loadCodelabsUseCase: LoadCodelabsUseCase = createTestLoadCodelabsUseCase(), getCodelabsInfoCardShownUseCase: GetCodelabsInfoCardShownUseCase = createTestGetCodelabsInfoCardShownUseCase(), setCodelabsInfoCardShownUseCase: SetCodelabsInfoCardShownUseCase = createTestSetCodelabsInfoCardShownUseCase() ): CodelabsViewModel { return CodelabsViewModel( loadCodelabsUseCase, getCodelabsInfoCardShownUseCase, setCodelabsInfoCardShownUseCase ) } private fun createTestLoadCodelabsUseCase(): LoadCodelabsUseCase { val conferenceDataRepository = createTestConferenceDataRepository() val codelabsRepository: CodelabsRepository = createTestCodelabsRepository(conferenceDataRepository) return LoadCodelabsUseCase( codelabsRepository, coroutineRule.testDispatcher ) } private fun createTestConferenceDataRepository(): ConferenceDataRepository { return ConferenceDataRepository( remoteDataSource = FakeConferenceDataSource, boostrapDataSource = FakeConferenceDataSource, appDatabase = FakeAppDatabase() ) } private fun createTestCodelabsRepository( conferenceDataRepository: ConferenceDataRepository ): CodelabsRepository { return CodelabsRepository(conferenceDataRepository) } private fun createTestGetCodelabsInfoCardShownUseCase( preferenceStorage: PreferenceStorage = FakePreferenceStorage() ): GetCodelabsInfoCardShownUseCase { return GetCodelabsInfoCardShownUseCase( preferenceStorage, coroutineRule.testDispatcher ) } private fun createTestSetCodelabsInfoCardShownUseCase( preferenceStorage: PreferenceStorage = FakePreferenceStorage() ): SetCodelabsInfoCardShownUseCase { return SetCodelabsInfoCardShownUseCase( preferenceStorage, coroutineRule.testDispatcher ) } }
mobile/src/test/java/com/google/samples/apps/iosched/ui/codelabs/CodelabsViewModelTest.kt
2113884636
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.core.stackFrame import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.jdi.LocalVariableProxyImpl import com.intellij.debugger.jdi.StackFrameProxyImpl import com.intellij.debugger.ui.impl.watch.StackFrameDescriptorImpl import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.xdebugger.frame.XNamedValue import com.intellij.xdebugger.frame.XValueChildrenList /** * A debugger extension that allows plugins to contribute to the debugger variable view */ interface KotlinStackFrameValueContributor { fun contributeValues( frame: KotlinStackFrame, context: EvaluationContextImpl, variables: List<LocalVariableProxyImpl>, ): List<XNamedValue> companion object { @JvmStatic val EP: ExtensionPointName<KotlinStackFrameValueContributor> = ExtensionPointName.create("com.intellij.debugger.kotlinStackFrameValueContributor") } }
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/stackFrame/KotlinStackFrameValueContributor.kt
532050993
import java.util.* class Forth { companion object { private val NUMBER_PATTERN = Regex("""^-?\d+$""") } private val stack: Deque<Int> = ArrayDeque() private val customOps: MutableMap<String, String> = mutableMapOf() private val ops = mutableMapOf( "+" to { require(stack.isNotEmpty()) { "empty stack" } require(stack.size >= 2) { "only one value on the stack" } stack.push(stack.pop() + stack.pop()) }, "-" to { require(stack.isNotEmpty()) { "empty stack" } require(stack.size >= 2) { "only one value on the stack" } val tmp = stack.pop() stack.push(stack.pop() - tmp) }, "*" to { require(stack.isNotEmpty()) { "empty stack" } require(stack.size >= 2) { "only one value on the stack" } stack.push(stack.pop() * stack.pop()) }, "/" to { require(stack.isNotEmpty()) { "empty stack" } require(stack.size >= 2) { "only one value on the stack" } val tmp = stack.pop() require(tmp != 0) { "divide by zero" } stack.push(stack.pop() / tmp) }, "DUP" to { require(stack.isNotEmpty()) { "empty stack" } stack.push(stack.first) }, "DROP" to { require(stack.isNotEmpty()) { "empty stack" } stack.pop() }, "SWAP" to { require(stack.isNotEmpty()) { "empty stack" } require(stack.size >= 2) { "only one value on the stack" } val a = stack.pop() val b = stack.pop() stack.push(a) stack.push(b) }, "OVER" to { require(stack.isNotEmpty()) { "empty stack" } require(stack.size >= 2) { "only one value on the stack" } stack.push(stack.elementAt(1)) } ); fun evaluate(vararg lines: String): List<Int> { lines.forEach { line -> evaluateLine(line.uppercase()) } return stack.reversed() } private fun evaluateLine(line: String) { val tokens = line.split(" ") if (tokens.first() == ":") { val op = tokens[1] val expression = tokens.subList(2, tokens.lastIndex) require(!op.matches(NUMBER_PATTERN)) { "illegal operation" } customOps[op] = expression.joinToString(" ") { customOps.getOrDefault(it, it) } return } tokens.forEach { token -> when { token.matches(NUMBER_PATTERN) -> stack.push(token.toInt()) token in customOps.keys -> evaluateLine(customOps[token]!!) token in ops.keys -> ops[token]!!() else -> throw IllegalArgumentException("undefined operation") } } } }
exercises/practice/forth/.meta/src/reference/kotlin/Forth.kt
531668909
package org.kodein.di.compose import android.content.Context import android.content.ContextWrapper import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.platform.LocalContext import org.kodein.di.DI import org.kodein.di.DIAware /** * Access the closest [DI] container attached to the [Context] * * @throws [ClassCastException] if no [DI] container is declared in the parent [Context]s */ @Composable fun contextDI(): DI { var context: Context? = LocalContext.current while (context != null) { if (context is DIAware) return context.di context = if (context is ContextWrapper) context.baseContext else null } return (LocalContext.current.applicationContext as DIAware).di } /** * Attaches a [DI] container to the underlying [Composable] tree, using the [DI] container attached to the current [Context] (see [contextDI]). * * @param content underlying [Composable] tree that will be able to consume the [LocalDI] container */ @Composable fun withDI(content: @Composable () -> Unit) = CompositionLocalProvider(LocalDI provides contextDI()) { content() }
app/src/main/java/org/kodein/di/compose/AndroidContext.kt
4242767357
package cn.imrhj.sharetoqrcode.ui.activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class EmptyActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) finish() overridePendingTransition(0, 0) } }
app/src/main/java/cn/imrhj/sharetoqrcode/ui/activity/EmptyActivity.kt
928937683
package ch.difty.scipamato.common import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test internal class FrozenDateTimeServiceTest { private val service = FrozenDateTimeService() @Test fun gettingDateTime() { service.currentDateTime.toString() shouldBeEqualTo "2016-12-09T06:02:13" } @Test fun gettingTimestamp() { service.currentTimestamp.toString() shouldBeEqualTo "2016-12-09 06:02:13.0" } @Test fun gettingCurrentDate() { service.currentDate.toString() shouldBeEqualTo "2016-12-09" } }
common/common-test/src/test/kotlin/ch/difty/scipamato/common/FrozenDateTimeServiceTest.kt
4147536963
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.formatter.blocks.special import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.psi.codeStyle.CodeStyleSettings import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.formatter.blocks.MarkdownBlocks import org.intellij.plugins.markdown.lang.formatter.blocks.MarkdownFormattingBlock import org.intellij.plugins.markdown.util.MarkdownTextUtil import org.intellij.plugins.markdown.util.children /** * Markdown special formatting block that makes all * [MarkdownTokenTypes.TEXT] elements inside wrap. * * It is used to make markdown paragraph wrap around * right margin. So, it kind of emulates reflow formatting * for paragraphs. */ internal class MarkdownWrappingFormattingBlock( settings: CodeStyleSettings, spacing: SpacingBuilder, node: ASTNode, alignment: Alignment? = null, wrap: Wrap? = null ) : MarkdownFormattingBlock(node, settings, spacing, alignment, wrap) { companion object { private val NORMAL_WRAP = Wrap.createWrap(WrapType.NORMAL, false) } /** Number of newlines in this block's text */ val newlines: Int get() = node.text.count { it == '\n' } override fun buildChildren(): List<Block> { val filtered = MarkdownBlocks.filterFromWhitespaces(node.children()) val result = ArrayList<Block>() for (node in filtered) { if (node.elementType == MarkdownTokenTypes.TEXT) { val splits = MarkdownTextUtil.getSplitBySpacesRanges(node.text, node.textRange.startOffset) for (split in splits) { result.add(MarkdownRangedFormattingBlock(node, split, settings, spacing, alignment, NORMAL_WRAP)) } } else { result.add(MarkdownBlocks.create(node, settings, spacing) { alignment }) } } return result } }
plugins/markdown/src/org/intellij/plugins/markdown/lang/formatter/blocks/special/MarkdownWrappingFormattingBlock.kt
1061602608
package com.glodanif.bluetoothchat.ui.adapter import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import com.glodanif.bluetoothchat.R import com.glodanif.bluetoothchat.ui.viewmodel.ConversationViewModel class ConversationsAdapter : RecyclerView.Adapter<ConversationsAdapter.ConversationViewHolder>() { var clickListener: ((ConversationViewModel) -> Unit)? = null var longClickListener: ((ConversationViewModel, Boolean) -> Unit)? = null private var isConnected: Boolean = false private var conversations: ArrayList<ConversationViewModel> = ArrayList() override fun onBindViewHolder(holder: ConversationViewHolder, position: Int) { val conversation = conversations[position] holder.name.text = conversation.fullName holder.itemView.setOnClickListener { clickListener?.invoke(conversation) } holder.itemView.setOnLongClickListener { val isCurrent = isConnected && position == 0 longClickListener?.invoke(conversation, isCurrent) return@setOnLongClickListener true } if (conversation.lastMessage != null) { holder.messageContainer.visibility = View.VISIBLE holder.lastMessage.text = conversation.lastMessage } else { holder.messageContainer.visibility = View.GONE } if (conversation.lastActivityText != null) { holder.time.visibility = View.VISIBLE holder.time.text = conversation.lastActivityText } else { holder.time.visibility = View.GONE } if (conversation.notSeen > 0) { holder.notSeen.visibility = View.VISIBLE holder.notSeen.text = conversation.notSeen.toString() } else { holder.notSeen.visibility = View.GONE } val isNotConnected = !isConnected || position > 0 holder.connected.visibility = if (isNotConnected) View.GONE else View.VISIBLE val drawable = if (isNotConnected) conversation.getGrayedAvatar() else conversation.getColoredAvatar() holder.avatar.setImageDrawable(drawable) } override fun getItemCount(): Int { return conversations.size } fun setData(items: ArrayList<ConversationViewModel>, connected: String?) { conversations = items setCurrentConversation(connected) } fun setCurrentConversation(connected: String?) { isConnected = connected != null val sortedList = conversations.sortedWith( compareByDescending<ConversationViewModel> { it.address == connected } .thenByDescending { it.lastActivity }) conversations = ArrayList() conversations.addAll(sortedList) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConversationViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_conversation, parent, false) return ConversationViewHolder(view) } class ConversationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val avatar: ImageView = itemView.findViewById(R.id.iv_avatar) val name: TextView = itemView.findViewById(R.id.tv_name) val connected: ImageView = itemView.findViewById(R.id.iv_connected) val lastMessage: TextView = itemView.findViewById(R.id.tv_last_message) val time: TextView = itemView.findViewById(R.id.tv_time) val notSeen: TextView = itemView.findViewById(R.id.tv_not_seen) val messageContainer: LinearLayout = itemView.findViewById(R.id.ll_message_info) } }
app/src/main/kotlin/com/glodanif/bluetoothchat/ui/adapter/ConversationsAdapter.kt
3182369454
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.multitenant.fs import com.facebook.buck.core.path.ForwardRelativePath import com.facebook.buck.multitenant.cache.AppendOnlyBidirectionalCache import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder /** * Cache between path [String] and [ForwardRelativePath] wrapper around this [String] value. * Soft references are used. * Softly-referenced objects will be garbage-collected in a <i>globally</i> least-recently-used manner, * in response to memory demand. */ private val PATH_CACHE: Cache<String, ForwardRelativePath> = CacheBuilder.newBuilder().softValues().build() /** * Cache between [ForwardRelativePath] to unique [Int] value. */ private val PATH_TO_INDEX_CACHE = AppendOnlyBidirectionalCache<ForwardRelativePath>() object FsAgnosticPath { fun fromIndex(index: Int): ForwardRelativePath = PATH_TO_INDEX_CACHE.getByIndex(index) fun toIndex(fsAgnosticPath: ForwardRelativePath): Int = PATH_TO_INDEX_CACHE.get(fsAgnosticPath) /** * @param path must be a normalized, relative path. */ fun of(path: String): ForwardRelativePath { return PATH_CACHE.getIfPresent(path) ?: run { val pathObject = ForwardRelativePath.of(path) PATH_CACHE.put(path, pathObject) pathObject } } }
src/com/facebook/buck/multitenant/fs/FsAgnosticPath.kt
3319774368
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.minimaloboe import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.plus import kotlin.coroutines.CoroutineContext object AudioPlayer : DefaultLifecycleObserver { // Create a coroutine scope which we can launch coroutines from. This way, if our // player is ever destroyed (for example, if it was no longer a singleton and had multiple // instances) any jobs would also be cancelled. private val coroutineScope = CoroutineScope(Dispatchers.Default) + Job() private var _playerState = MutableStateFlow<PlayerState>(PlayerState.NoResultYet) val playerState = _playerState.asStateFlow() init { // Load the library containing the native code including the JNI functions. System.loadLibrary("minimaloboe") } fun setPlaybackEnabled(isEnabled: Boolean) { // Start (and stop) Oboe from a coroutine in case it blocks for too long. // If the AudioServer has died it may take several seconds to recover. // That can cause an ANR if we are starting audio from the main UI thread. coroutineScope.launch { val result = if (isEnabled) { startAudioStreamNative() } else { stopAudioStreamNative() } val newUiState = if (result == 0) { if (isEnabled){ PlayerState.Started } else { PlayerState.Stopped } } else { PlayerState.Unknown(result) } _playerState.update { newUiState } } } override fun onStop(owner: LifecycleOwner) { super.onStop(owner) setPlaybackEnabled(false) } private external fun startAudioStreamNative(): Int private external fun stopAudioStreamNative(): Int } sealed interface PlayerState { object NoResultYet : PlayerState object Started : PlayerState object Stopped : PlayerState data class Unknown(val resultCode: Int) : PlayerState }
samples/minimaloboe/src/main/java/com/example/minimaloboe/AudioPlayer.kt
712094553
/* * Copyright 2022 Benoit LETONDOR * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.benoitletondor.easybudgetapp.view.recurringexpenseadd import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.app.Activity import android.app.ProgressDialog import android.os.Bundle import android.view.MenuItem import android.widget.ArrayAdapter import androidx.activity.viewModels import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import com.benoitletondor.easybudgetapp.R import com.benoitletondor.easybudgetapp.databinding.ActivityRecurringExpenseAddBinding import com.benoitletondor.easybudgetapp.helper.* import com.benoitletondor.easybudgetapp.parameters.Parameters import com.benoitletondor.easybudgetapp.model.RecurringExpenseType import com.benoitletondor.easybudgetapp.view.DatePickerDialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import dagger.hilt.android.AndroidEntryPoint import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.* import javax.inject.Inject import kotlin.math.abs @AndroidEntryPoint class RecurringExpenseEditActivity : BaseActivity<ActivityRecurringExpenseAddBinding>() { private val viewModel: RecurringExpenseEditViewModel by viewModels() @Inject lateinit var parameters: Parameters // -------------------------------------------> override fun createBinding(): ActivityRecurringExpenseAddBinding = ActivityRecurringExpenseAddBinding.inflate(layoutInflater) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) setUpButtons() setResult(Activity.RESULT_CANCELED) if ( willAnimateActivityEnter() ) { animateActivityEnter(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { binding.descriptionEdittext.setFocus() binding.saveExpenseFab.animateFABAppearance() } }) } else { binding.descriptionEdittext.setFocus() binding.saveExpenseFab.animateFABAppearance() } lifecycleScope.launchCollect(viewModel.editTypeFlow) { (isRevenue, isEditing) -> setExpenseTypeTextViewLayout(isRevenue, isEditing) } val existingExpenseData = viewModel.existingExpenseData if (existingExpenseData != null) { setUpTextFields( existingExpenseData.title, existingExpenseData.amount, type = existingExpenseData.type ) } else { setUpTextFields(description = null, amount = null, type = null) } lifecycleScope.launchCollect(viewModel.expenseDateFlow) { date -> setUpDateButton(date) } var progressDialog: ProgressDialog? = null lifecycleScope.launchCollect(viewModel.savingStateFlow) { savingState -> when(savingState) { RecurringExpenseEditViewModel.SavingState.Idle -> { progressDialog?.dismiss() progressDialog = null } is RecurringExpenseEditViewModel.SavingState.Saving -> { progressDialog?.dismiss() progressDialog = null // Show a ProgressDialog val dialog = ProgressDialog(this) dialog.isIndeterminate = true dialog.setTitle(R.string.recurring_expense_add_loading_title) dialog.setMessage(getString(if (savingState.isRevenue) R.string.recurring_income_add_loading_message else R.string.recurring_expense_add_loading_message)) dialog.setCanceledOnTouchOutside(false) dialog.setCancelable(false) dialog.show() progressDialog = dialog } } } lifecycleScope.launchCollect(viewModel.finishFlow) { progressDialog?.dismiss() progressDialog = null setResult(Activity.RESULT_OK) finish() } lifecycleScope.launchCollect(viewModel.errorFlow) { MaterialAlertDialogBuilder(this) .setTitle(R.string.recurring_expense_add_error_title) .setMessage(getString(R.string.recurring_expense_add_error_message)) .setNegativeButton(R.string.ok) { dialog, _ -> dialog.dismiss() } .show() } lifecycleScope.launchCollect(viewModel.expenseAddBeforeInitDateEventFlow) { MaterialAlertDialogBuilder(this) .setTitle(R.string.expense_add_before_init_date_dialog_title) .setMessage(R.string.expense_add_before_init_date_dialog_description) .setPositiveButton(R.string.expense_add_before_init_date_dialog_positive_cta) { _, _ -> viewModel.onAddExpenseBeforeInitDateConfirmed( getCurrentAmount(), binding.descriptionEdittext.text.toString(), getRecurringTypeFromSpinnerSelection(binding.expenseTypeSpinner.selectedItemPosition) ) } .setNegativeButton(R.string.expense_add_before_init_date_dialog_negative_cta) { _, _ -> viewModel.onAddExpenseBeforeInitDateCancelled() } .show() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } // -----------------------------------> /** * Validate user inputs * * @return true if user inputs are ok, false otherwise */ private fun validateInputs(): Boolean { var ok = true val description = binding.descriptionEdittext.text.toString() if (description.trim { it <= ' ' }.isEmpty()) { binding.descriptionEdittext.error = resources.getString(R.string.no_description_error) ok = false } val amount = binding.amountEdittext.text.toString() if (amount.trim { it <= ' ' }.isEmpty()) { binding.amountEdittext.error = resources.getString(R.string.no_amount_error) ok = false } else { try { val value = java.lang.Double.parseDouble(amount) if (value <= 0) { binding.amountEdittext.error = resources.getString(R.string.negative_amount_error) ok = false } } catch (e: Exception) { binding.amountEdittext.error = resources.getString(R.string.invalid_amount) ok = false } } return ok } /** * Set-up revenue and payment buttons */ private fun setUpButtons() { binding.expenseTypeSwitch.setOnCheckedChangeListener { _, isChecked -> viewModel.onExpenseRevenueValueChanged(isChecked) } binding.expenseTypeTv.setOnClickListener { viewModel.onExpenseRevenueValueChanged(!binding.expenseTypeSwitch.isChecked) } binding.saveExpenseFab.setOnClickListener { if (validateInputs()) { viewModel.onSave( getCurrentAmount(), binding.descriptionEdittext.text.toString(), getRecurringTypeFromSpinnerSelection(binding.expenseTypeSpinner.selectedItemPosition), ) } } } /** * Set revenue text view layout */ private fun setExpenseTypeTextViewLayout(isRevenue: Boolean, isEditing: Boolean) { if (isRevenue) { binding.expenseTypeTv.setText(R.string.income) binding.expenseTypeTv.setTextColor(ContextCompat.getColor(this, R.color.budget_green)) binding.expenseTypeSwitch.isChecked = true if( isEditing ) { setTitle(R.string.title_activity_recurring_income_edit) } else { setTitle(R.string.title_activity_recurring_income_add) } } else { binding.expenseTypeTv.setText(R.string.payment) binding.expenseTypeTv.setTextColor(ContextCompat.getColor(this, R.color.budget_red)) binding.expenseTypeSwitch.isChecked = false if( isEditing ) { setTitle(R.string.title_activity_recurring_expense_edit) } else { setTitle(R.string.title_activity_recurring_expense_add) } } } /** * Set up text field focus behavior */ private fun setUpTextFields(description: String?, amount: Double?, type: RecurringExpenseType?) { binding.amountInputlayout.hint = resources.getString(R.string.amount, parameters.getUserCurrency().symbol) val recurringTypesString = arrayOf( getString(R.string.recurring_interval_daily), getString(R.string.recurring_interval_weekly), getString(R.string.recurring_interval_bi_weekly), getString(R.string.recurring_interval_ter_weekly), getString(R.string.recurring_interval_four_weekly), getString(R.string.recurring_interval_monthly), getString(R.string.recurring_interval_bi_monthly), getString(R.string.recurring_interval_ter_monthly), getString(R.string.recurring_interval_six_monthly), getString(R.string.recurring_interval_yearly) ) val adapter = ArrayAdapter(this, R.layout.spinner_item, recurringTypesString) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) binding.expenseTypeSpinner.adapter = adapter if( type != null ) { setSpinnerSelectionFromRecurringType(type) } else { setSpinnerSelectionFromRecurringType(RecurringExpenseType.MONTHLY) } if (description != null) { binding.descriptionEdittext.setText(description) binding.descriptionEdittext.setSelection(binding.descriptionEdittext.text?.length ?: 0) // Put focus at the end of the text } binding.amountEdittext.preventUnsupportedInputForDecimals() if (amount != null) { binding.amountEdittext.setText(CurrencyHelper.getFormattedAmountValue(abs(amount))) } } /** * Get the recurring expense type associated with the spinner selection * * @param spinnerSelectedItem index of the spinner selection * @return the corresponding expense type */ private fun getRecurringTypeFromSpinnerSelection(spinnerSelectedItem: Int): RecurringExpenseType { when (spinnerSelectedItem) { 0 -> return RecurringExpenseType.DAILY 1-> return RecurringExpenseType.WEEKLY 2 -> return RecurringExpenseType.BI_WEEKLY 3 -> return RecurringExpenseType.TER_WEEKLY 4 -> return RecurringExpenseType.FOUR_WEEKLY 5 -> return RecurringExpenseType.MONTHLY 6 -> return RecurringExpenseType.BI_MONTHLY 7 -> return RecurringExpenseType.TER_MONTHLY 8 -> return RecurringExpenseType.SIX_MONTHLY 9 -> return RecurringExpenseType.YEARLY } throw IllegalStateException("getRecurringTypeFromSpinnerSelection unable to get value for $spinnerSelectedItem") } private fun setSpinnerSelectionFromRecurringType(type: RecurringExpenseType) { val selectionIndex = when (type) { RecurringExpenseType.DAILY -> 0 RecurringExpenseType.WEEKLY -> 1 RecurringExpenseType.BI_WEEKLY -> 2 RecurringExpenseType.TER_WEEKLY -> 3 RecurringExpenseType.FOUR_WEEKLY -> 4 RecurringExpenseType.MONTHLY -> 5 RecurringExpenseType.BI_MONTHLY -> 6 RecurringExpenseType.TER_MONTHLY -> 7 RecurringExpenseType.SIX_MONTHLY -> 8 RecurringExpenseType.YEARLY -> 9 } binding.expenseTypeSpinner.setSelection(selectionIndex, false) } /** * Set up the date button */ private fun setUpDateButton(date: LocalDate) { val formatter = DateTimeFormatter.ofPattern(resources.getString(R.string.add_expense_date_format), Locale.getDefault()) binding.dateButton.text = formatter.format(date) binding.dateButton.setOnClickListener { val fragment = DatePickerDialogFragment(date) { _, year, monthOfYear, dayOfMonth -> viewModel.onDateChanged(LocalDate.of(year, monthOfYear + 1, dayOfMonth)) } fragment.show(supportFragmentManager, "datePicker") } } private fun getCurrentAmount(): Double { return java.lang.Double.parseDouble(binding.amountEdittext.text.toString()) } }
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/recurringexpenseadd/RecurringExpenseEditActivity.kt
983501722
/* * Copyright 2022 Benoit LETONDOR * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.benoitletondor.easybudgetapp.view.main import android.app.Dialog import android.app.ProgressDialog import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.res.Configuration import android.os.Bundle import com.benoitletondor.easybudgetapp.view.welcome.WelcomeActivity import com.google.android.material.snackbar.Snackbar import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.recyclerview.widget.LinearLayoutManager import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.widget.EditText import android.widget.LinearLayout import androidx.activity.viewModels import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import com.benoitletondor.easybudgetapp.R import com.benoitletondor.easybudgetapp.databinding.ActivityMainBinding import com.benoitletondor.easybudgetapp.model.Expense import com.benoitletondor.easybudgetapp.model.RecurringExpenseDeleteType import com.benoitletondor.easybudgetapp.view.main.calendar.CalendarFragment import com.benoitletondor.easybudgetapp.view.selectcurrency.SelectCurrencyFragment import com.roomorama.caldroid.CaldroidFragment import com.roomorama.caldroid.CaldroidListener import java.util.Calendar import java.util.Locale import com.benoitletondor.easybudgetapp.helper.* import com.benoitletondor.easybudgetapp.iab.INTENT_IAB_STATUS_CHANGED import com.benoitletondor.easybudgetapp.iab.Iab import com.benoitletondor.easybudgetapp.parameters.* import com.benoitletondor.easybudgetapp.view.expenseedit.ExpenseEditActivity import com.benoitletondor.easybudgetapp.view.recurringexpenseadd.RecurringExpenseEditActivity import com.benoitletondor.easybudgetapp.view.report.base.MonthlyReportBaseActivity import com.benoitletondor.easybudgetapp.view.settings.SettingsActivity import com.benoitletondor.easybudgetapp.view.settings.SettingsActivity.Companion.SHOW_BACKUP_INTENT_KEY import com.benoitletondor.easybudgetapp.view.welcome.getOnboardingStep import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.BaseTransientBottomBar import dagger.hilt.android.AndroidEntryPoint import java.time.LocalDate import java.time.format.DateTimeFormatter import javax.inject.Inject /** * Main activity containing Calendar and List of expenses * * @author Benoit LETONDOR */ @AndroidEntryPoint class MainActivity : BaseActivity<ActivityMainBinding>() { private val receiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { INTENT_EXPENSE_DELETED -> { val expense = intent.getParcelableExtra<Expense>("expense")!! viewModel.onDeleteExpenseClicked(expense) } INTENT_RECURRING_EXPENSE_DELETED -> { val expense = intent.getParcelableExtra<Expense>("expense")!! val deleteType = RecurringExpenseDeleteType.fromValue(intent.getIntExtra("deleteType", RecurringExpenseDeleteType.ALL.value))!! viewModel.onDeleteRecurringExpenseClicked(expense, deleteType) } SelectCurrencyFragment.CURRENCY_SELECTED_INTENT -> viewModel.onCurrencySelected() INTENT_SHOW_WELCOME_SCREEN -> { val startIntent = Intent(this@MainActivity, WelcomeActivity::class.java) ActivityCompat.startActivityForResult(this@MainActivity, startIntent, WELCOME_SCREEN_ACTIVITY_CODE, null) } INTENT_IAB_STATUS_CHANGED -> viewModel.onIabStatusChanged() INTENT_SHOW_CHECKED_BALANCE_CHANGED -> viewModel.onShowCheckedBalanceChanged() INTENT_LOW_MONEY_WARNING_THRESHOLD_CHANGED -> viewModel.onLowMoneyWarningThresholdChanged() } } } private lateinit var calendarFragment: CalendarFragment private lateinit var expensesViewAdapter: ExpensesRecyclerViewAdapter private val menuBackgroundAnimationDuration: Long = 150 private var menuExpandAnimation: Animation? = null private var menuCollapseAnimation: Animation? = null private var isMenuExpended = false private var lastStopDate: LocalDate? = null private val viewModel: MainViewModel by viewModels() @Inject lateinit var parameters: Parameters @Inject lateinit var iab: Iab // ------------------------------------------> override fun createBinding(): ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Launch welcome screen if needed if (parameters.getOnboardingStep() != WelcomeActivity.STEP_COMPLETED) { val startIntent = Intent(this, WelcomeActivity::class.java) ActivityCompat.startActivityForResult(this, startIntent, WELCOME_SCREEN_ACTIVITY_CODE, null) } setSupportActionBar(binding.toolbar) initCalendarFragment(savedInstanceState) initFab() initRecyclerView() registerBroadcastReceiver() performIntentActionIfAny() observeViewModel() } private fun observeViewModel() { lifecycleScope.launchCollect(viewModel.expenseDeletionSuccessEventFlow) { (deletedExpense, newBalance, maybeNewCheckecBalance) -> expensesViewAdapter.removeExpense(deletedExpense) updateBalanceDisplayForDay( expensesViewAdapter.getDate(), newBalance, maybeNewCheckecBalance ) calendarFragment.refreshView() val snackbar = Snackbar.make( binding.coordinatorLayout, if (deletedExpense.isRevenue()) R.string.income_delete_snackbar_text else R.string.expense_delete_snackbar_text, Snackbar.LENGTH_LONG ) snackbar.setAction(R.string.undo) { viewModel.onExpenseDeletionCancelled(deletedExpense) } snackbar.setActionTextColor( ContextCompat.getColor( this@MainActivity, R.color.snackbar_action_undo ) ) snackbar.duration = BaseTransientBottomBar.LENGTH_LONG snackbar.show() } lifecycleScope.launchCollect(viewModel.expenseDeletionErrorEventFlow) { MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.expense_delete_error_title) .setMessage(R.string.expense_delete_error_message) .setNegativeButton(R.string.ok) { dialog, _ -> dialog.dismiss() } .show() } var expenseDeletionDialog: ProgressDialog? = null lifecycleScope.launchCollect(viewModel.recurringExpenseDeletionProgressStateFlow) { state -> when(state) { is MainViewModel.RecurringExpenseDeleteProgressState.Deleting -> { val dialog = ProgressDialog(this@MainActivity) dialog.isIndeterminate = true dialog.setTitle(R.string.recurring_expense_delete_loading_title) dialog.setMessage(resources.getString(R.string.recurring_expense_delete_loading_message)) dialog.setCanceledOnTouchOutside(false) dialog.setCancelable(false) dialog.show() expenseDeletionDialog = dialog } MainViewModel.RecurringExpenseDeleteProgressState.Idle -> { expenseDeletionDialog?.dismiss() expenseDeletionDialog = null } } } lifecycleScope.launchCollect(viewModel.recurringExpenseDeletionEventFlow) { event -> when(event) { is MainViewModel.RecurringExpenseDeletionEvent.ErrorCantDeleteBeforeFirstOccurrence -> { MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.recurring_expense_delete_first_error_title) .setMessage(R.string.recurring_expense_delete_first_error_message) .setNegativeButton(R.string.ok, null) .show() } is MainViewModel.RecurringExpenseDeletionEvent.ErrorIO -> { showGenericRecurringDeleteErrorDialog() } is MainViewModel.RecurringExpenseDeletionEvent.ErrorRecurringExpenseDeleteNotAssociated -> { showGenericRecurringDeleteErrorDialog() } is MainViewModel.RecurringExpenseDeletionEvent.Success -> { val snackbar = Snackbar.make( binding.coordinatorLayout, R.string.recurring_expense_delete_success_message, Snackbar.LENGTH_LONG ) snackbar.setAction(R.string.undo) { viewModel.onRestoreRecurringExpenseClicked( event.recurringExpense, event.restoreRecurring, event.expensesToRestore ) } snackbar.setActionTextColor( ContextCompat.getColor( this@MainActivity, R.color.snackbar_action_undo ) ) snackbar.duration = BaseTransientBottomBar.LENGTH_LONG snackbar.show() } } } var expenseRestoreDialog: Dialog? = null lifecycleScope.launchCollect(viewModel.recurringExpenseRestoreProgressStateFlow) { state -> when(state) { MainViewModel.RecurringExpenseRestoreProgressState.Idle -> { expenseRestoreDialog?.dismiss() expenseRestoreDialog = null } is MainViewModel.RecurringExpenseRestoreProgressState.Restoring -> { val dialog = ProgressDialog(this@MainActivity) dialog.isIndeterminate = true dialog.setTitle(R.string.recurring_expense_restoring_loading_title) dialog.setMessage(resources.getString(R.string.recurring_expense_restoring_loading_message)) dialog.setCanceledOnTouchOutside(false) dialog.setCancelable(false) dialog.show() expenseRestoreDialog = dialog } } } lifecycleScope.launchCollect(viewModel.recurringExpenseRestoreEventFlow) { event -> when(event) { is MainViewModel.RecurringExpenseRestoreEvent.ErrorIO -> { MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.recurring_expense_restore_error_title) .setMessage(resources.getString(R.string.recurring_expense_restore_error_message)) .setNegativeButton(R.string.ok) { dialog, _ -> dialog.dismiss() } .show() } is MainViewModel.RecurringExpenseRestoreEvent.Success -> { Snackbar.make( binding.coordinatorLayout, R.string.recurring_expense_restored_success_message, Snackbar.LENGTH_LONG ).show() } } } lifecycleScope.launchCollect(viewModel.startCurrentBalanceEditorEventFlow) { currentBalance -> val dialogView = layoutInflater.inflate(R.layout.dialog_adjust_balance, null) val amountEditText = dialogView.findViewById<EditText>(R.id.balance_amount) amountEditText.setText( if (currentBalance == 0.0) "0" else CurrencyHelper.getFormattedAmountValue( currentBalance ) ) amountEditText.preventUnsupportedInputForDecimals() amountEditText.setSelection(amountEditText.text.length) // Put focus at the end of the text val builder = MaterialAlertDialogBuilder(this) builder.setTitle(R.string.adjust_balance_title) builder.setMessage(R.string.adjust_balance_message) builder.setView(dialogView) builder.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() } builder.setPositiveButton(R.string.ok) { dialog, _ -> try { val stringValue = amountEditText.text.toString() if (stringValue.isNotBlank()) { val newBalance = java.lang.Double.valueOf(stringValue) viewModel.onNewBalanceSelected( newBalance, getString(R.string.adjust_balance_expense_title) ) } } catch (e: Exception) { Logger.error("Error parsing new balance", e) } dialog.dismiss() } val dialog = builder.show() // Directly show keyboard when the dialog pops amountEditText.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> // Check if the device doesn't have a physical keyboard if (hasFocus && resources.configuration.keyboard == Configuration.KEYBOARD_NOKEYS) { dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) } } } lifecycleScope.launchCollect(viewModel.currentBalanceEditingErrorEventFlow) { MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.adjust_balance_error_title) .setMessage(R.string.adjust_balance_error_message) .setNegativeButton(R.string.ok) { dialog1, _ -> dialog1.dismiss() } .show() } lifecycleScope.launchCollect(viewModel.currentBalanceEditedEventFlow) { (expense, diff, newBalance) -> //Show snackbar val snackbar = Snackbar.make( binding.coordinatorLayout, resources.getString( R.string.adjust_balance_snackbar_text, CurrencyHelper.getFormattedCurrencyString(parameters, newBalance) ), Snackbar.LENGTH_LONG ) snackbar.setAction(R.string.undo) { viewModel.onCurrentBalanceEditedCancelled(expense, diff) } snackbar.setActionTextColor( ContextCompat.getColor( this@MainActivity, R.color.snackbar_action_undo ) ) snackbar.duration = BaseTransientBottomBar.LENGTH_LONG snackbar.show() } lifecycleScope.launchCollect(viewModel.currentBalanceRestoringErrorEventFlow) { MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.adjust_balance_error_title) .setMessage(R.string.adjust_balance_error_message) .setNegativeButton(R.string.ok) { dialog1, _ -> dialog1.dismiss() } .show() } lifecycleScope.launchCollect(viewModel.premiumStatusFlow) { invalidateOptionsMenu() } lifecycleScope.launchCollect(viewModel.selectedDateDataFlow) { (date, balance, maybeCheckedBalance, expenses) -> refreshAllForDate(date, balance, maybeCheckedBalance, expenses) } lifecycleScope.launchCollect(viewModel.refreshDatesFlow) { calendarFragment.refreshView() } lifecycleScope.launchCollect(viewModel.expenseCheckedErrorEventFlow) { exception -> MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.expense_check_error_title) .setMessage( getString( R.string.expense_check_error_message, exception.localizedMessage ) ) .setNegativeButton(R.string.ok) { dialog2, _ -> dialog2.dismiss() } .show() } lifecycleScope.launchCollect(viewModel.showGoToCurrentMonthButtonStateFlow) { invalidateOptionsMenu() } lifecycleScope.launchCollect(viewModel.goBackToCurrentMonthEventFlow) { calendarFragment.goToCurrentMonth() } lifecycleScope.launchCollect(viewModel.confirmCheckAllPastEntriesEventFlow) { MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.check_all_past_expences_title) .setMessage(getString(R.string.check_all_past_expences_message)) .setPositiveButton(R.string.check_all_past_expences_confirm_cta) { dialog2, _ -> viewModel.onCheckAllPastEntriesConfirmPressed() dialog2.dismiss() } .setNegativeButton(android.R.string.cancel) { dialog2, _ -> dialog2.dismiss() } .show() } lifecycleScope.launchCollect(viewModel.checkAllPastEntriesErrorEventFlow) { error -> MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.check_all_past_expences_error_title) .setMessage( getString( R.string.check_all_past_expences_error_message, error.localizedMessage ) ) .setNegativeButton(R.string.ok) { dialog2, _ -> dialog2.dismiss() } .show() } } private fun performIntentActionIfAny() { if (intent != null) { openSettingsIfNeeded(intent) openMonthlyReportIfNeeded(intent) openPremiumIfNeeded(intent) openAddExpenseIfNeeded(intent) openAddRecurringExpenseIfNeeded(intent) openSettingsForBackupIfNeeded(intent) } } private fun registerBroadcastReceiver() { // Register receiver val filter = IntentFilter() filter.addAction(INTENT_EXPENSE_DELETED) filter.addAction(INTENT_RECURRING_EXPENSE_DELETED) filter.addAction(SelectCurrencyFragment.CURRENCY_SELECTED_INTENT) filter.addAction(INTENT_SHOW_WELCOME_SCREEN) filter.addAction(Intent.ACTION_VIEW) filter.addAction(INTENT_IAB_STATUS_CHANGED) filter.addAction(INTENT_SHOW_CHECKED_BALANCE_CHANGED) filter.addAction(INTENT_LOW_MONEY_WARNING_THRESHOLD_CHANGED) LocalBroadcastManager.getInstance(applicationContext).registerReceiver(receiver, filter) } override fun onStart() { super.onStart() // If the last stop happened yesterday (or another day), set and refresh to the current date if (lastStopDate != null) { if (LocalDate.now() != lastStopDate) { viewModel.onDayChanged() } lastStopDate = null } } override fun onStop() { lastStopDate = LocalDate.now() super.onStop() } override fun onDestroy() { LocalBroadcastManager.getInstance(applicationContext).unregisterReceiver(receiver) super.onDestroy() } override fun onSaveInstanceState(outState: Bundle) { calendarFragment.saveStatesToKey(outState, CALENDAR_SAVED_STATE) super.onSaveInstanceState(outState) } @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == ADD_EXPENSE_ACTIVITY_CODE || requestCode == MANAGE_RECURRING_EXPENSE_ACTIVITY_CODE) { if (resultCode == RESULT_OK) { viewModel.onExpenseAdded() } } else if (requestCode == WELCOME_SCREEN_ACTIVITY_CODE) { if (resultCode == RESULT_OK) { viewModel.onWelcomeScreenFinished() } else if (resultCode == RESULT_CANCELED) { finish() // Finish activity if welcome screen is finish via back button } } else if (requestCode == SETTINGS_SCREEN_ACTIVITY_CODE) { calendarFragment.setFirstDayOfWeek(parameters.getCaldroidFirstDayOfWeek()) } } @Deprecated("Deprecated in Java") override fun onBackPressed() { /*if ( menu.isExpanded) { menu.collapse() } else {*/ super.onBackPressed() //} } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) if (intent == null) { return } openSettingsIfNeeded(intent) openMonthlyReportIfNeeded(intent) openPremiumIfNeeded(intent) openAddExpenseIfNeeded(intent) openAddRecurringExpenseIfNeeded(intent) openSettingsForBackupIfNeeded(intent) } // ------------------------------------------> override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) // Remove monthly report for non premium users if ( !viewModel.premiumStatusFlow.value ) { menu.removeItem(R.id.action_monthly_report) menu.removeItem(R.id.action_check_all_past_entries) } else if ( !parameters.hasUserSawMonthlyReportHint() ) { binding.monthlyReportHint.visibility = View.VISIBLE binding.monthlyReportHintButton.setOnClickListener { binding.monthlyReportHint.visibility = View.GONE parameters.setUserSawMonthlyReportHint() } } // Remove back to today button if needed if (!viewModel.showGoToCurrentMonthButtonStateFlow.value) { menu.removeItem(R.id.action_go_to_current_month) } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_settings -> { val startIntent = Intent(this, SettingsActivity::class.java) ActivityCompat.startActivityForResult(this@MainActivity, startIntent, SETTINGS_SCREEN_ACTIVITY_CODE, null) return true } R.id.action_balance -> { viewModel.onAdjustCurrentBalanceClicked() return true } R.id.action_monthly_report -> { val startIntent = Intent(this, MonthlyReportBaseActivity::class.java) ActivityCompat.startActivity(this@MainActivity, startIntent, null) return true } R.id.action_go_to_current_month -> { viewModel.onGoBackToCurrentMonthButtonPressed() return true } R.id.action_check_all_past_entries -> { viewModel.onCheckAllPastEntriesPressed() return true } else -> return super.onOptionsItemSelected(item) } } // ------------------------------------------> /** * Update the balance for the given day * TODO optimization */ private fun updateBalanceDisplayForDay(day: LocalDate, balance: Double, maybeCheckedBalance: Double?) { val format = DateTimeFormatter.ofPattern(resources.getString(R.string.account_balance_date_format), Locale.getDefault()) var formatted = resources.getString(R.string.account_balance_format, format.format(day)) // FIXME it's ugly!! if (formatted.endsWith(".:")) { formatted = formatted.substring(0, formatted.length - 2) + ":" // Remove . at the end of the month (ex: nov.: -> nov:) } else if (formatted.endsWith(". :")) { formatted = formatted.substring(0, formatted.length - 3) + " :" // Remove . at the end of the month (ex: nov. : -> nov :) } binding.budgetLine.text = formatted binding.budgetLineAmount.text = if (maybeCheckedBalance != null ) { resources.getString( R.string.account_balance_checked_format, CurrencyHelper.getFormattedCurrencyString(parameters, balance), CurrencyHelper.getFormattedCurrencyString(parameters, maybeCheckedBalance), ) } else { CurrencyHelper.getFormattedCurrencyString(parameters, balance) } binding.budgetLineAmount.setTextColor(ContextCompat.getColor(this, when { balance <= 0 -> R.color.budget_red balance < parameters.getLowMoneyWarningAmount() -> R.color.budget_orange else -> R.color.budget_green })) } /** * Open the settings activity if the given intent contains the [.INTENT_REDIRECT_TO_SETTINGS_EXTRA] * extra. */ private fun openSettingsIfNeeded(intent: Intent) { if (intent.getBooleanExtra(INTENT_REDIRECT_TO_SETTINGS_EXTRA, false)) { val startIntent = Intent(this, SettingsActivity::class.java) ActivityCompat.startActivityForResult(this@MainActivity, startIntent, SETTINGS_SCREEN_ACTIVITY_CODE, null) } } /** * Open the settings activity to display backup options if the given intent contains the * [.INTENT_REDIRECT_TO_SETTINGS_FOR_BACKUP_EXTRA] extra. */ private fun openSettingsForBackupIfNeeded(intent: Intent) { if( intent.getBooleanExtra(INTENT_REDIRECT_TO_SETTINGS_FOR_BACKUP_EXTRA, false) ) { val startIntent = Intent(this, SettingsActivity::class.java).apply { putExtra(SHOW_BACKUP_INTENT_KEY, true) } ActivityCompat.startActivityForResult(this@MainActivity, startIntent, SETTINGS_SCREEN_ACTIVITY_CODE, null) } } /** * Open the monthly report activity if the given intent contains the monthly uri part. * * @param intent */ private fun openMonthlyReportIfNeeded(intent: Intent) { try { val data = intent.data if (data != null && "true" == data.getQueryParameter("monthly")) { val startIntent = Intent(this, MonthlyReportBaseActivity::class.java) startIntent.putExtra(MonthlyReportBaseActivity.FROM_NOTIFICATION_EXTRA, true) ActivityCompat.startActivity(this@MainActivity, startIntent, null) } } catch (e: Exception) { Logger.error("Error while opening report activity", e) } } /** * Open the premium screen if the given intent contains the [.INTENT_REDIRECT_TO_PREMIUM_EXTRA] * extra. * * @param intent */ private fun openPremiumIfNeeded(intent: Intent) { if (intent.getBooleanExtra(INTENT_REDIRECT_TO_PREMIUM_EXTRA, false)) { val startIntent = Intent(this, SettingsActivity::class.java) startIntent.putExtra(SettingsActivity.SHOW_PREMIUM_INTENT_KEY, true) ActivityCompat.startActivityForResult(this, startIntent, SETTINGS_SCREEN_ACTIVITY_CODE, null) } } /** * Open the add expense screen if the given intent contains the [.INTENT_SHOW_ADD_EXPENSE] * extra. * * @param intent */ private fun openAddExpenseIfNeeded(intent: Intent) { if (intent.getBooleanExtra(INTENT_SHOW_ADD_EXPENSE, false)) { val startIntent = Intent(this, ExpenseEditActivity::class.java) startIntent.putExtra("date", LocalDate.now().toEpochDay()) ActivityCompat.startActivityForResult(this, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null) } } /** * Open the add recurring expense screen if the given intent contains the [.INTENT_SHOW_ADD_RECURRING_EXPENSE] * extra. * * @param intent */ private fun openAddRecurringExpenseIfNeeded(intent: Intent) { if (intent.getBooleanExtra(INTENT_SHOW_ADD_RECURRING_EXPENSE, false)) { val startIntent = Intent(this, RecurringExpenseEditActivity::class.java) startIntent.putExtra("dateStart", LocalDate.now().toEpochDay()) ActivityCompat.startActivityForResult(this, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null) } } // ------------------------------------------> private fun initCalendarFragment(savedInstanceState: Bundle?) { calendarFragment = CalendarFragment() if (savedInstanceState != null && savedInstanceState.containsKey(CALENDAR_SAVED_STATE) ) { calendarFragment.restoreStatesFromKey(savedInstanceState, CALENDAR_SAVED_STATE) } else { val args = Bundle() val cal = Calendar.getInstance() args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1) args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR)) args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true) args.putBoolean(CaldroidFragment.SIX_WEEKS_IN_CALENDAR, false) args.putInt(CaldroidFragment.START_DAY_OF_WEEK, parameters.getCaldroidFirstDayOfWeek()) args.putBoolean(CaldroidFragment.ENABLE_CLICK_ON_DISABLED_DATES, false) args.putInt(CaldroidFragment.THEME_RESOURCE, R.style.caldroid_style) calendarFragment.arguments = args calendarFragment.setMinDate((parameters.getInitDate() ?: LocalDate.now()).computeCalendarMinDateFromInitDate()) } val listener = object : CaldroidListener() { override fun onSelectDate(date: LocalDate, view: View) { viewModel.onSelectDate(date) } override fun onLongClickDate(date: LocalDate, view: View?) // Add expense on long press { val startIntent = Intent(this@MainActivity, ExpenseEditActivity::class.java) startIntent.putExtra("date", date.toEpochDay()) // Get the absolute location on window for Y value val viewLocation = IntArray(2) view!!.getLocationInWindow(viewLocation) startIntent.putExtra(ANIMATE_TRANSITION_KEY, true) startIntent.putExtra(CENTER_X_KEY, view.x.toInt() + view.width / 2) startIntent.putExtra(CENTER_Y_KEY, viewLocation[1] + view.height / 2) ActivityCompat.startActivityForResult(this@MainActivity, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null) } override fun onChangeMonth(month: Int, year: Int) { viewModel.onMonthChanged(month - 1, year) } override fun onCaldroidViewCreated() { val viewPager = calendarFragment.dateViewPager val leftButton = calendarFragment.leftArrowButton val rightButton = calendarFragment.rightArrowButton val textView = calendarFragment.monthTitleTextView val weekDayGreedView = calendarFragment.weekdayGridView val topLayout = [email protected]<LinearLayout>(com.caldroid.R.id.calendar_title_view) val params = textView.layoutParams as LinearLayout.LayoutParams params.gravity = Gravity.TOP params.setMargins(0, 0, 0, [email protected](R.dimen.calendar_month_text_padding_bottom)) textView.layoutParams = params topLayout.setPadding(0, [email protected](R.dimen.calendar_month_padding_top), 0, [email protected](R.dimen.calendar_month_padding_bottom)) val leftButtonParams = leftButton.layoutParams as LinearLayout.LayoutParams leftButtonParams.setMargins([email protected](R.dimen.calendar_month_buttons_margin), 0, 0, 0) leftButton.layoutParams = leftButtonParams val rightButtonParams = rightButton.layoutParams as LinearLayout.LayoutParams rightButtonParams.setMargins(0, 0, [email protected](R.dimen.calendar_month_buttons_margin), 0) rightButton.layoutParams = rightButtonParams textView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_header_month_color)) topLayout.setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_header_background)) leftButton.text = "<" leftButton.textSize = 25f leftButton.gravity = Gravity.CENTER leftButton.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_month_button_color)) leftButton.setBackgroundResource(R.drawable.calendar_month_switcher_button_drawable) rightButton.text = ">" rightButton.textSize = 25f rightButton.gravity = Gravity.CENTER rightButton.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_month_button_color)) rightButton.setBackgroundResource(R.drawable.calendar_month_switcher_button_drawable) weekDayGreedView.setPadding(0, [email protected](R.dimen.calendar_weekdays_padding_top), 0, [email protected](R.dimen.calendar_weekdays_padding_bottom)) viewPager.setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_background)) (viewPager.parent as View?)?.setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.calendar_background)) } } calendarFragment.caldroidListener = listener val t = supportFragmentManager.beginTransaction() t.replace(R.id.calendarView, calendarFragment) t.commit() } private fun initFab() { isMenuExpended = binding.fabChoicesBackground.visibility == View.VISIBLE binding.fabChoicesBackground.setOnClickListener { collapseMenu() } binding.fabChoices.setOnClickListener { if (isMenuExpended) { collapseMenu() } else { expandMenu() } } listOf(binding.fabNewExpense, binding.fabNewExpenseText).forEach { it.setOnClickListener { val startIntent = Intent(this@MainActivity, ExpenseEditActivity::class.java) startIntent.putExtra("date", calendarFragment.getSelectedDate().toEpochDay()) startIntent.putExtra(ANIMATE_TRANSITION_KEY, true) ActivityCompat.startActivityForResult(this@MainActivity, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null) collapseMenu() } } listOf(binding.fabNewRecurringExpense, binding.fabNewRecurringExpenseText).forEach { it.setOnClickListener { val startIntent = Intent(this@MainActivity, RecurringExpenseEditActivity::class.java) startIntent.putExtra("dateStart", calendarFragment.getSelectedDate().toEpochDay()) startIntent.putExtra(ANIMATE_TRANSITION_KEY, true) ActivityCompat.startActivityForResult(this@MainActivity, startIntent, ADD_EXPENSE_ACTIVITY_CODE, null) collapseMenu() } } } private fun initRecyclerView() { binding.expensesRecyclerView.layoutManager = LinearLayoutManager(this) expensesViewAdapter = ExpensesRecyclerViewAdapter(this, parameters, iab, LocalDate.now()) { expense, checked -> viewModel.onExpenseChecked(expense, checked) } binding.expensesRecyclerView.adapter = expensesViewAdapter } private fun collapseMenu() { isMenuExpended = false menuExpandAnimation?.cancel() menuCollapseAnimation?.cancel() menuCollapseAnimation = AlphaAnimation(1.0f, 0.0f) menuCollapseAnimation?.duration = menuBackgroundAnimationDuration menuCollapseAnimation?.fillAfter = true menuCollapseAnimation?.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { } override fun onAnimationEnd(animation: Animation) { binding.fabChoicesBackground.visibility = View.GONE binding.fabChoicesBackground.isClickable = false binding.fabNewRecurringExpenseContainer.isVisible = false binding.fabNewExpenseContainer.isVisible = false } override fun onAnimationRepeat(animation: Animation) { } }) binding.fabChoicesBackground.startAnimation(menuCollapseAnimation) binding.fabNewRecurringExpense.startAnimation(menuCollapseAnimation) binding.fabNewRecurringExpenseText.startAnimation(menuCollapseAnimation) binding.fabNewExpense.startAnimation(menuCollapseAnimation) binding.fabNewExpenseText.startAnimation(menuCollapseAnimation) } private fun expandMenu() { isMenuExpended = true menuExpandAnimation?.cancel() menuCollapseAnimation?.cancel() menuExpandAnimation = AlphaAnimation(0.0f, 1.0f) menuExpandAnimation?.duration = menuBackgroundAnimationDuration menuExpandAnimation?.fillAfter = true menuExpandAnimation?.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { binding.fabChoicesBackground.visibility = View.VISIBLE binding.fabChoicesBackground.isClickable = true binding.fabNewRecurringExpenseContainer.isVisible = true binding.fabNewExpenseContainer.isVisible = true } override fun onAnimationEnd(animation: Animation) { } override fun onAnimationRepeat(animation: Animation) { } }) binding.fabChoicesBackground.startAnimation(menuExpandAnimation) binding.fabNewRecurringExpense.startAnimation(menuExpandAnimation) binding.fabNewRecurringExpenseText.startAnimation(menuExpandAnimation) binding.fabNewExpense.startAnimation(menuExpandAnimation) binding.fabNewExpenseText.startAnimation(menuExpandAnimation) } private fun refreshRecyclerViewForDate(date: LocalDate, expenses: List<Expense>) { expensesViewAdapter.setDate(date, expenses) if ( expenses.isNotEmpty() ) { binding.expensesRecyclerView.visibility = View.VISIBLE binding.emptyExpensesRecyclerViewPlaceholder.visibility = View.GONE } else { binding.expensesRecyclerView.visibility = View.GONE binding.emptyExpensesRecyclerViewPlaceholder.visibility = View.VISIBLE } } private fun refreshAllForDate(date: LocalDate, balance: Double, maybeCheckedBalance: Double?, expenses: List<Expense>) { refreshRecyclerViewForDate(date, expenses) updateBalanceDisplayForDay(date, balance, maybeCheckedBalance) calendarFragment.setSelectedDate(date) calendarFragment.refreshView() } /** * Show a generic alert dialog telling the user an error occured while deleting recurring expense */ private fun showGenericRecurringDeleteErrorDialog() { MaterialAlertDialogBuilder(this@MainActivity) .setTitle(R.string.recurring_expense_delete_error_title) .setMessage(R.string.recurring_expense_delete_error_message) .setNegativeButton(R.string.ok) { dialog, _ -> dialog.dismiss() } .show() } companion object { const val ADD_EXPENSE_ACTIVITY_CODE = 101 const val MANAGE_RECURRING_EXPENSE_ACTIVITY_CODE = 102 const val WELCOME_SCREEN_ACTIVITY_CODE = 103 const val SETTINGS_SCREEN_ACTIVITY_CODE = 104 const val INTENT_EXPENSE_DELETED = "intent.expense.deleted" const val INTENT_RECURRING_EXPENSE_DELETED = "intent.expense.monthly.deleted" const val INTENT_SHOW_WELCOME_SCREEN = "intent.welcomscreen.show" const val INTENT_SHOW_ADD_EXPENSE = "intent.addexpense.show" const val INTENT_SHOW_ADD_RECURRING_EXPENSE = "intent.addrecurringexpense.show" const val INTENT_SHOW_CHECKED_BALANCE_CHANGED = "intent.showcheckedbalance.changed" const val INTENT_LOW_MONEY_WARNING_THRESHOLD_CHANGED = "intent.lowmoneywarningthreshold.changed" const val INTENT_REDIRECT_TO_PREMIUM_EXTRA = "intent.extra.premiumshow" const val INTENT_REDIRECT_TO_SETTINGS_EXTRA = "intent.extra.redirecttosettings" const val INTENT_REDIRECT_TO_SETTINGS_FOR_BACKUP_EXTRA = "intent.extra.redirecttosettingsforbackup" const val ANIMATE_TRANSITION_KEY = "animate" const val CENTER_X_KEY = "centerX" const val CENTER_Y_KEY = "centerY" private const val CALENDAR_SAVED_STATE = "calendar_saved_state" } }
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/main/MainActivity.kt
2232268206
package com.dbflow5.coroutines import com.dbflow5.config.DBFlowDatabase import com.dbflow5.query.Queriable import com.dbflow5.structure.delete import com.dbflow5.structure.insert import com.dbflow5.structure.load import com.dbflow5.structure.save import com.dbflow5.structure.update import com.dbflow5.transaction.FastStoreModelTransaction import com.dbflow5.transaction.Transaction import com.dbflow5.transaction.fastDelete import com.dbflow5.transaction.fastInsert import com.dbflow5.transaction.fastSave import com.dbflow5.transaction.fastUpdate import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException /** * Turns this [Transaction.Builder] into a [Deferred] object to use in coroutines. */ fun <R : Any?> Transaction.Builder<R>.defer(): Deferred<R> { val deferred = CompletableDeferred<R>() val transaction = success { _, result -> deferred.complete(result) } .error { _, throwable -> deferred.completeExceptionally(throwable) } .build() deferred.invokeOnCompletion { if (deferred.isCancelled) { transaction.cancel() } } transaction.execute() return deferred } inline fun <R : Any?> constructCoroutine(continuation: CancellableContinuation<R>, databaseDefinition: DBFlowDatabase, crossinline fn: () -> R) { val transaction = databaseDefinition.beginTransactionAsync { fn() } .success { _, result -> continuation.resume(result) } .error { _, throwable -> if (continuation.isCancelled) return@error continuation.resumeWithException(throwable) }.build() transaction.execute() continuation.invokeOnCancellation { if (continuation.isCancelled) { transaction.cancel() } } } /** * Description: Puts this [Queriable] operation inside a coroutine. Inside the [queriableFunction] * execute the db operation. */ suspend inline fun <Q : Queriable, R : Any?> Q.awaitTransact( dbFlowDatabase: DBFlowDatabase, crossinline queriableFunction: Q.(DBFlowDatabase) -> R) = suspendCancellableCoroutine<R> { continuation -> com.dbflow5.coroutines.constructCoroutine(continuation, dbFlowDatabase) { queriableFunction(dbFlowDatabase) } } /** * Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction] * execute the db operation. */ suspend inline fun <reified M : Any> M.awaitSave(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Boolean> { continuation -> constructCoroutine(continuation, databaseDefinition) { save(databaseDefinition) } } /** * Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction] * execute the db operation. */ suspend inline fun <reified M : Any> M.awaitInsert(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation -> constructCoroutine(continuation, databaseDefinition) { insert(databaseDefinition) } } /** * Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction] * execute the db operation. */ suspend inline fun <reified M : Any> M.awaitDelete(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Boolean> { continuation -> constructCoroutine(continuation, databaseDefinition) { delete(databaseDefinition) } } /** * Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction] * execute the db operation. */ suspend inline fun <reified M : Any> M.awaitUpdate(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Boolean> { continuation -> constructCoroutine(continuation, databaseDefinition) { update(databaseDefinition) } } /** * Description: Puts a [Model] operation inside a coroutine. Inside the [queriableFunction] * execute the db operation. */ suspend inline fun <reified M : Any> M.awaitLoad(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Unit> { continuation -> constructCoroutine(continuation, databaseDefinition) { load(databaseDefinition) } } /** * Description: Puts the [Collection] inside a [FastStoreModelTransaction] coroutine. */ suspend inline fun <reified T : Any, reified M : Collection<T>> M.awaitSave(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation -> constructFastCoroutine(continuation, databaseDefinition) { fastSave() } } /** * Description: Puts the [Collection] inside a [FastStoreModelTransaction] coroutine. */ suspend inline fun <reified T : Any, reified M : Collection<T>> M.awaitInsert(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation -> constructFastCoroutine(continuation, databaseDefinition) { fastInsert() } } /** * Description: Puts the [Collection] inside a [FastStoreModelTransaction] coroutine. */ suspend inline fun <reified T : Any, reified M : Collection<T>> M.awaitUpdate(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation -> constructFastCoroutine(continuation, databaseDefinition) { fastUpdate() } } /** * Description: Puts the [Collection] inside a [FastStoreModelTransaction] coroutine. */ suspend inline fun <reified T : Any, reified M : Collection<T>> M.awaitDelete(databaseDefinition: DBFlowDatabase) = suspendCancellableCoroutine<Long> { continuation -> constructFastCoroutine(continuation, databaseDefinition) { fastDelete() } } inline fun <R : Any?> constructFastCoroutine(continuation: CancellableContinuation<Long>, databaseDefinition: DBFlowDatabase, crossinline fn: () -> FastStoreModelTransaction.Builder<R>) { val transaction = databaseDefinition.beginTransactionAsync(fn().build()) .success { _, result -> continuation.resume(result) } .error { _, throwable -> if (continuation.isCancelled) return@error continuation.resumeWithException(throwable) }.build() transaction.execute() continuation.invokeOnCancellation { transaction.cancel() } }
coroutines/src/main/kotlin/com/dbflow5/coroutines/Coroutines.kt
2860997812
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.dataFlow.inference import com.intellij.lang.LighterAST import com.intellij.lang.LighterASTNode import com.intellij.psi.JavaTokenType import com.intellij.psi.PsiMethod import com.intellij.psi.impl.source.JavaLightStubBuilder import com.intellij.psi.impl.source.JavaLightTreeUtil import com.intellij.psi.impl.source.PsiFileImpl import com.intellij.psi.impl.source.PsiMethodImpl import com.intellij.psi.impl.source.tree.JavaElementType.* import com.intellij.psi.impl.source.tree.LightTreeUtil import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.gist.GistManager import java.util.* import kotlin.collections.HashMap /** * @author peter */ private val gist = GistManager.getInstance().newPsiFileGist("contractInference", 12, MethodDataExternalizer) { file -> indexFile(file.node.lighterAST) } private fun indexFile(tree: LighterAST): Map<Int, MethodData> { val visitor = InferenceVisitor(tree) visitor.visitNode(tree.root) return visitor.result } internal data class ClassData(val hasSuper : Boolean, val hasPureInitializer : Boolean, val fieldModifiers : Map<String, LighterASTNode?>) private class InferenceVisitor(val tree : LighterAST) : RecursiveLighterASTNodeWalkingVisitor(tree) { var methodIndex = 0 val classData = HashMap<LighterASTNode, ClassData>() val result = HashMap<Int, MethodData>() override fun visitNode(element: LighterASTNode) { when(element.tokenType) { CLASS, ANONYMOUS_CLASS -> { classData[element] = calcClassData(element) } METHOD -> { calcData(element)?.let { data -> result[methodIndex] = data } methodIndex++ } } if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return super.visitNode(element) } private fun calcClassData(aClass: LighterASTNode) : ClassData { var hasSuper = aClass.tokenType == ANONYMOUS_CLASS val fieldModifiers = HashMap<String, LighterASTNode?>() val initializers = ArrayList<LighterASTNode>() for (child in tree.getChildren(aClass)) { when(child.tokenType) { EXTENDS_LIST -> { if (LightTreeUtil.firstChildOfType(tree, child, JAVA_CODE_REFERENCE) != null) { hasSuper = true } } FIELD -> { val fieldName = JavaLightTreeUtil.getNameIdentifierText(tree, child) if (fieldName != null) { val modifiers = LightTreeUtil.firstChildOfType(tree, child, MODIFIER_LIST) fieldModifiers[fieldName] = modifiers val isStatic = LightTreeUtil.firstChildOfType(tree, modifiers, JavaTokenType.STATIC_KEYWORD) != null if (!isStatic) { val initializer = JavaLightTreeUtil.findExpressionChild(tree, child) if (initializer != null) { initializers.add(initializer) } } } } CLASS_INITIALIZER -> { val modifiers = LightTreeUtil.firstChildOfType(tree, child, MODIFIER_LIST) val isStatic = LightTreeUtil.firstChildOfType(tree, modifiers, JavaTokenType.STATIC_KEYWORD) != null if (!isStatic) { val body = LightTreeUtil.firstChildOfType(tree, child, CODE_BLOCK) if (body != null) { initializers.add(body) } } } } } var pureInitializer = true if (initializers.isNotEmpty()) { val visitor = PurityInferenceVisitor(tree, aClass, fieldModifiers, true) for (initializer in initializers) { walkMethodBody(initializer, visitor::visitNode) val result = visitor.result pureInitializer = result != null && result.singleCall == null && result.mutatedRefs.isEmpty() if (!pureInitializer) break } } return ClassData(hasSuper, pureInitializer, fieldModifiers) } private fun calcData(method: LighterASTNode): MethodData? { val body = LightTreeUtil.firstChildOfType(tree, method, CODE_BLOCK) ?: return null val clsData = classData[tree.getParent(method)] val fieldMap = clsData?.fieldModifiers ?: emptyMap() // Constructor which has super classes may implicitly call impure super constructor, so don't infer purity for subclasses val ctor = LightTreeUtil.firstChildOfType(tree, method, TYPE) == null val maybeImpureCtor = ctor && (clsData == null || clsData.hasSuper || !clsData.hasPureInitializer) val statements = ContractInferenceInterpreter.getStatements(body, tree) val contractInference = ContractInferenceInterpreter(tree, method, body) val contracts = contractInference.inferContracts(statements) val nullityVisitor = MethodReturnInferenceVisitor(tree, contractInference.parameters, body) val purityVisitor = PurityInferenceVisitor(tree, body, fieldMap, ctor) for (statement in statements) { walkMethodBody(statement) { nullityVisitor.visitNode(it) if (!maybeImpureCtor) { purityVisitor.visitNode(it) } } } val notNullParams = inferNotNullParameters(tree, method, statements) return createData(body, contracts, nullityVisitor.result, if (maybeImpureCtor) null else purityVisitor.result, notNullParams) } private fun walkMethodBody(root: LighterASTNode, processor: (LighterASTNode) -> Unit) { object : RecursiveLighterASTNodeWalkingVisitor(tree) { override fun visitNode(element: LighterASTNode) { val type = element.tokenType if (type === CLASS || type === FIELD || type === METHOD || type === ANNOTATION_METHOD || type === LAMBDA_EXPRESSION) return processor(element) super.visitNode(element) } }.visitNode(root) } private fun createData(body: LighterASTNode, contracts: List<PreContract>, methodReturn: MethodReturnInferenceResult?, purity: PurityInferenceResult?, notNullParams: BitSet): MethodData? { if (methodReturn == null && purity == null && contracts.isEmpty() && notNullParams.isEmpty) return null return MethodData(methodReturn, purity, contracts, notNullParams, body.startOffset, body.endOffset) } } fun getIndexedData(method: PsiMethodImpl): MethodData? { val file = method.containingFile val map = CachedValuesManager.getCachedValue(file) { val fileData = gist.getFileData(file) val result = hashMapOf<PsiMethod, MethodData>() if (fileData != null) { val spine = (file as PsiFileImpl).stubbedSpine var methodIndex = 0 for (i in 0 until spine.stubCount) { if (spine.getStubType(i) === METHOD) { fileData[methodIndex]?.let { result[spine.getStubPsi(i) as PsiMethod] = it } methodIndex++ } } } CachedValueProvider.Result.create(result, file) } return map[method] }
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/ContractInferenceIndex.kt
2296837641
package codegen.lambda.lambda13 import kotlin.test.* @Test fun runTest() { apply("foo") { println(this) } } fun apply(str: String, block: String.() -> Unit) { str.block() }
backend.native/tests/codegen/lambda/lambda13.kt
3545521938
class P { var x : Int = 0 private set fun foo() { ({ x = 4 })() } } fun box() : String { val p = P() p.foo() return if (p.x == 4) "OK" else "fail" }
backend.native/tests/external/codegen/box/properties/kt2331.kt
503391451
// Auto-generated by GeneratePrimitiveVsObjectEqualityTestData. Do not edit! val nx: Any? = 0 val nn: Any? = null val x: Int = 0 val y: Int = 1 fun box(): String { val ax: Any? = 0 val an: Any? = null val bx: Int = 0 val by: Int = 1 return when { 0 != nx -> "Fail 0" 1 == nx -> "Fail 1" !(0 == nx) -> "Fail 2" !(1 != nx) -> "Fail 3" x != nx -> "Fail 4" y == nx -> "Fail 5" !(x == nx) -> "Fail 6" !(y != nx) -> "Fail 7" 0 == nn -> "Fail 8" !(0 != nn) -> "Fail 9" x == nn -> "Fail 10" !(x != nn) -> "Fail 11" 0 != ax -> "Fail 12" 1 == ax -> "Fail 13" !(0 == ax) -> "Fail 14" !(1 != ax) -> "Fail 15" x != ax -> "Fail 16" y == ax -> "Fail 17" !(x == ax) -> "Fail 18" !(y != ax) -> "Fail 19" bx != ax -> "Fail 20" by == ax -> "Fail 21" !(bx == ax) -> "Fail 22" !(by != ax) -> "Fail 23" 0 == an -> "Fail 24" !(0 != an) -> "Fail 25" x == an -> "Fail 26" !(x != an) -> "Fail 27" bx == an -> "Fail 28" !(bx != an) -> "Fail 29" else -> "OK" } }
backend.native/tests/external/codegen/box/primitiveTypes/equalityWithObject/generated/primitiveEqObjectInt.kt
1508268145
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.services.impl import com.intellij.psi.PsiElement import com.intellij.util.containers.CollectionFactory import org.editorconfig.language.schema.descriptors.impl.EditorConfigOptionDescriptor import org.editorconfig.language.util.EditorConfigDescriptorUtil class EditorConfigOptionDescriptorStorage(source: Iterable<EditorConfigOptionDescriptor>) { val allDescriptors: List<EditorConfigOptionDescriptor> private val descriptors: Map<String, List<EditorConfigOptionDescriptor>> private val badDescriptors: List<EditorConfigOptionDescriptor> init { val allDescriptors = mutableListOf<EditorConfigOptionDescriptor>() val descriptors = CollectionFactory.createCaseInsensitiveStringMap<MutableList<EditorConfigOptionDescriptor>>() val badDescriptors = mutableListOf<EditorConfigOptionDescriptor>() for (optionDescriptor in source) { allDescriptors.add(optionDescriptor) val constants = EditorConfigDescriptorUtil.collectConstants(optionDescriptor.key) if (constants.isEmpty()) { badDescriptors.add(optionDescriptor) continue } for (constant in constants) { var list = descriptors[constant] if (list == null) { list = mutableListOf() descriptors[constant] = list } list.add(optionDescriptor) } } this.allDescriptors = allDescriptors this.descriptors = descriptors this.badDescriptors = badDescriptors } operator fun get(key: PsiElement, parts: List<String>): EditorConfigOptionDescriptor? { for (part in parts) { val partDescriptors = descriptors[part] ?: continue for (descriptor in partDescriptors) { if (descriptor.key.matches(key)) return descriptor } } return badDescriptors.firstOrNull { it.key.matches(key) } } }
plugins/editorconfig/src/org/editorconfig/language/services/impl/EditorConfigOptionDescriptorStorage.kt
340755210
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.inference.nullability import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.nj2k.inference.common.* import org.jetbrains.kotlin.nj2k.inference.common.collectors.ConstraintsCollector import org.jetbrains.kotlin.psi.* class NullabilityConstraintsCollector : ConstraintsCollector() { override fun ConstraintBuilder.collectConstraints( element: KtElement, boundTypeCalculator: BoundTypeCalculator, inferenceContext: InferenceContext, resolutionFacade: ResolutionFacade ) { when { element is KtBinaryExpression && (element.left?.isNullExpression() == true || element.right?.isNullExpression() == true) -> { val notNullOperand = if (element.left?.isNullExpression() == true) element.right else element.left notNullOperand?.isTheSameTypeAs(State.UPPER, ConstraintPriority.COMPARE_WITH_NULL) } element is KtQualifiedExpression -> { element.receiverExpression.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER) } element is KtForExpression -> { element.loopRange?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER) } element is KtWhileExpressionBase -> { element.condition?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER) } element is KtIfExpression -> { element.condition?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER) } element is KtValueArgument && element.isSpread -> { element.getArgumentExpression()?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER) } element is KtBinaryExpression && !KtPsiUtil.isAssignment(element) -> { element.left?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER) element.right?.isTheSameTypeAs(State.LOWER, ConstraintPriority.USE_AS_RECEIVER) } } } }
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/nullability/NullabilityConstraintsCollector.kt
1126309720
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto import com.intellij.util.Range import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.psi.KtCallableReferenceExpression import org.jetbrains.kotlin.psi.KtDeclarationWithBody import javax.swing.Icon class KotlinMethodReferenceSmartStepTarget( highlightElement: KtCallableReferenceExpression, lines: Range<Int>, label: String, val targetMethodName: String, val declaration: KtDeclarationWithBody ) : KotlinSmartStepTarget(label, highlightElement, true, lines) { override fun createMethodFilter() = KotlinMethodReferenceFilter(this) override fun getIcon(): Icon? = KotlinIcons.FUNCTION }
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinMethodReferenceSmartStepTarget.kt
3183356406
import java.util.ArrayList fun test() { val abc = ArrayList<Int>() .map { it * 2 } .filter { it > 4 } } fun test1() { val abc = ArrayList<Int>() .map({ it * 2 }) .filter({ it > 4 }) } fun test2() { val abc = ArrayList<Int>() .map { it * 2 } } fun test3() { val abc = ArrayList<Int>().map { it * 2 } } fun test4() { val abc = ArrayList<Int>().mapTo( LinkedHashSet() ) { it * 2 } } fun testWithComments() { val abc = ArrayList<Int>() // .map { // it * 2 // } .filter { it > 4 } } // SET_TRUE: CONTINUATION_INDENT_FOR_CHAINED_CALLS // SET_TRUE: ALLOW_TRAILING_COMMA
plugins/kotlin/idea/tests/testData/formatter/callChain/FunctionLiteralsInChainCalls.after.inv.kt
2701998349
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.impl import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.util.SmartList import com.intellij.util.containers.minimalElements import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.filterSameSignatureCandidates import org.jetbrains.plugins.groovy.lang.resolve.api.Applicability import org.jetbrains.plugins.groovy.lang.resolve.api.Applicability.canBeApplicable import org.jetbrains.plugins.groovy.lang.resolve.api.Applicability.inapplicable import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyOverloadResolver /** * Applicable results and a flag whether overload should be selected. * * There may be cases when we don't know types of arguments, so we cannot select a method 100% sure. * Consider the example: * ``` * def foo(Integer a) {} * def foo(Number b) {} * foo(unknownArgument) * ``` * If we were to choose an overload with most specific signature, then only `foo(Integer)` would be chosen. * In such case we assume both overloads as [potentially applicable][canBeApplicable] * and offer navigation to both of them, etc. */ typealias ApplicabilitiesResult<X> = Pair<List<X>, Boolean> fun <X> List<X>.filterApplicable(applicability: (X) -> Applicability): ApplicabilitiesResult<X> { if (isEmpty()) { return ApplicabilitiesResult(emptyList(), true) } val results = SmartList<X>() var canSelectOverload = true for (thing in this) { val thingApplicability = applicability(thing) if (thingApplicability == inapplicable) { continue } if (thingApplicability == canBeApplicable) { canSelectOverload = false } results += thing } return ApplicabilitiesResult(results, canSelectOverload) } fun List<GroovyMethodResult>.correctStaticScope(): List<GroovyMethodResult> { if (isEmpty()) return emptyList() return filterTo(SmartList()) { it.isStaticsOK } } private val overloadResolverEp = ExtensionPointName.create<GroovyOverloadResolver>("org.intellij.groovy.overloadResolver") private fun compare(left: GroovyMethodResult, right: GroovyMethodResult): Int { for (resolver in overloadResolverEp.extensions) { val result = resolver.compare(left, right) if (result != 0) { return result } } return 0 } private val resultOverloadComparator: Comparator<GroovyMethodResult> = Comparator(::compare) fun chooseOverloads(candidates: List<GroovyMethodResult>): List<GroovyMethodResult> { return SmartList(candidates.minimalElements(resultOverloadComparator)) } /** * @return results that have the same numbers of parameters as passed arguments, * or original results if it's not possible to compute arguments number or if there are no matching results */ fun filterByArgumentsCount(results: List<GroovyMethodResult>, arguments: Arguments?): List<GroovyMethodResult> { val argumentsCount = arguments?.size ?: return results val filtered = results.filterTo(SmartList()) { it.element.parameterList.parametersCount == argumentsCount } return if (filtered.isEmpty()) results else filtered } fun filterBySignature(results: List<GroovyMethodResult>): List<GroovyMethodResult> { if (results.size < 2) return results @Suppress("UNCHECKED_CAST") return filterSameSignatureCandidates(results).toList() as List<GroovyMethodResult> }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/overloads.kt
2506648529
package io.fotoapparat.result.adapter.rxjava2 import android.annotation.SuppressLint import io.fotoapparat.result.PendingResult import io.reactivex.Observable import java.util.concurrent.Future /** * Adapter for [Observable]. */ object ObservableAdapter { /** * @return Adapter which adapts result to [Observable]. */ @JvmStatic @SuppressLint("CheckResult") fun <T> toObservable(): Function1<Future<T>, Observable<T>> { return { future -> Observable.fromFuture(future) } } } /** * @return A [Observable] from the given [PendingResult]. */ @SuppressLint("CheckResult") fun <T> PendingResult<T>.toObservable(): Observable<T> { return adapt { future -> Observable.fromFuture(future) } }
fotoapparat-adapters/rxjava2/src/main/java/io/fotoapparat/result/adapter/rxjava2/ObservableAdapter.kt
373392175
fun myFun() {} <warning descr="SSR">fun Int.myFun1() {}</warning> <warning descr="SSR">fun kotlin.Int.myFun2() {}</warning>
plugins/kotlin/idea/tests/testData/structuralsearch/function/funReceiverTypeReference.kt
2764559179
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.inspections import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.util.TextRange import org.editorconfig.language.codeinsight.quickfixes.EditorConfigSanitizeCharClassQuickFix import org.editorconfig.language.messages.EditorConfigBundle import org.editorconfig.language.psi.EditorConfigCharClass import org.editorconfig.language.psi.EditorConfigCharClassLetter import org.editorconfig.language.psi.EditorConfigVisitor class EditorConfigCharClassLetterRedundancyInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() { override fun visitCharClass(charClass: EditorConfigCharClass) { val letters = charClass.charClassLetterList @Suppress("DialogTitleCapitalization") val message = EditorConfigBundle["inspection.charclass.duplicate.message"] // Ranges are collected this way // in order to avoid overwhelming user // with a bunch of one-character warnings var state = State.INITIAL var firstDuplicateStart = Int.MAX_VALUE letters.forEach { val unique = isUnique(it, letters) if (unique && state == State.COLLECTING_DUPLICATES) { val range = TextRange.create(firstDuplicateStart, it.startOffsetInParent) holder.registerProblem(charClass, range, message, EditorConfigSanitizeCharClassQuickFix()) state = State.INITIAL } else if (!unique && state == State.INITIAL) { firstDuplicateStart = it.startOffsetInParent state = State.COLLECTING_DUPLICATES } } if (state == State.COLLECTING_DUPLICATES) { val last = letters.last() val range = TextRange.create(firstDuplicateStart, last.startOffsetInParent + last.textLength) holder.registerProblem(charClass, range, message, EditorConfigSanitizeCharClassQuickFix()) } } } private fun isUnique(letter: EditorConfigCharClassLetter, letters: List<EditorConfigCharClassLetter>) = letters.count(letter::textMatches) <= 1 private enum class State { INITIAL, COLLECTING_DUPLICATES } }
plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigCharClassLetterRedundancyInspection.kt
2685353562
data class Foo(val bar: Int) {<caret> }
plugins/kotlin/idea/tests/testData/intentions/removeEmptyClassBody/emptyDataClass.kt
904197820
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.test.handlers import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.testFramework.TestDataPath import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.completion.test.COMPLETION_TEST_DATA_BASE import org.jetbrains.kotlin.idea.completion.test.KotlinFixtureCompletionBaseTestCase import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.test.TestMetadata import org.jetbrains.kotlin.test.TestRoot import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith import java.io.File @RunWith(JUnit38ClassRunner::class) @TestRoot("idea/tests") @TestDataPath("\$CONTENT_ROOT") @TestMetadata("testData/handlers/multifile") class CompletionMultiFileHandlerTest22 : KotlinFixtureCompletionBaseTestCase() { fun testExtensionFunctionImport() = doTest() fun testExtensionPropertyImport() = doTest() fun testImportAlreadyImportedObject() = doTest() fun testJetClassCompletionImport() = doTest() fun testStaticMethodFromGrandParent() = doTest('\n', "StaticMethodFromGrandParent-1.java", "StaticMethodFromGrandParent-2.java") fun testTopLevelFunctionImport() = doTest() fun testTopLevelFunctionInQualifiedExpr() = doTest() fun testTopLevelPropertyImport() = doTest() fun testTopLevelValImportInStringTemplate() = doTest() fun testNoParenthesisInImports() = doTest() fun testKeywordExtensionFunctionName() = doTest() fun testInfixExtensionCallImport() = doTest() fun testClassWithClassObject() = doTest() fun testGlobalFunctionImportInLambda() = doTest() fun testObjectInStringTemplate() = doTest() fun testPropertyFunctionConflict() = doTest() fun testPropertyFunctionConflict2() = doTest(tailText = " { Int, Int -> ... } (i: (Int, Int) -> Unit) (a.b)") fun testExclCharInsertImport() = doTest('!') fun testPropertyKeysWithPrefixEnter() = doTest('\n', "TestBundle.properties") fun testPropertyKeysWithPrefixTab() = doTest('\t', "TestBundle.properties") fun testFileRefInStringLiteralEnter() = doTest('\n', "foo.txt", "bar.txt") fun testFileRefInStringLiteralTab() = doTest('\t', "foo.txt", "bar.txt") fun testNotImportedExtension() = doTest() fun testNotImportedTypeAlias() = doTest() fun testKT12077() = doTest() fun doTest(completionChar: Char = '\n', vararg extraFileNames: String, tailText: String? = null) { val fileNameBase = getTestName(false) val defaultFiles = listOf("$fileNameBase-1.kt", "$fileNameBase-2.kt") val filteredFiles = defaultFiles.filter { File(testDataDirectory, it).exists() } require(filteredFiles.isNotEmpty()) { "At least one of $defaultFiles should exist!" } myFixture.configureByFiles(*extraFileNames) myFixture.configureByFiles(*filteredFiles.toTypedArray()) val items = complete(CompletionType.BASIC, 2) if (items != null) { val item = if (tailText == null) items.singleOrNull() ?: error("Multiple items in completion") else { val presentation = LookupElementPresentation() items.first { it.renderElement(presentation) presentation.tailText == tailText } } CompletionHandlerTestBase.selectItem(myFixture, item, completionChar) } myFixture.checkResultByFile("$fileNameBase.kt.after") } override val testDataDirectory: File get() = COMPLETION_TEST_DATA_BASE.resolve("handlers/multifile") override fun defaultCompletionType(): CompletionType = CompletionType.BASIC override fun getPlatform(): TargetPlatform = JvmPlatforms.unspecifiedJvmPlatform override fun getProjectDescriptor() = LightJavaCodeInsightFixtureTestCase.JAVA_11 }
plugins/kotlin/completion/tests/test/org/jetbrains/kotlin/idea/completion/test/handlers/CompletionMultifileHandlerTest.kt
3267331664
package v_builders import util.* fun todoTask36(): Nothing = TODO( """ Task 36. Read about extension function literals. You can declare `isEven` and `isOdd` as values, that can be called as extension functions. Complete the declarations below. """, documentation = doc36() ) fun task36(): List<Boolean> { val isEven: Int.() -> Boolean = { todoTask36() } val isOdd: Int.() -> Boolean = { todoTask36() } return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven()) }
src/v_builders/_36_ExtensionFunctionLiterals.kt
1922533617
/* * Generated from WebIDL by webidl-util */ @file:Suppress("UnsafeCastFromDynamic", "ClassName", "FunctionName", "UNUSED_VARIABLE", "UNUSED_PARAMETER", "unused") package physx external interface SupportFunctions { /** * Native object address. */ val ptr: Int /** * @param actor WebIDL type: [PxRigidActor] (Ref) * @param index WebIDL type: long * @return WebIDL type: [PxShape] */ fun PxActor_getShape(actor: PxRigidActor, index: Int): PxShape /** * @param pairHeader WebIDL type: [PxContactPairHeader] (Ref) * @param index WebIDL type: long * @return WebIDL type: [PxActor] */ fun PxContactPairHeader_getActor(pairHeader: PxContactPairHeader, index: Int): PxActor /** * @param scene WebIDL type: [PxScene] * @return WebIDL type: [Vector_PxActorPtr] (Ref) */ fun PxScene_getActiveActors(scene: PxScene): Vector_PxActorPtr } fun SupportFunctions.destroy() { PhysXJsLoader.destroy(this) } external interface PxActorPtr fun PxActorPtr.destroy() { PhysXJsLoader.destroy(this) } external interface PxMaterialPtr fun PxMaterialPtr.destroy() { PhysXJsLoader.destroy(this) } external interface PxMaterialConstPtr fun PxMaterialConstPtr.destroy() { PhysXJsLoader.destroy(this) } external interface PxVehicleWheelsPtr fun PxVehicleWheelsPtr.destroy() { PhysXJsLoader.destroy(this) } external interface PxRealPtr fun PxRealPtr.destroy() { PhysXJsLoader.destroy(this) } external interface PxU8Ptr : PxU8ConstPtr fun PxU8Ptr.destroy() { PhysXJsLoader.destroy(this) } external interface PxU8ConstPtr fun PxU8ConstPtr.destroy() { PhysXJsLoader.destroy(this) } external interface PxU16Ptr : PxU16ConstPtr fun PxU16Ptr.destroy() { PhysXJsLoader.destroy(this) } external interface PxU16ConstPtr fun PxU16ConstPtr.destroy() { PhysXJsLoader.destroy(this) } external interface PxU32Ptr : PxU32ConstPtr fun PxU32Ptr.destroy() { PhysXJsLoader.destroy(this) } external interface PxU32ConstPtr fun PxU32ConstPtr.destroy() { PhysXJsLoader.destroy(this) } external interface TypeHelpers { /** * Native object address. */ val ptr: Int /** * @param base WebIDL type: [PxU8ConstPtr] (Ref) * @param index WebIDL type: long * @return WebIDL type: octet */ fun getU8At(base: PxU8ConstPtr, index: Int): Byte /** * @param base WebIDL type: [PxU16ConstPtr] (Ref) * @param index WebIDL type: long * @return WebIDL type: unsigned short */ fun getU16At(base: PxU16ConstPtr, index: Int): Short /** * @param base WebIDL type: [PxU32ConstPtr] (Ref) * @param index WebIDL type: long * @return WebIDL type: unsigned long */ fun getU32At(base: PxU32ConstPtr, index: Int): Int /** * @param base WebIDL type: [PxRealPtr] (Ref) * @param index WebIDL type: long * @return WebIDL type: float */ fun getRealAt(base: PxRealPtr, index: Int): Float /** * @param base WebIDL type: [PxActor] * @param index WebIDL type: long * @return WebIDL type: [PxActor] */ fun getActorAt(base: PxActor, index: Int): PxActor /** * @param base WebIDL type: [PxBounds3] * @param index WebIDL type: long * @return WebIDL type: [PxBounds3] */ fun getBounds3At(base: PxBounds3, index: Int): PxBounds3 /** * @param base WebIDL type: [PxContactPair] * @param index WebIDL type: long * @return WebIDL type: [PxContactPair] */ fun getContactPairAt(base: PxContactPair, index: Int): PxContactPair /** * @param base WebIDL type: [PxContactPairHeader] * @param index WebIDL type: long * @return WebIDL type: [PxContactPairHeader] */ fun getContactPairHeaderAt(base: PxContactPairHeader, index: Int): PxContactPairHeader /** * @param base WebIDL type: [PxController] * @param index WebIDL type: long * @return WebIDL type: [PxController] */ fun getControllerAt(base: PxController, index: Int): PxController /** * @param base WebIDL type: [PxControllerShapeHit] * @param index WebIDL type: long * @return WebIDL type: [PxControllerShapeHit] */ fun getControllerShapeHitAt(base: PxControllerShapeHit, index: Int): PxControllerShapeHit /** * @param base WebIDL type: [PxControllersHit] * @param index WebIDL type: long * @return WebIDL type: [PxControllersHit] */ fun getControllersHitAt(base: PxControllersHit, index: Int): PxControllersHit /** * @param base WebIDL type: [PxControllerObstacleHit] * @param index WebIDL type: long * @return WebIDL type: [PxControllerObstacleHit] */ fun getControllerObstacleHitAt(base: PxControllerObstacleHit, index: Int): PxControllerObstacleHit /** * @param base WebIDL type: [PxObstacle] * @param index WebIDL type: long * @return WebIDL type: [PxObstacle] */ fun getObstacleAt(base: PxObstacle, index: Int): PxObstacle /** * @param base WebIDL type: [PxShape] * @param index WebIDL type: long * @return WebIDL type: [PxShape] */ fun getShapeAt(base: PxShape, index: Int): PxShape /** * @param base WebIDL type: [PxTriggerPair] * @param index WebIDL type: long * @return WebIDL type: [PxTriggerPair] */ fun getTriggerPairAt(base: PxTriggerPair, index: Int): PxTriggerPair /** * @param base WebIDL type: [PxVec3] * @param index WebIDL type: long * @return WebIDL type: [PxVec3] */ fun getVec3At(base: PxVec3, index: Int): PxVec3 /** * @param voidPtr WebIDL type: VoidPtr * @return WebIDL type: [PxU8Ptr] (Value) */ fun voidToU8Ptr(voidPtr: Any): PxU8Ptr /** * @param voidPtr WebIDL type: VoidPtr * @return WebIDL type: [PxU16Ptr] (Value) */ fun voidToU16Ptr(voidPtr: Any): PxU16Ptr /** * @param voidPtr WebIDL type: VoidPtr * @return WebIDL type: [PxU32Ptr] (Value) */ fun voidToU32Ptr(voidPtr: Any): PxU32Ptr /** * @param voidPtr WebIDL type: VoidPtr * @return WebIDL type: [PxRealPtr] (Value) */ fun voidToRealPtr(voidPtr: Any): PxRealPtr /** * @param baseJoint WebIDL type: [PxArticulationJointBase] * @return WebIDL type: [PxArticulationJoint] */ fun articulationBaseJointToJoint(baseJoint: PxArticulationJointBase): PxArticulationJoint /** * @param baseJoint WebIDL type: [PxArticulationJointBase] * @return WebIDL type: [PxArticulationJointReducedCoordinate] */ fun articulationBaseJointToJointReducedCoordinate(baseJoint: PxArticulationJointBase): PxArticulationJointReducedCoordinate /** * @param voidPtr WebIDL type: VoidPtr * @return WebIDL type: any */ fun voidToAny(voidPtr: Any): Int } fun TypeHelpers.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxMaterialConst { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxMaterial] (Const) */ fun at(index: Int): PxMaterial /** * @return WebIDL type: [PxMaterialConstPtr] */ fun data(): PxMaterialConstPtr /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxMaterial] (Const) */ fun push_back(value: PxMaterial) fun clear() } fun Vector_PxMaterialConst(): Vector_PxMaterialConst { fun _Vector_PxMaterialConst(_module: dynamic) = js("new _module.Vector_PxMaterialConst()") return _Vector_PxMaterialConst(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxMaterialConst(size: Int): Vector_PxMaterialConst { fun _Vector_PxMaterialConst(_module: dynamic, size: Int) = js("new _module.Vector_PxMaterialConst(size)") return _Vector_PxMaterialConst(PhysXJsLoader.physXJs, size) } fun Vector_PxMaterialConst.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxHeightFieldSample { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxHeightFieldSample] (Ref) */ fun at(index: Int): PxHeightFieldSample /** * @return WebIDL type: [PxHeightFieldSample] */ fun data(): PxHeightFieldSample /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxHeightFieldSample] (Ref) */ fun push_back(value: PxHeightFieldSample) fun clear() } fun Vector_PxHeightFieldSample(): Vector_PxHeightFieldSample { fun _Vector_PxHeightFieldSample(_module: dynamic) = js("new _module.Vector_PxHeightFieldSample()") return _Vector_PxHeightFieldSample(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxHeightFieldSample(size: Int): Vector_PxHeightFieldSample { fun _Vector_PxHeightFieldSample(_module: dynamic, size: Int) = js("new _module.Vector_PxHeightFieldSample(size)") return _Vector_PxHeightFieldSample(PhysXJsLoader.physXJs, size) } fun Vector_PxHeightFieldSample.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxReal { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: float */ fun at(index: Int): Float /** * @return WebIDL type: VoidPtr */ fun data(): Any /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: float */ fun push_back(value: Float) fun clear() } fun Vector_PxReal(): Vector_PxReal { fun _Vector_PxReal(_module: dynamic) = js("new _module.Vector_PxReal()") return _Vector_PxReal(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxReal(size: Int): Vector_PxReal { fun _Vector_PxReal(_module: dynamic, size: Int) = js("new _module.Vector_PxReal(size)") return _Vector_PxReal(PhysXJsLoader.physXJs, size) } fun Vector_PxReal.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxU8 { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: octet */ fun at(index: Int): Byte /** * @return WebIDL type: VoidPtr */ fun data(): Any /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: octet */ fun push_back(value: Byte) fun clear() } fun Vector_PxU8(): Vector_PxU8 { fun _Vector_PxU8(_module: dynamic) = js("new _module.Vector_PxU8()") return _Vector_PxU8(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxU8(size: Int): Vector_PxU8 { fun _Vector_PxU8(_module: dynamic, size: Int) = js("new _module.Vector_PxU8(size)") return _Vector_PxU8(PhysXJsLoader.physXJs, size) } fun Vector_PxU8.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxU16 { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: unsigned short */ fun at(index: Int): Short /** * @return WebIDL type: VoidPtr */ fun data(): Any /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: unsigned short */ fun push_back(value: Short) fun clear() } fun Vector_PxU16(): Vector_PxU16 { fun _Vector_PxU16(_module: dynamic) = js("new _module.Vector_PxU16()") return _Vector_PxU16(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxU16(size: Int): Vector_PxU16 { fun _Vector_PxU16(_module: dynamic, size: Int) = js("new _module.Vector_PxU16(size)") return _Vector_PxU16(PhysXJsLoader.physXJs, size) } fun Vector_PxU16.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxU32 { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: unsigned long */ fun at(index: Int): Int /** * @return WebIDL type: VoidPtr */ fun data(): Any /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: unsigned long */ fun push_back(value: Int) fun clear() } fun Vector_PxU32(): Vector_PxU32 { fun _Vector_PxU32(_module: dynamic) = js("new _module.Vector_PxU32()") return _Vector_PxU32(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxU32(size: Int): Vector_PxU32 { fun _Vector_PxU32(_module: dynamic, size: Int) = js("new _module.Vector_PxU32(size)") return _Vector_PxU32(PhysXJsLoader.physXJs, size) } fun Vector_PxU32.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxVec3 { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxVec3] (Ref) */ fun at(index: Int): PxVec3 /** * @return WebIDL type: [PxVec3] */ fun data(): PxVec3 /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxVec3] (Ref) */ fun push_back(value: PxVec3) fun clear() } fun Vector_PxVec3(): Vector_PxVec3 { fun _Vector_PxVec3(_module: dynamic) = js("new _module.Vector_PxVec3()") return _Vector_PxVec3(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxVec3(size: Int): Vector_PxVec3 { fun _Vector_PxVec3(_module: dynamic, size: Int) = js("new _module.Vector_PxVec3(size)") return _Vector_PxVec3(PhysXJsLoader.physXJs, size) } fun Vector_PxVec3.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxActorPtr { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxActor] */ fun at(index: Int): PxActor /** * @return WebIDL type: [PxActorPtr] */ fun data(): PxActorPtr /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxActor] */ fun push_back(value: PxActor) fun clear() } fun Vector_PxActorPtr(): Vector_PxActorPtr { fun _Vector_PxActorPtr(_module: dynamic) = js("new _module.Vector_PxActorPtr()") return _Vector_PxActorPtr(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxActorPtr(size: Int): Vector_PxActorPtr { fun _Vector_PxActorPtr(_module: dynamic, size: Int) = js("new _module.Vector_PxActorPtr(size)") return _Vector_PxActorPtr(PhysXJsLoader.physXJs, size) } fun Vector_PxActorPtr.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxContactPairPoint { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxContactPairPoint] (Ref) */ fun at(index: Int): PxContactPairPoint /** * @return WebIDL type: [PxContactPairPoint] */ fun data(): PxContactPairPoint /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxContactPairPoint] (Ref) */ fun push_back(value: PxContactPairPoint) fun clear() } fun Vector_PxContactPairPoint(): Vector_PxContactPairPoint { fun _Vector_PxContactPairPoint(_module: dynamic) = js("new _module.Vector_PxContactPairPoint()") return _Vector_PxContactPairPoint(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxContactPairPoint(size: Int): Vector_PxContactPairPoint { fun _Vector_PxContactPairPoint(_module: dynamic, size: Int) = js("new _module.Vector_PxContactPairPoint(size)") return _Vector_PxContactPairPoint(PhysXJsLoader.physXJs, size) } fun Vector_PxContactPairPoint.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxRaycastQueryResult { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxRaycastQueryResult] (Ref) */ fun at(index: Int): PxRaycastQueryResult /** * @return WebIDL type: [PxRaycastQueryResult] */ fun data(): PxRaycastQueryResult /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxRaycastQueryResult] (Ref) */ fun push_back(value: PxRaycastQueryResult) fun clear() } fun Vector_PxRaycastQueryResult(): Vector_PxRaycastQueryResult { fun _Vector_PxRaycastQueryResult(_module: dynamic) = js("new _module.Vector_PxRaycastQueryResult()") return _Vector_PxRaycastQueryResult(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxRaycastQueryResult(size: Int): Vector_PxRaycastQueryResult { fun _Vector_PxRaycastQueryResult(_module: dynamic, size: Int) = js("new _module.Vector_PxRaycastQueryResult(size)") return _Vector_PxRaycastQueryResult(PhysXJsLoader.physXJs, size) } fun Vector_PxRaycastQueryResult.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxSweepQueryResult { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxSweepQueryResult] (Ref) */ fun at(index: Int): PxSweepQueryResult /** * @return WebIDL type: [PxSweepQueryResult] */ fun data(): PxSweepQueryResult /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxSweepQueryResult] (Ref) */ fun push_back(value: PxSweepQueryResult) fun clear() } fun Vector_PxSweepQueryResult(): Vector_PxSweepQueryResult { fun _Vector_PxSweepQueryResult(_module: dynamic) = js("new _module.Vector_PxSweepQueryResult()") return _Vector_PxSweepQueryResult(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxSweepQueryResult(size: Int): Vector_PxSweepQueryResult { fun _Vector_PxSweepQueryResult(_module: dynamic, size: Int) = js("new _module.Vector_PxSweepQueryResult(size)") return _Vector_PxSweepQueryResult(PhysXJsLoader.physXJs, size) } fun Vector_PxSweepQueryResult.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxRaycastHit { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxRaycastHit] (Ref) */ fun at(index: Int): PxRaycastHit /** * @return WebIDL type: [PxRaycastHit] */ fun data(): PxRaycastHit /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxRaycastHit] (Ref) */ fun push_back(value: PxRaycastHit) fun clear() } fun Vector_PxRaycastHit(): Vector_PxRaycastHit { fun _Vector_PxRaycastHit(_module: dynamic) = js("new _module.Vector_PxRaycastHit()") return _Vector_PxRaycastHit(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxRaycastHit(size: Int): Vector_PxRaycastHit { fun _Vector_PxRaycastHit(_module: dynamic, size: Int) = js("new _module.Vector_PxRaycastHit(size)") return _Vector_PxRaycastHit(PhysXJsLoader.physXJs, size) } fun Vector_PxRaycastHit.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxSweepHit { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxSweepHit] (Ref) */ fun at(index: Int): PxSweepHit /** * @return WebIDL type: [PxSweepHit] */ fun data(): PxSweepHit /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxSweepHit] (Ref) */ fun push_back(value: PxSweepHit) fun clear() } fun Vector_PxSweepHit(): Vector_PxSweepHit { fun _Vector_PxSweepHit(_module: dynamic) = js("new _module.Vector_PxSweepHit()") return _Vector_PxSweepHit(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxSweepHit(size: Int): Vector_PxSweepHit { fun _Vector_PxSweepHit(_module: dynamic, size: Int) = js("new _module.Vector_PxSweepHit(size)") return _Vector_PxSweepHit(PhysXJsLoader.physXJs, size) } fun Vector_PxSweepHit.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxVehicleDrivableSurfaceType { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxVehicleDrivableSurfaceType] (Ref) */ fun at(index: Int): PxVehicleDrivableSurfaceType /** * @return WebIDL type: [PxVehicleDrivableSurfaceType] */ fun data(): PxVehicleDrivableSurfaceType /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxVehicleDrivableSurfaceType] (Ref) */ fun push_back(value: PxVehicleDrivableSurfaceType) fun clear() } fun Vector_PxVehicleDrivableSurfaceType(): Vector_PxVehicleDrivableSurfaceType { fun _Vector_PxVehicleDrivableSurfaceType(_module: dynamic) = js("new _module.Vector_PxVehicleDrivableSurfaceType()") return _Vector_PxVehicleDrivableSurfaceType(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxVehicleDrivableSurfaceType(size: Int): Vector_PxVehicleDrivableSurfaceType { fun _Vector_PxVehicleDrivableSurfaceType(_module: dynamic, size: Int) = js("new _module.Vector_PxVehicleDrivableSurfaceType(size)") return _Vector_PxVehicleDrivableSurfaceType(PhysXJsLoader.physXJs, size) } fun Vector_PxVehicleDrivableSurfaceType.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxWheelQueryResult { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxWheelQueryResult] (Ref) */ fun at(index: Int): PxWheelQueryResult /** * @return WebIDL type: [PxWheelQueryResult] */ fun data(): PxWheelQueryResult /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxWheelQueryResult] (Ref) */ fun push_back(value: PxWheelQueryResult) fun clear() } fun Vector_PxWheelQueryResult(): Vector_PxWheelQueryResult { fun _Vector_PxWheelQueryResult(_module: dynamic) = js("new _module.Vector_PxWheelQueryResult()") return _Vector_PxWheelQueryResult(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxWheelQueryResult(size: Int): Vector_PxWheelQueryResult { fun _Vector_PxWheelQueryResult(_module: dynamic, size: Int) = js("new _module.Vector_PxWheelQueryResult(size)") return _Vector_PxWheelQueryResult(PhysXJsLoader.physXJs, size) } fun Vector_PxWheelQueryResult.destroy() { PhysXJsLoader.destroy(this) } external interface Vector_PxVehicleWheels { /** * Native object address. */ val ptr: Int /** * @param index WebIDL type: unsigned long * @return WebIDL type: [PxVehicleWheels] */ fun at(index: Int): PxVehicleWheels /** * @return WebIDL type: [PxVehicleWheelsPtr] */ fun data(): PxVehicleWheelsPtr /** * @return WebIDL type: unsigned long */ fun size(): Int /** * @param value WebIDL type: [PxVehicleWheels] */ fun push_back(value: PxVehicleWheels) fun clear() } fun Vector_PxVehicleWheels(): Vector_PxVehicleWheels { fun _Vector_PxVehicleWheels(_module: dynamic) = js("new _module.Vector_PxVehicleWheels()") return _Vector_PxVehicleWheels(PhysXJsLoader.physXJs) } /** * @param size WebIDL type: unsigned long */ fun Vector_PxVehicleWheels(size: Int): Vector_PxVehicleWheels { fun _Vector_PxVehicleWheels(_module: dynamic, size: Int) = js("new _module.Vector_PxVehicleWheels(size)") return _Vector_PxVehicleWheels(PhysXJsLoader.physXJs, size) } fun Vector_PxVehicleWheels.destroy() { PhysXJsLoader.destroy(this) } external interface PxPvdTransport { /** * Native object address. */ val ptr: Int /** * @return WebIDL type: boolean */ fun connect(): Boolean fun disconnect() /** * @return WebIDL type: boolean */ fun isConnected(): Boolean } external interface SimplePvdTransport : PxPvdTransport { /** * @return WebIDL type: boolean */ override fun connect(): Boolean /** * @param inBytes WebIDL type: any * @param inLength WebIDL type: unsigned long */ fun send(inBytes: Int, inLength: Int) } fun SimplePvdTransport.destroy() { PhysXJsLoader.destroy(this) } external interface JSPvdTransport : SimplePvdTransport { /** * return WebIDL type: boolean */ var connect: () -> Boolean /** * param inBytes WebIDL type: any * param inLength WebIDL type: unsigned long */ var send: (inBytes: Int, inLength: Int) -> Unit } fun JSPvdTransport(): JSPvdTransport { fun _JSPvdTransport(_module: dynamic) = js("new _module.JSPvdTransport()") return _JSPvdTransport(PhysXJsLoader.physXJs) } external interface PxPvdInstrumentationFlags { /** * Native object address. */ val ptr: Int /** * @param flag WebIDL type: [PxPvdInstrumentationFlagEnum] (enum) * @return WebIDL type: boolean */ fun isSet(flag: Int): Boolean /** * @param flag WebIDL type: [PxPvdInstrumentationFlagEnum] (enum) */ fun set(flag: Int) /** * @param flag WebIDL type: [PxPvdInstrumentationFlagEnum] (enum) */ fun clear(flag: Int) } /** * @param flags WebIDL type: octet */ fun PxPvdInstrumentationFlags(flags: Byte): PxPvdInstrumentationFlags { fun _PxPvdInstrumentationFlags(_module: dynamic, flags: Byte) = js("new _module.PxPvdInstrumentationFlags(flags)") return _PxPvdInstrumentationFlags(PhysXJsLoader.physXJs, flags) } fun PxPvdInstrumentationFlags.destroy() { PhysXJsLoader.destroy(this) } external interface PxPvd { /** * Native object address. */ val ptr: Int /** * @param transport WebIDL type: [PxPvdTransport] (Ref) * @param flags WebIDL type: [PxPvdInstrumentationFlags] (Ref) * @return WebIDL type: boolean */ fun connect(transport: PxPvdTransport, flags: PxPvdInstrumentationFlags): Boolean } external interface PassThroughFilterShader : PxSimulationFilterShader { /** * WebIDL type: unsigned long */ var outputPairFlags: Int /** * @param attributes0 WebIDL type: unsigned long * @param filterData0w0 WebIDL type: unsigned long * @param filterData0w1 WebIDL type: unsigned long * @param filterData0w2 WebIDL type: unsigned long * @param filterData0w3 WebIDL type: unsigned long * @param attributes1 WebIDL type: unsigned long * @param filterData1w0 WebIDL type: unsigned long * @param filterData1w1 WebIDL type: unsigned long * @param filterData1w2 WebIDL type: unsigned long * @param filterData1w3 WebIDL type: unsigned long * @return WebIDL type: unsigned long */ fun filterShader(attributes0: Int, filterData0w0: Int, filterData0w1: Int, filterData0w2: Int, filterData0w3: Int, attributes1: Int, filterData1w0: Int, filterData1w1: Int, filterData1w2: Int, filterData1w3: Int): Int } fun PassThroughFilterShader.destroy() { PhysXJsLoader.destroy(this) } external interface JavaPassThroughFilterShader : PassThroughFilterShader { /** * param attributes0 WebIDL type: unsigned long * param filterData0w0 WebIDL type: unsigned long * param filterData0w1 WebIDL type: unsigned long * param filterData0w2 WebIDL type: unsigned long * param filterData0w3 WebIDL type: unsigned long * param attributes1 WebIDL type: unsigned long * param filterData1w0 WebIDL type: unsigned long * param filterData1w1 WebIDL type: unsigned long * param filterData1w2 WebIDL type: unsigned long * param filterData1w3 WebIDL type: unsigned long * return WebIDL type: unsigned long */ var filterShader: (attributes0: Int, filterData0w0: Int, filterData0w1: Int, filterData0w2: Int, filterData0w3: Int, attributes1: Int, filterData1w0: Int, filterData1w1: Int, filterData1w2: Int, filterData1w3: Int) -> Int } fun JavaPassThroughFilterShader(): JavaPassThroughFilterShader { fun _JavaPassThroughFilterShader(_module: dynamic) = js("new _module.JavaPassThroughFilterShader()") return _JavaPassThroughFilterShader(PhysXJsLoader.physXJs) } object PxPvdInstrumentationFlagEnum { val eDEBUG: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxPvdInstrumentationFlagEnum_eDEBUG() val ePROFILE: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxPvdInstrumentationFlagEnum_ePROFILE() val eMEMORY: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxPvdInstrumentationFlagEnum_eMEMORY() val eALL: Int get() = PhysXJsLoader.physXJs._emscripten_enum_PxPvdInstrumentationFlagEnum_eALL() }
kool-physics/src/jsMain/kotlin/physx/Support.kt
161452087
package v_builders.examples import junit.framework.Assert import org.junit.Test import java.util.HashMap class _38_The_Function_Apply { @Test fun testBuildString() { val expected = buildString() val actual = StringBuilder().myApply { append("Numbers: ") for (i in 1..10) { append(i) } }.toString() Assert.assertEquals("String should be built:", expected, actual) } @Test fun testBuildMap() { val expected = buildMap() val actual = HashMap<Int, String>().myApply { put(0, "0") for (i in 1..10) { put(i, "$i") } } Assert.assertEquals("Map should be filled with the right values", expected, actual) } }
test/v_builders/_38_The_Function_Apply.kt
1045677604
package com.kelsos.mbrc.ui.navigation.library.album_tracks import toothpick.config.Module class AlbumTracksModule : Module() { init { bind(AlbumTracksPresenter::class.java).to(AlbumTracksPresenterImpl::class.java) .singletonInScope() } }
app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/library/album_tracks/AlbumTracksModule.kt
3546883718
fun a() { while (<caret>) } // SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS
plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyConditionInWhile.kt
541145297
/* * Copyright (C) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.data import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.util.UUID /** * Immutable model class for a Task. In order to compile with Room, we can't use @JvmOverloads to * generate multiple constructors. * * @param title title of the task * @param description description of the task * @param isCompleted whether or not this task is completed * @param id id of the task */ @Entity(tableName = "tasks") data class Task @JvmOverloads constructor( @ColumnInfo(name = "title") var title: String = "", @ColumnInfo(name = "description") var description: String = "", @ColumnInfo(name = "completed") var isCompleted: Boolean = false, @PrimaryKey @ColumnInfo(name = "entryid") var id: String = UUID.randomUUID().toString() ) { val titleForList: String get() = if (title.isNotEmpty()) title else description val isActive get() = !isCompleted val isEmpty get() = title.isEmpty() || description.isEmpty() }
app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/Task.kt
2327300220
class Solution { fun toRomanAux(one: Char, five: Char, ten: Char): (Int) -> List<Char> = { /* n: 0~9 */ n : Int -> when (n) { in 0..3 -> List(n) { one } 4 -> listOf(one, five) in 5..8 -> listOf(five) + List(n-5) { one } 9 -> listOf(one, ten) else -> throw IllegalArgumentException("Unexpected input") } } fun intToRoman(num: Int): String { val numDs = num % 10 val numTs = (num % 100 - numDs) / 10 val numHs = (num % 1000 - numTs*10 - numDs) / 100 val numKs = (num % 10000 - numHs * 100 - numTs*10 - numDs) / 1000 val rKs = toRomanAux('M','?','?')(numKs) val rHs = toRomanAux('C','D','M')(numHs) val rTs = toRomanAux('X','L','C')(numTs) val rDs = toRomanAux('I','V','X')(numDs) return (rKs + rHs + rTs + rDs).joinToString("") } companion object { @JvmStatic fun main(args: Array<String>) { println(Solution().intToRoman(3) == "III") println(Solution().intToRoman(1994) == "MCMXCIV") } } }
integer-to-roman/Solution.kt
3856460801
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.images import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.MarkdownTestingUtil class MarkdownConfigureImageLineMarkerTooltipTest: BasePlatformTestCase() { fun `test markdown image with empty link`() { doTest("![some image]()", getMessage()) } fun `test markdown image with simple system path`() { doTest("![some image](image.png)", getMessage("image.png")) } fun `test markdown image with relative system path`() { doTest("![some image](../image.png)", getMessage("image.png")) } fun `test markdown image with long system path`() { doTest("![some image](/Users/user/home/Pictures/image.png)", getMessage("image.png")) } fun `test markdown image with windows path`() { doTest("![some image](user\\home\\Pictures\\image.png)", getMessage("image.png")) } fun `test markdown image with relative windows path`() { doTest("![some image](..\\image.png)", getMessage("image.png")) } fun `test markdown image with url`() { doTest("![some image](https://some.com/sub/path/image.png)", getMessage("image.png")) } fun `test markdown image with weird url`() { doTest("![some image](https://some.com/sub/actual-image?parameter=image.png)", getMessage("actual-image")) } private fun getMessage(file: String): String { return MarkdownBundle.message("markdown.configure.image.line.marker.presentation", file) } private fun getMessage(): String { return MarkdownBundle.message("markdown.configure.image.text") } private fun doTest(content: String, expectedTooltip: String) { doTest(content, listOf(expectedTooltip)) } private fun doTest(content: String, expectedTooltips: Iterable<String>) { myFixture.configureByText(getTestFileName(), content) // Workaround for org.intellij.plugins.markdown.injection.MarkdownCodeFenceErrorHighlightingIntention.SettingsListener (myFixture as CodeInsightTestFixtureImpl).canChangeDocumentDuringHighlighting(true) myFixture.doHighlighting() val markers = DaemonCodeAnalyzerImpl.getLineMarkers(myFixture.editor.document, myFixture.project) val tooltips = markers.mapNotNull { it.lineMarkerTooltip }.sorted() assertEquals(expectedTooltips.sorted(), tooltips) } private fun getTestFileName(): String { return "${getTestName(false)}.md" } override fun getTestName(lowercaseFirstLetter: Boolean): String { val name = super.getTestName(lowercaseFirstLetter) return name.trimStart().replace(' ', '_') } override fun getTestDataPath(): String { return "${MarkdownTestingUtil.TEST_DATA_PATH}/editor/images/markers/" } }
plugins/markdown/test/src/org/intellij/plugins/markdown/editor/images/MarkdownConfigureImageLineMarkerTooltipTest.kt
2663026104
package inline @JvmName("test") inline fun g() = 0
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/other/inlineTopLevelFunctionWithJvmName/inline.kt
3633363155
package com.zeke.demo.draw.base_api import android.content.Context import android.graphics.* import android.util.AttributeSet import com.zeke.demo.base.BasePracticeView import com.zeke.kangaroo.utils.UIUtils class Practice3RectView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : BasePracticeView(context, attrs, defStyleAttr) { var rect = Rect(50, 50, 500, 350) private var rectF_Inner = RectF(100f, 100f, 450f, 300f) private var rectF = RectF(550f, 50f, 1000f, 350f) override fun onDraw(canvas: Canvas) { super.onDraw(canvas ) //练习内容:使用 canvas.drawRect() 方法画矩形 //练习内容:使用 canvas.drawRoundRect() 方法画圆角矩形 paint.style = Paint.Style.STROKE paint.color = Color.BLACK paint.strokeWidth = UIUtils.px2dip(context, 30f).toFloat() canvas.drawRect(rect, paint) paint.style = Paint.Style.FILL paint.color = Color.MAGENTA canvas.drawRoundRect(rectF_Inner, 60f, 60f, paint) paint.style = Paint.Style.STROKE canvas.drawRoundRect(rectF, 40f, 40f, paint) } override fun getViewHeight(): Int { return 400 } }
module-Demo/src/main/java/com/zeke/demo/draw/base_api/Practice3RectView.kt
1822594287
package com.intellij.settingsSync import java.util.* internal fun interface SettingsChangeListener : EventListener { fun settingChanged(event: SyncSettingsEvent) } internal sealed class SyncSettingsEvent { class IdeChange(val snapshot: SettingsSnapshot) : SyncSettingsEvent() class CloudChange(val snapshot: SettingsSnapshot) : SyncSettingsEvent() object PushIfNeededRequest : SyncSettingsEvent() object MustPushRequest: SyncSettingsEvent() object LogCurrentSettings: SyncSettingsEvent() } internal data class SettingsSnapshot(val fileStates: Set<FileState>) { fun isEmpty(): Boolean = fileStates.isEmpty() }
plugins/settings-sync/src/com/intellij/settingsSync/SettingsChangeListener.kt
1461304390
// "Create enum constant 'A'" "false" // ACTION: Create annotation 'A' // ACTION: Create class 'A' // ACTION: Create enum 'A' // ACTION: Create interface 'A' // ACTION: Create object 'A' // ACTION: Do not show return expression hints // ACTION: Rename reference // ERROR: Unresolved reference: A package p import p.X.<caret>A class X { }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createClass/importDirective/enumEntryWithQualifier.kt
2016538611
// FIR_IDENTICAL // FIR_COMPARISON fun bar() { val handler = { i: Int, s: <caret> } } // EXIST: Int // EXIST: String // ABSENT: bar // ABSENT: handler
plugins/kotlin/completion/tests/testData/basic/common/lambdaSignature/ParameterType2.kt
795147072
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.kotlin import org.jetbrains.uast.UFile import org.junit.Ignore import org.junit.Test import java.io.File class KotlinIDERenderLogTest : AbstractKotlinUastLightCodeInsightFixtureTest(), AbstractKotlinRenderLogTest { override val testDataDirectory: File get() = TEST_KOTLIN_MODEL_DIR override fun getTestFile(testName: String, ext: String): File { if (ext.endsWith(".txt")) { val testFile = super.getTestFile(testName, ext.removeSuffix(".txt") + "-ide.txt") if (testFile.exists()) return testFile } return super.getTestFile(testName, ext) } override fun check(testName: String, file: UFile) = super.check(testName, file) @Test fun testLocalDeclarations() = doTest("LocalDeclarations") @Test fun testSimple() = doTest("Simple") @Test fun testWhenIs() = doTest("WhenIs") @Test fun testDefaultImpls() = doTest("DefaultImpls") @Test fun testBitwise() = doTest("Bitwise") @Test fun testElvis() = doTest("Elvis") @Test fun testPropertyAccessors() = doTest("PropertyAccessors") @Test fun testPropertyInitializer() = doTest("PropertyInitializer") @Test fun testPropertyInitializerWithoutSetter() = doTest("PropertyInitializerWithoutSetter") @Test fun testAnnotationParameters() = doTest("AnnotationParameters") @Test fun testEnumValueMembers() = doTest("EnumValueMembers") @Test fun testEnumValuesConstructors() = doTest("EnumValuesConstructors") @Test fun testStringTemplate() = doTest("StringTemplate") @Test fun testStringTemplateComplex() = doTest("StringTemplateComplex") @Test fun testStringTemplateComplexForUInjectionHost() = withForceUInjectionHostValue { doTest("StringTemplateComplexForUInjectionHost") } @Test fun testQualifiedConstructorCall() = doTest("QualifiedConstructorCall") @Test fun testPropertyDelegate() = doTest("PropertyDelegate") @Test fun testLocalVariableWithAnnotation() = doTest("LocalVariableWithAnnotation") @Test fun testPropertyWithAnnotation() = doTest("PropertyWithAnnotation") @Test fun testIfStatement() = doTest("IfStatement") @Test fun testInnerClasses() = doTest("InnerClasses") @Test @Ignore // there is a descriptor leak probably, unignore when fixed fun ingoretestSimpleScript() = doTest("SimpleScript") { testName, file -> check(testName, file, false) } @Test fun testDestructuringDeclaration() = doTest("DestructuringDeclaration") @Test fun testDefaultParameterValues() = doTest("DefaultParameterValues") @Test fun testParameterPropertyWithAnnotation() = doTest("ParameterPropertyWithAnnotation") @Test fun testParametersWithDefaultValues() = doTest("ParametersWithDefaultValues") @Test fun testUnexpectedContainer() = doTest("UnexpectedContainerException") @Test fun testWhenStringLiteral() = doTest("WhenStringLiteral") @Test fun testWhenAndDestructing() = doTest("WhenAndDestructing") { testName, file -> check(testName, file, false) } @Test fun testSuperCalls() = doTest("SuperCalls") @Test fun testConstructors() = doTest("Constructors") @Test fun testClassAnnotation() = doTest("ClassAnnotation") @Test fun testReceiverFun() = doTest("ReceiverFun") @Test fun testAnonymous() = doTest("Anonymous") @Test fun testAnnotationComplex() = doTest("AnnotationComplex") @Test fun testParametersDisorder() = doTest("ParametersDisorder") { testName, file -> // disabled due to inconsistent parents for 2-receivers call (KT-22344) check(testName, file, false) } @Test fun testLambdas() = doTest("Lambdas") @Test fun testTypeReferences() = doTest("TypeReferences") @Test fun testDelegate() = doTest("Delegate") @Test fun testConstructorDelegate() = doTest("ConstructorDelegate") { testName, file -> // Igor Yakovlev told that delegation is a little bit broken in ULC and not expected to be fixed check(testName, file, false) } @Test fun testLambdaReturn() = doTest("LambdaReturn") @Test fun testReified() = doTest("Reified") @Test fun testReifiedReturnType() = doTest("ReifiedReturnType") @Test fun testReifiedParameters() = doTest("ReifiedParameters") @Test fun testSuspend() = doTest("Suspend") @Test fun testDeprecatedHidden() = doTest("DeprecatedHidden") @Test fun testTryCatch() = doTest("TryCatch") @Test fun testComments() = doTest("Comments") }
plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/KotlinIDERenderLogTest.kt
2678194297
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.testutils import android.content.Context import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import java.util.ArrayList import kotlin.math.ceil import kotlin.math.floor /** One [MotionEvent] approximately every 10 milliseconds. We care about this frequency because a * standard touchscreen operates at 100 Hz and therefore produces about one touch event every * 10 milliseconds. We want to produce a similar frequency to emulate real world input events.*/ const val MOTION_EVENT_INTERVAL_MILLIS: Int = 10 /** * Distance and time span necessary to produce a fling. * * Distance and time necessary to produce a fling for [MotionEvent] * * @property distance Distance between [MotionEvent]s in pixels for a fling. * @property time Time between [MotionEvent]s in milliseconds for a fling. */ data class FlingData(val distance: Float, val time: Int) { /** * @property velocity Velocity of fling in pixels per millisecond. */ val velocity: Float = distance / time } data class MotionEventData( val eventTimeDelta: Int, val action: Int, val x: Float, val y: Float, val metaState: Int ) enum class Direction { UP, DOWN, LEFT, RIGHT } fun MotionEventData.toMotionEvent(downTime: Long): MotionEvent = MotionEvent.obtain( downTime, this.eventTimeDelta + downTime, this.action, this.x, this.y, this.metaState ) /** * Constructs a [FlingData] from a [Context] and [velocityPixelsPerSecond]. * * [velocityPixelsPerSecond] must between [ViewConfiguration.getScaledMinimumFlingVelocity] * 1.1 * and [ViewConfiguration.getScaledMaximumFlingVelocity] * .9, inclusive. Losses of precision do * not allow the simulated fling to be super precise. */ @JvmOverloads fun generateFlingData(context: Context, velocityPixelsPerSecond: Float? = null): FlingData { val configuration = ViewConfiguration.get(context) val touchSlop = configuration.scaledTouchSlop val minimumVelocity = configuration.scaledMinimumFlingVelocity val maximumVelocity = configuration.scaledMaximumFlingVelocity val targetPixelsPerMilli = if (velocityPixelsPerSecond != null) { if (velocityPixelsPerSecond < minimumVelocity * 1.1 - .001f || velocityPixelsPerSecond > maximumVelocity * .9 + .001f ) { throw IllegalArgumentException( "velocityPixelsPerSecond must be between " + "ViewConfiguration.scaledMinimumFlingVelocity * 1.1 and " + "ViewConfiguration.scaledMinimumFlingVelocity * .9, inclusive" ) } velocityPixelsPerSecond / 1000f } else { ((maximumVelocity + minimumVelocity) / 2) / 1000f } val targetDistancePixels = touchSlop * 2 val targetMillisPassed = floor(targetDistancePixels / targetPixelsPerMilli).toInt() if (targetMillisPassed < 1) { throw IllegalArgumentException("Flings must require some time") } return FlingData(targetDistancePixels.toFloat(), targetMillisPassed) } /** * Returns [value] rounded up to the closest [interval] * N, where N is a Integer. */ private fun ceilToInterval(value: Int, interval: Int): Int = ceil(value.toFloat() / interval).toInt() * interval /** * Generates a [List] of [MotionEventData] starting from ([originX], [originY]) that will cause a * fling in the finger direction [Direction]. */ fun FlingData.generateFlingMotionEventData( originX: Float, originY: Float, fingerDirection: Direction ): List<MotionEventData> { // Ceiling the time and distance to match up with motion event intervals. val time: Int = ceilToInterval(this.time, MOTION_EVENT_INTERVAL_MILLIS) val distance: Float = velocity * time val dx: Float = when (fingerDirection) { Direction.LEFT -> -distance Direction.RIGHT -> distance else -> 0f } val dy: Float = when (fingerDirection) { Direction.UP -> -distance Direction.DOWN -> distance else -> 0f } val toX = originX + dx val toY = originY + dy val numberOfInnerEvents = (time / MOTION_EVENT_INTERVAL_MILLIS) - 1 val dxIncrement = dx / (numberOfInnerEvents + 1) val dyIncrement = dy / (numberOfInnerEvents + 1) val motionEventData = ArrayList<MotionEventData>() motionEventData.add(MotionEventData(0, MotionEvent.ACTION_DOWN, originX, originY, 0)) for (i in 1..(numberOfInnerEvents)) { val timeDelta = i * MOTION_EVENT_INTERVAL_MILLIS val x = originX + (i * dxIncrement) val y = originY + (i * dyIncrement) motionEventData.add(MotionEventData(timeDelta, MotionEvent.ACTION_MOVE, x, y, 0)) } motionEventData.add(MotionEventData(time, MotionEvent.ACTION_MOVE, toX, toY, 0)) motionEventData.add(MotionEventData(time, MotionEvent.ACTION_UP, toX, toY, 0)) return motionEventData } /** * Dispatches an array of [MotionEvent] to a [View]. * * The MotionEvents will start at [downTime] and will be generated from the [motionEventData]. * The MotionEvents will be dispatched synchronously, one after the other, with no gaps of time * in between each [MotionEvent]. * */ fun View.dispatchTouchEvents(downTime: Long, motionEventData: List<MotionEventData>) { for (motionEventDataItem in motionEventData) { dispatchTouchEvent(motionEventDataItem.toMotionEvent(downTime)) } } /** * Simulates a fling on a [View]. * * Convenience method that calls other public api. See documentation of those functions for more * detail. * * @see [generateFlingData] * @see [generateFlingMotionEventData] * @see [dispatchTouchEvents] */ @JvmOverloads fun View.simulateFling( downTime: Long, originX: Float, originY: Float, direction: Direction, velocityPixelsPerSecond: Float? = null ) { dispatchTouchEvents( downTime, generateFlingData(context, velocityPixelsPerSecond) .generateFlingMotionEventData(originX, originY, direction) ) }
testutils/testutils-runtime/src/main/java/androidx/testutils/SimpleGestureGenerator.kt
3832798628
package com.simplemobiletools.commons.adapters import android.content.Context import android.view.* import android.widget.PopupMenu import com.simplemobiletools.commons.R import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.extensions.copyToClipboard import com.simplemobiletools.commons.extensions.deleteBlockedNumber import com.simplemobiletools.commons.extensions.getPopupMenuTheme import com.simplemobiletools.commons.extensions.getProperTextColor import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener import com.simplemobiletools.commons.models.BlockedNumber import com.simplemobiletools.commons.views.MyRecyclerView import kotlinx.android.synthetic.main.item_manage_blocked_number.view.* class ManageBlockedNumbersAdapter( activity: BaseSimpleActivity, var blockedNumbers: ArrayList<BlockedNumber>, val listener: RefreshRecyclerViewListener?, recyclerView: MyRecyclerView, itemClick: (Any) -> Unit ) : MyRecyclerViewAdapter(activity, recyclerView, itemClick) { init { setupDragListener(true) } override fun getActionMenuId() = R.menu.cab_blocked_numbers override fun prepareActionMode(menu: Menu) { menu.apply { findItem(R.id.cab_copy_number).isVisible = isOneItemSelected() } } override fun actionItemPressed(id: Int) { if (selectedKeys.isEmpty()) { return } when (id) { R.id.cab_copy_number -> copyNumberToClipboard() R.id.cab_delete -> deleteSelection() } } override fun getSelectableItemCount() = blockedNumbers.size override fun getIsItemSelectable(position: Int) = true override fun getItemSelectionKey(position: Int) = blockedNumbers.getOrNull(position)?.id?.toInt() override fun getItemKeyPosition(key: Int) = blockedNumbers.indexOfFirst { it.id.toInt() == key } override fun onActionModeCreated() {} override fun onActionModeDestroyed() {} override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(R.layout.item_manage_blocked_number, parent) override fun onBindViewHolder(holder: ViewHolder, position: Int) { val blockedNumber = blockedNumbers[position] holder.bindView(blockedNumber, true, true) { itemView, _ -> setupView(itemView, blockedNumber) } bindViewHolder(holder) } override fun getItemCount() = blockedNumbers.size private fun getSelectedItems() = blockedNumbers.filter { selectedKeys.contains(it.id.toInt()) } as ArrayList<BlockedNumber> private fun setupView(view: View, blockedNumber: BlockedNumber) { view.apply { manage_blocked_number_holder?.isSelected = selectedKeys.contains(blockedNumber.id.toInt()) manage_blocked_number_title.apply { text = blockedNumber.number setTextColor(textColor) } overflow_menu_icon.drawable.apply { mutate() setTint(activity.getProperTextColor()) } overflow_menu_icon.setOnClickListener { showPopupMenu(overflow_menu_anchor, blockedNumber) } } } private fun showPopupMenu(view: View, blockedNumber: BlockedNumber) { finishActMode() val theme = activity.getPopupMenuTheme() val contextTheme = ContextThemeWrapper(activity, theme) PopupMenu(contextTheme, view, Gravity.END).apply { inflate(getActionMenuId()) setOnMenuItemClickListener { item -> val blockedNumberId = blockedNumber.id.toInt() when (item.itemId) { R.id.cab_copy_number -> { executeItemMenuOperation(blockedNumberId) { copyNumberToClipboard() } } R.id.cab_delete -> { executeItemMenuOperation(blockedNumberId) { deleteSelection() } } } true } show() } } private fun executeItemMenuOperation(blockedNumberId: Int, callback: () -> Unit) { selectedKeys.add(blockedNumberId) callback() selectedKeys.remove(blockedNumberId) } private fun copyNumberToClipboard() { val selectedNumber = getSelectedItems().firstOrNull() ?: return activity.copyToClipboard(selectedNumber.number) finishActMode() } private fun deleteSelection() { val deleteBlockedNumbers = ArrayList<BlockedNumber>(selectedKeys.size) val positions = getSelectedItemPositions() getSelectedItems().forEach { deleteBlockedNumbers.add(it) activity.deleteBlockedNumber(it.number) } blockedNumbers.removeAll(deleteBlockedNumbers) removeSelectedItems(positions) if (blockedNumbers.isEmpty()) { listener?.refreshItems() } } }
commons/src/main/kotlin/com/simplemobiletools/commons/adapters/ManageBlockedNumbersAdapter.kt
189568549
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.integration.demos import android.app.Activity import androidx.activity.ComponentActivity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.wear.compose.material.Button import androidx.wear.compose.material.ButtonDefaults import androidx.wear.compose.material.Icon import androidx.wear.compose.material.LocalContentAlpha import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.SwipeToDismissBoxState import androidx.wear.compose.material.Text import kotlin.reflect.KClass /** * Generic demo with a [title] that will be displayed in the list of demos. */ sealed class Demo(val title: String, val description: String? = null) { override fun toString() = title } /** * Demo that launches an [Activity] when selected. * * This should only be used for demos that need to customize the activity, the large majority of * demos should just use [ComposableDemo] instead. * * @property activityClass the KClass (Foo::class) of the activity that will be launched when * this demo is selected. */ class ActivityDemo<T : ComponentActivity>(title: String, val activityClass: KClass<T>) : Demo(title) /** * A category of [Demo]s, that will display a list of [demos] when selected. */ class DemoCategory( title: String, val demos: List<Demo> ) : Demo(title) /** * Parameters which are used by [Demo] screens. */ class DemoParameters( val navigateBack: () -> Unit, val swipeToDismissBoxState: SwipeToDismissBoxState ) /** * Demo that displays [Composable] [content] when selected, * with a method to navigate back to the parent. */ class ComposableDemo( title: String, description: String? = null, val content: @Composable (params: DemoParameters) -> Unit, ) : Demo(title, description) /** * A simple [Icon] with default size */ @Composable fun DemoIcon( resourceId: Int, modifier: Modifier = Modifier, size: Dp = 24.dp, contentDescription: String? = null, ) { Icon( painter = painterResource(id = resourceId), contentDescription = contentDescription, modifier = modifier .size(size) .wrapContentSize(align = Alignment.Center), ) } @Composable fun DemoImage( resourceId: Int, modifier: Modifier = Modifier, size: Dp = 24.dp, ) { Image( painter = painterResource(id = resourceId), contentDescription = null, modifier = modifier.size(size), contentScale = ContentScale.Crop, alpha = LocalContentAlpha.current ) } @Composable fun TextIcon( text: String, size: Dp = 24.dp, style: TextStyle = MaterialTheme.typography.title2 ) { Button( modifier = Modifier .padding(0.dp) .requiredSize(32.dp), onClick = {}, colors = ButtonDefaults.buttonColors( disabledBackgroundColor = MaterialTheme.colors.primary.copy( alpha = LocalContentAlpha.current ), disabledContentColor = MaterialTheme.colors.onPrimary.copy( alpha = LocalContentAlpha.current ) ), enabled = false ) { Box( modifier = Modifier .padding(all = 0.dp) .requiredSize(size) .wrapContentSize(align = Alignment.Center) ) { Text( text = text, textAlign = TextAlign.Center, color = MaterialTheme.colors.onPrimary.copy(alpha = LocalContentAlpha.current), style = style, ) } } } @Composable fun Centralize(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) { Column( modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, content = content ) } public val DemoListTag = "DemoListTag" public val AlternatePrimaryColor1 = Color(0x7F, 0xCF, 0xFF) public val AlternatePrimaryColor2 = Color(0xD0, 0xBC, 0xFF) public val AlternatePrimaryColor3 = Color(0x6D, 0xD5, 0x8C)
wear/compose/integration-tests/demos/src/main/java/androidx/wear/compose/integration/demos/DemoComponents.kt
2440967803
package de.liz3.liz3web.util.extension.js.backend import de.liz3.liz3web.util.extension.ExtensionExecutor /** * Created by liz3 on 28.07.17. */ class Chrome(val executor: ExtensionExecutor) { fun test() = "Das ist eine kleine test nachricht" } class ChromeRuntime(val executor: ExtensionExecutor) { }
src/main/java/de/liz3/liz3web/util/extension/js/backend/Chrome.kt
2961625179
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform internal inline fun ifDebug(block: () -> Unit) { // Right now, we always run these. At a later point, we may revisit this block() } internal expect fun simpleIdentityToString(obj: Any, name: String?): String
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/platform/DebugUtils.kt
2244110537
package kotlinx.html import kotlinx.html.* import kotlinx.html.impl.* import kotlinx.html.attributes.* /******************************************************************************* DO NOT EDIT This file was generated by module generate *******************************************************************************/ interface FlowOrMetaDataOrPhrasingContent : Tag { } interface FlowOrHeadingContent : Tag { } interface FlowOrMetaDataContent : FlowOrMetaDataOrPhrasingContent, Tag { } interface FlowOrInteractiveContent : FlowOrInteractiveOrPhrasingContent, Tag { } interface FlowOrPhrasingContent : FlowOrInteractiveOrPhrasingContent, FlowOrMetaDataOrPhrasingContent, Tag { } interface SectioningOrFlowContent : Tag { } interface FlowOrInteractiveOrPhrasingContent : Tag { } @HtmlTagMarker inline fun FlowOrMetaDataOrPhrasingContent.command(type : CommandType? = null, classes : String? = null, crossinline block : COMMAND.() -> Unit = {}) : Unit = COMMAND(attributesMapOf("type", type?.enumEncode(),"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrMetaDataOrPhrasingContent.commandCommand(classes : String? = null, crossinline block : COMMAND.() -> Unit = {}) : Unit = COMMAND(attributesMapOf("type", CommandType.command.realValue,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrMetaDataOrPhrasingContent.checkBoxCommand(classes : String? = null, crossinline block : COMMAND.() -> Unit = {}) : Unit = COMMAND(attributesMapOf("type", CommandType.checkBox.realValue,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrMetaDataOrPhrasingContent.radioCommand(classes : String? = null, crossinline block : COMMAND.() -> Unit = {}) : Unit = COMMAND(attributesMapOf("type", CommandType.radio.realValue,"class", classes), consumer).visit(block) /** * A media-independent link */ @HtmlTagMarker inline fun FlowOrMetaDataOrPhrasingContent.link(href : String? = null, rel : String? = null, type : String? = null, crossinline block : LINK.() -> Unit = {}) : Unit = LINK(attributesMapOf("href", href,"rel", rel,"type", type), consumer).visit(block) /** * Generic metainformation */ @HtmlTagMarker inline fun FlowOrMetaDataOrPhrasingContent.meta(name : String? = null, content : String? = null, charset : String? = null, crossinline block : META.() -> Unit = {}) : Unit = META(attributesMapOf("name", name,"content", content,"charset", charset), consumer).visit(block) /** * Generic metainformation */ @HtmlTagMarker inline fun FlowOrMetaDataOrPhrasingContent.noScript(classes : String? = null, crossinline block : NOSCRIPT.() -> Unit = {}) : Unit = NOSCRIPT(attributesMapOf("class", classes), consumer).visit(block) /** * Script statements */ @HtmlTagMarker inline fun FlowOrMetaDataOrPhrasingContent.script(type : String? = null, src : String? = null, crossinline block : SCRIPT.() -> Unit = {}) : Unit = SCRIPT(attributesMapOf("type", type,"src", src), consumer).visit(block) @Deprecated("This tag doesn't support content or requires unsafe (try unsafe {})") @Suppress("DEPRECATION") /** * Script statements */ @HtmlTagMarker fun FlowOrMetaDataOrPhrasingContent.script(type : String? = null, src : String? = null, content : String = "") : Unit = SCRIPT(attributesMapOf("type", type,"src", src), consumer).visit({+content}) /** * Heading */ @HtmlTagMarker inline fun FlowOrHeadingContent.h1(classes : String? = null, crossinline block : H1.() -> Unit = {}) : Unit = H1(attributesMapOf("class", classes), consumer).visit(block) /** * Heading */ @HtmlTagMarker inline fun FlowOrHeadingContent.h2(classes : String? = null, crossinline block : H2.() -> Unit = {}) : Unit = H2(attributesMapOf("class", classes), consumer).visit(block) /** * Heading */ @HtmlTagMarker inline fun FlowOrHeadingContent.h3(classes : String? = null, crossinline block : H3.() -> Unit = {}) : Unit = H3(attributesMapOf("class", classes), consumer).visit(block) /** * Heading */ @HtmlTagMarker inline fun FlowOrHeadingContent.h4(classes : String? = null, crossinline block : H4.() -> Unit = {}) : Unit = H4(attributesMapOf("class", classes), consumer).visit(block) /** * Heading */ @HtmlTagMarker inline fun FlowOrHeadingContent.h5(classes : String? = null, crossinline block : H5.() -> Unit = {}) : Unit = H5(attributesMapOf("class", classes), consumer).visit(block) /** * Heading */ @HtmlTagMarker inline fun FlowOrHeadingContent.h6(classes : String? = null, crossinline block : H6.() -> Unit = {}) : Unit = H6(attributesMapOf("class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrHeadingContent.hGroup(classes : String? = null, crossinline block : HGROUP.() -> Unit = {}) : Unit = HGROUP(attributesMapOf("class", classes), consumer).visit(block) /** * Style info */ @HtmlTagMarker inline fun FlowOrMetaDataContent.style(type : String? = null, crossinline block : STYLE.() -> Unit = {}) : Unit = STYLE(attributesMapOf("type", type), consumer).visit(block) @Deprecated("This tag doesn't support content or requires unsafe (try unsafe {})") @Suppress("DEPRECATION") /** * Style info */ @HtmlTagMarker fun FlowOrMetaDataContent.style(type : String? = null, content : String = "") : Unit = STYLE(attributesMapOf("type", type), consumer).visit({+content}) /** * Disclosure control for hiding details */ @HtmlTagMarker inline fun FlowOrInteractiveContent.details(classes : String? = null, crossinline block : DETAILS.() -> Unit = {}) : Unit = DETAILS(attributesMapOf("class", classes), consumer).visit(block) /** * Abbreviated form (e.g., WWW, HTTP,etc.) */ @HtmlTagMarker inline fun FlowOrPhrasingContent.abbr(classes : String? = null, crossinline block : ABBR.() -> Unit = {}) : Unit = ABBR(attributesMapOf("class", classes), consumer).visit(block) /** * Client-side image map area */ @HtmlTagMarker inline fun FlowOrPhrasingContent.area(shape : AreaShape? = null, alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", shape?.enumEncode(),"alt", alt,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrPhrasingContent.rectArea(alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", AreaShape.rect.realValue,"alt", alt,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrPhrasingContent.circleArea(alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", AreaShape.circle.realValue,"alt", alt,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrPhrasingContent.polyArea(alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", AreaShape.poly.realValue,"alt", alt,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrPhrasingContent.defaultArea(alt : String? = null, classes : String? = null, crossinline block : AREA.() -> Unit = {}) : Unit = AREA(attributesMapOf("Shape", AreaShape.default.realValue,"alt", alt,"class", classes), consumer).visit(block) /** * Bold text style */ @HtmlTagMarker inline fun FlowOrPhrasingContent.b(classes : String? = null, crossinline block : B.() -> Unit = {}) : Unit = B(attributesMapOf("class", classes), consumer).visit(block) /** * Text directionality isolation */ @HtmlTagMarker inline fun FlowOrPhrasingContent.bdi(classes : String? = null, crossinline block : BDI.() -> Unit = {}) : Unit = BDI(attributesMapOf("class", classes), consumer).visit(block) /** * I18N BiDi over-ride */ @HtmlTagMarker inline fun FlowOrPhrasingContent.bdo(classes : String? = null, crossinline block : BDO.() -> Unit = {}) : Unit = BDO(attributesMapOf("class", classes), consumer).visit(block) /** * Forced line break */ @HtmlTagMarker inline fun FlowOrPhrasingContent.br(classes : String? = null, crossinline block : BR.() -> Unit = {}) : Unit = BR(attributesMapOf("class", classes), consumer).visit(block) /** * Scriptable bitmap canvas */ @HtmlTagMarker inline fun FlowOrPhrasingContent.canvas(classes : String? = null, crossinline block : CANVAS.() -> Unit = {}) : Unit = CANVAS(attributesMapOf("class", classes), consumer).visit(block) /** * Scriptable bitmap canvas */ @HtmlTagMarker fun FlowOrPhrasingContent.canvas(classes : String? = null, content : String = "") : Unit = CANVAS(attributesMapOf("class", classes), consumer).visit({+content}) /** * Citation */ @HtmlTagMarker inline fun FlowOrPhrasingContent.cite(classes : String? = null, crossinline block : CITE.() -> Unit = {}) : Unit = CITE(attributesMapOf("class", classes), consumer).visit(block) /** * Computer code fragment */ @HtmlTagMarker inline fun FlowOrPhrasingContent.code(classes : String? = null, crossinline block : CODE.() -> Unit = {}) : Unit = CODE(attributesMapOf("class", classes), consumer).visit(block) /** * Container for options for */ @HtmlTagMarker inline fun FlowOrPhrasingContent.dataList(classes : String? = null, crossinline block : DATALIST.() -> Unit = {}) : Unit = DATALIST(attributesMapOf("class", classes), consumer).visit(block) /** * Deleted text */ @HtmlTagMarker inline fun FlowOrPhrasingContent.del(classes : String? = null, crossinline block : DEL.() -> Unit = {}) : Unit = DEL(attributesMapOf("class", classes), consumer).visit(block) /** * Instance definition */ @HtmlTagMarker inline fun FlowOrPhrasingContent.dfn(classes : String? = null, crossinline block : DFN.() -> Unit = {}) : Unit = DFN(attributesMapOf("class", classes), consumer).visit(block) /** * Emphasis */ @HtmlTagMarker inline fun FlowOrPhrasingContent.em(classes : String? = null, crossinline block : EM.() -> Unit = {}) : Unit = EM(attributesMapOf("class", classes), consumer).visit(block) /** * Italic text style */ @HtmlTagMarker inline fun FlowOrPhrasingContent.i(classes : String? = null, crossinline block : I.() -> Unit = {}) : Unit = I(attributesMapOf("class", classes), consumer).visit(block) /** * Inserted text */ @HtmlTagMarker inline fun FlowOrPhrasingContent.ins(classes : String? = null, crossinline block : INS.() -> Unit = {}) : Unit = INS(attributesMapOf("class", classes), consumer).visit(block) /** * Text to be entered by the user */ @HtmlTagMarker inline fun FlowOrPhrasingContent.kbd(classes : String? = null, crossinline block : KBD.() -> Unit = {}) : Unit = KBD(attributesMapOf("class", classes), consumer).visit(block) /** * Client-side image map */ @HtmlTagMarker inline fun FlowOrPhrasingContent.map(name : String? = null, classes : String? = null, crossinline block : MAP.() -> Unit = {}) : Unit = MAP(attributesMapOf("name", name,"class", classes), consumer).visit(block) /** * Highlight */ @HtmlTagMarker inline fun FlowOrPhrasingContent.mark(classes : String? = null, crossinline block : MARK.() -> Unit = {}) : Unit = MARK(attributesMapOf("class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrPhrasingContent.math(classes : String? = null, crossinline block : MATH.() -> Unit = {}) : Unit = MATH(attributesMapOf("class", classes), consumer).visit(block) /** * Gauge */ @HtmlTagMarker inline fun FlowOrPhrasingContent.meter(classes : String? = null, crossinline block : METER.() -> Unit = {}) : Unit = METER(attributesMapOf("class", classes), consumer).visit(block) /** * Calculated output value */ @HtmlTagMarker inline fun FlowOrPhrasingContent.output(classes : String? = null, crossinline block : OUTPUT.() -> Unit = {}) : Unit = OUTPUT(attributesMapOf("class", classes), consumer).visit(block) /** * Progress bar */ @HtmlTagMarker inline fun FlowOrPhrasingContent.progress(classes : String? = null, crossinline block : PROGRESS.() -> Unit = {}) : Unit = PROGRESS(attributesMapOf("class", classes), consumer).visit(block) /** * Short inline quotation */ @HtmlTagMarker inline fun FlowOrPhrasingContent.q(classes : String? = null, crossinline block : Q.() -> Unit = {}) : Unit = Q(attributesMapOf("class", classes), consumer).visit(block) /** * Ruby annotation(s) */ @HtmlTagMarker inline fun FlowOrPhrasingContent.ruby(classes : String? = null, crossinline block : RUBY.() -> Unit = {}) : Unit = RUBY(attributesMapOf("class", classes), consumer).visit(block) /** * Strike-through text style */ @HtmlTagMarker inline fun FlowOrPhrasingContent.samp(classes : String? = null, crossinline block : SAMP.() -> Unit = {}) : Unit = SAMP(attributesMapOf("class", classes), consumer).visit(block) /** * Small text style */ @HtmlTagMarker inline fun FlowOrPhrasingContent.small(classes : String? = null, crossinline block : SMALL.() -> Unit = {}) : Unit = SMALL(attributesMapOf("class", classes), consumer).visit(block) /** * Generic language/style container */ @HtmlTagMarker inline fun FlowOrPhrasingContent.span(classes : String? = null, crossinline block : SPAN.() -> Unit = {}) : Unit = SPAN(attributesMapOf("class", classes), consumer).visit(block) /** * Strong emphasis */ @HtmlTagMarker inline fun FlowOrPhrasingContent.strong(classes : String? = null, crossinline block : STRONG.() -> Unit = {}) : Unit = STRONG(attributesMapOf("class", classes), consumer).visit(block) /** * Subscript */ @HtmlTagMarker inline fun FlowOrPhrasingContent.sub(classes : String? = null, crossinline block : SUB.() -> Unit = {}) : Unit = SUB(attributesMapOf("class", classes), consumer).visit(block) /** * Superscript */ @HtmlTagMarker inline fun FlowOrPhrasingContent.sup(classes : String? = null, crossinline block : SUP.() -> Unit = {}) : Unit = SUP(attributesMapOf("class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrPhrasingContent.svg(classes : String? = null, crossinline block : SVG.() -> Unit = {}) : Unit = SVG(attributesMapOf("class", classes), consumer).visit(block) @HtmlTagMarker fun FlowOrPhrasingContent.svg(classes : String? = null, content : String = "") : Unit = SVG(attributesMapOf("class", classes), consumer).visit({+content}) /** * Machine-readable equivalent of date- or time-related data */ @HtmlTagMarker inline fun FlowOrPhrasingContent.time(classes : String? = null, crossinline block : TIME.() -> Unit = {}) : Unit = TIME(attributesMapOf("class", classes), consumer).visit(block) /** * Unordered list */ @HtmlTagMarker inline fun FlowOrPhrasingContent.htmlVar(classes : String? = null, crossinline block : VAR.() -> Unit = {}) : Unit = VAR(attributesMapOf("class", classes), consumer).visit(block) /** * Self-contained syndicatable or reusable composition */ @HtmlTagMarker inline fun SectioningOrFlowContent.article(classes : String? = null, crossinline block : ARTICLE.() -> Unit = {}) : Unit = ARTICLE(attributesMapOf("class", classes), consumer).visit(block) /** * Sidebar for tangentially related content */ @HtmlTagMarker inline fun SectioningOrFlowContent.aside(classes : String? = null, crossinline block : ASIDE.() -> Unit = {}) : Unit = ASIDE(attributesMapOf("class", classes), consumer).visit(block) /** * Container for the dominant contents of another element */ @HtmlTagMarker inline fun SectioningOrFlowContent.main(classes : String? = null, crossinline block : MAIN.() -> Unit = {}) : Unit = MAIN(attributesMapOf("class", classes), consumer).visit(block) /** * Section with navigational links */ @HtmlTagMarker inline fun SectioningOrFlowContent.nav(classes : String? = null, crossinline block : NAV.() -> Unit = {}) : Unit = NAV(attributesMapOf("class", classes), consumer).visit(block) /** * Generic document or application section */ @HtmlTagMarker inline fun SectioningOrFlowContent.section(classes : String? = null, crossinline block : SECTION.() -> Unit = {}) : Unit = SECTION(attributesMapOf("class", classes), consumer).visit(block) /** * Anchor */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.a(href : String? = null, target : String? = null, classes : String? = null, crossinline block : A.() -> Unit = {}) : Unit = A(attributesMapOf("href", href,"target", target,"class", classes), consumer).visit(block) /** * Audio player */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.audio(classes : String? = null, crossinline block : AUDIO.() -> Unit = {}) : Unit = AUDIO(attributesMapOf("class", classes), consumer).visit(block) /** * Push button */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.button(formEncType : ButtonFormEncType? = null, formMethod : ButtonFormMethod? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.getButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.get.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.postButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.post.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block) @Suppress("DEPRECATION") @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.putButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.put.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block) @Suppress("DEPRECATION") @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.deleteButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.delete.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block) @Suppress("DEPRECATION") @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.patchButton(formEncType : ButtonFormEncType? = null, name : String? = null, type : ButtonType? = null, classes : String? = null, crossinline block : BUTTON.() -> Unit = {}) : Unit = BUTTON(attributesMapOf("formenctype", formEncType?.enumEncode(),"formmethod", ButtonFormMethod.patch.realValue,"name", name,"type", type?.enumEncode(),"class", classes), consumer).visit(block) /** * Plugin */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.embed(classes : String? = null, crossinline block : EMBED.() -> Unit = {}) : Unit = EMBED(attributesMapOf("class", classes), consumer).visit(block) /** * Inline subwindow */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.iframe(sandbox : IframeSandbox? = null, classes : String? = null, crossinline block : IFRAME.() -> Unit = {}) : Unit = IFRAME(attributesMapOf("sandbox", sandbox?.enumEncode(),"class", classes), consumer).visit(block) /** * Inline subwindow */ @HtmlTagMarker fun FlowOrInteractiveOrPhrasingContent.iframe(sandbox : IframeSandbox? = null, classes : String? = null, content : String = "") : Unit = IFRAME(attributesMapOf("sandbox", sandbox?.enumEncode(),"class", classes), consumer).visit({+content}) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.allowSameOriginIframe(classes : String? = null, crossinline block : IFRAME.() -> Unit = {}) : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowSameOrigin.realValue,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.allowFormSIframe(classes : String? = null, crossinline block : IFRAME.() -> Unit = {}) : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowFormS.realValue,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.allowScriptsIframe(classes : String? = null, crossinline block : IFRAME.() -> Unit = {}) : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowScripts.realValue,"class", classes), consumer).visit(block) @HtmlTagMarker fun FlowOrInteractiveOrPhrasingContent.allowSameOriginIframe(classes : String? = null, content : String = "") : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowSameOrigin.realValue,"class", classes), consumer).visit({+content}) @HtmlTagMarker fun FlowOrInteractiveOrPhrasingContent.allowFormSIframe(classes : String? = null, content : String = "") : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowFormS.realValue,"class", classes), consumer).visit({+content}) @HtmlTagMarker fun FlowOrInteractiveOrPhrasingContent.allowScriptsIframe(classes : String? = null, content : String = "") : Unit = IFRAME(attributesMapOf("sandbox", IframeSandbox.allowScripts.realValue,"class", classes), consumer).visit({+content}) /** * Embedded image */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.img(alt : String? = null, src : String? = null, classes : String? = null, crossinline block : IMG.() -> Unit = {}) : Unit = IMG(attributesMapOf("alt", alt,"src", src,"class", classes), consumer).visit(block) /** * Pictures container */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.picture(crossinline block : PICTURE.() -> Unit = {}) : Unit = PICTURE(emptyMap, consumer).visit(block) /** * Form control */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.input(type : InputType? = null, formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", type?.enumEncode(),"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.buttonInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.button.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.checkBoxInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.checkBox.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.colorInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.color.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.dateInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.date.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.dateTimeInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.dateTime.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.dateTimeLocalInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.dateTimeLocal.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.emailInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.email.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.fileInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.file.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.hiddenInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.hidden.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.imageInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.image.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.monthInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.month.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.numberInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.number.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.passwordInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.password.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.radioInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.radio.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.rangeInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.range.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.resetInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.reset.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.searchInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.search.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.submitInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.submit.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.textInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.text.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.telInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.tel.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.timeInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.time.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.urlInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.url.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.weekInput(formEncType : InputFormEncType? = null, formMethod : InputFormMethod? = null, name : String? = null, classes : String? = null, crossinline block : INPUT.() -> Unit = {}) : Unit = INPUT(attributesMapOf("type", InputType.week.realValue,"formenctype", formEncType?.enumEncode(),"formmethod", formMethod?.enumEncode(),"name", name,"class", classes), consumer).visit(block) /** * Cryptographic key-pair generator form control */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.keyGen(keyType : KeyGenKeyType? = null, classes : String? = null, crossinline block : KEYGEN.() -> Unit = {}) : Unit = KEYGEN(attributesMapOf("keytype", keyType?.enumEncode(),"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.rsaKeyGen(classes : String? = null, crossinline block : KEYGEN.() -> Unit = {}) : Unit = KEYGEN(attributesMapOf("keytype", KeyGenKeyType.rsa.realValue,"class", classes), consumer).visit(block) /** * Form field label text */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.label(classes : String? = null, crossinline block : LABEL.() -> Unit = {}) : Unit = LABEL(attributesMapOf("class", classes), consumer).visit(block) /** * Generic embedded object */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.htmlObject(classes : String? = null, crossinline block : OBJECT.() -> Unit = {}) : Unit = OBJECT(attributesMapOf("class", classes), consumer).visit(block) /** * Option selector */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.select(classes : String? = null, crossinline block : SELECT.() -> Unit = {}) : Unit = SELECT(attributesMapOf("class", classes), consumer).visit(block) /** * Multi-line text field */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.textArea(rows : String? = null, cols : String? = null, wrap : TextAreaWrap? = null, classes : String? = null, crossinline block : TEXTAREA.() -> Unit = {}) : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", wrap?.enumEncode(),"class", classes), consumer).visit(block) /** * Multi-line text field */ @HtmlTagMarker fun FlowOrInteractiveOrPhrasingContent.textArea(rows : String? = null, cols : String? = null, wrap : TextAreaWrap? = null, classes : String? = null, content : String = "") : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", wrap?.enumEncode(),"class", classes), consumer).visit({+content}) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.hardTextArea(rows : String? = null, cols : String? = null, classes : String? = null, crossinline block : TEXTAREA.() -> Unit = {}) : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", TextAreaWrap.hard.realValue,"class", classes), consumer).visit(block) @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.softTextArea(rows : String? = null, cols : String? = null, classes : String? = null, crossinline block : TEXTAREA.() -> Unit = {}) : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", TextAreaWrap.soft.realValue,"class", classes), consumer).visit(block) @HtmlTagMarker fun FlowOrInteractiveOrPhrasingContent.hardTextArea(rows : String? = null, cols : String? = null, classes : String? = null, content : String = "") : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", TextAreaWrap.hard.realValue,"class", classes), consumer).visit({+content}) @HtmlTagMarker fun FlowOrInteractiveOrPhrasingContent.softTextArea(rows : String? = null, cols : String? = null, classes : String? = null, content : String = "") : Unit = TEXTAREA(attributesMapOf("rows", rows,"cols", cols,"wrap", TextAreaWrap.soft.realValue,"class", classes), consumer).visit({+content}) /** * Video player */ @HtmlTagMarker inline fun FlowOrInteractiveOrPhrasingContent.video(classes : String? = null, crossinline block : VIDEO.() -> Unit = {}) : Unit = VIDEO(attributesMapOf("class", classes), consumer).visit(block)
src/commonMain/kotlin/generated/gen-tag-unions.kt
2331261108
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs import com.intellij.openapi.vfs.VirtualFile import java.awt.Color private class DefaultFileStatusManager : FileStatusManager() { override fun getStatus(file: VirtualFile): FileStatus = FileStatus.NOT_CHANGED override fun getNotChangedDirectoryColor(file: VirtualFile): Color = Color.BLACK override fun fileStatusesChanged() = Unit override fun fileStatusChanged(file: VirtualFile?) = Unit }
platform/editor-ui-api/src/com/intellij/openapi/vcs/DefaultFileStatusManager.kt
1612163284
package org.jetbrains.completion.full.line.platform import org.jetbrains.completion.full.line.AnalyzedFullLineProposal import org.jetbrains.completion.full.line.ProposalsFilter import org.jetbrains.completion.full.line.RawFullLineProposal import kotlin.math.min object RedCodeFilter : ProposalsFilter.Adapter("red code") { override fun checkAnalyzedFullLine(proposal: AnalyzedFullLineProposal): Boolean { return proposal.refCorrectness.isCorrect() } } class SameAsPrefixFilter(private val prefix: String) : ProposalsFilter.Adapter("same as prefix") { override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean { return proposal.suggestion != prefix } } object ProhibitedWordsFilter : ProposalsFilter.Adapter("prohibited words") { private val prohibited = listOf( "龖", "#", "print ", "BOS", "<PAD>", "<EOS>", "<UNK>" ) override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean { return prohibited.none { proposal.suggestion.contains(it) } } } object SemanticFilter : ProposalsFilter.Adapter("doesn't make sense") { override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean { return proposal.suggestion.find { it.isJavaIdentifierPart() || it.isDigit() } != null } } object EmptyStringFilter : ProposalsFilter.Adapter("empty") { override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean { return proposal.suggestion.isNotEmpty() } } object ScoreFilter : ProposalsFilter.Adapter("low score") { private const val scoreThreshold: Double = 0.1 override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean { return proposal.score > scoreThreshold } } object ASCIIFilter : ProposalsFilter.Adapter("non-ACII symbols") { override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean { return proposal.suggestion.toCharArray().none { it < ' ' || it > '~' } } } // Do not find repetition in sub-strings, only if whole string is repetition object RepetitionFilter : ProposalsFilter.Adapter("repetition") { private const val repetition = 3 override fun checkRawFullLine(proposal: RawFullLineProposal): Boolean { val zArr = zFunction(proposal.suggestion) return !findRepetition(zArr) } private fun findRepetition(arr: IntArray): Boolean { for ((i, z) in arr.withIndex()) { if ((i + z) == arr.size && arr.size % i == 0 && arr.size / i >= repetition) { return true } } return false } private fun zFunction(line: String): IntArray { val z = IntArray(line.length) var l = 0 var r = 0 for (i in 1..(line.length / 2)) { if (i <= r) { z[i] = min(r - i + 1, z[i - l]) } while (i + z[i] < line.length && line[z[i]] == line[i + z[i]]) { ++z[i] } if (i + z[i] - 1 > r) { l = i r = i + z[i] - 1 } } return z } }
plugins/full-line/src/org/jetbrains/completion/full/line/platform/ProposalFilters.kt
4248717046
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleTooling import org.gradle.api.tasks.Exec import org.jetbrains.kotlin.idea.gradleTooling.arguments.CompilerArgumentsCacheAwareImpl import org.jetbrains.kotlin.idea.projectModel.* import java.io.File import org.jetbrains.kotlin.idea.gradleTooling.arguments.createCachedArgsInfo class KotlinSourceSetProto( val name: String, private val languageSettings: KotlinLanguageSettings, private val sourceDirs: Set<File>, private val resourceDirs: Set<File>, private val regularDependencies: () -> Array<KotlinDependencyId>, private val intransitiveDependencies: () -> Array<KotlinDependencyId>, val dependsOnSourceSets: Set<String>, val additionalVisibleSourceSets: Set<String>, val androidSourceSetInfo: KotlinAndroidSourceSetInfo? ) { fun buildKotlinSourceSetImpl( doBuildDependencies: Boolean, allSourceSetsProtosByNames: Map<String, KotlinSourceSetProto>, ) = KotlinSourceSetImpl( name = name, languageSettings = languageSettings, sourceDirs = sourceDirs, resourceDirs = resourceDirs, regularDependencies = if (doBuildDependencies) regularDependencies() else emptyArray(), intransitiveDependencies = if (doBuildDependencies) intransitiveDependencies() else emptyArray(), // .toMutableSet, because Android IDE plugin depends on this // KotlinAndroidMPPGradleProjectResolver.kt: private fun KotlinMPPGradleModel.mergeSourceSets declaredDependsOnSourceSets = dependsOnSourceSets.toMutableSet(), allDependsOnSourceSets = allDependsOnSourceSets(allSourceSetsProtosByNames).toMutableSet(), additionalVisibleSourceSets = additionalVisibleSourceSets.toMutableSet(), androidSourceSetInfo = androidSourceSetInfo ) } fun KotlinSourceSetProto.allDependsOnSourceSets(sourceSetsByName: Map<String, KotlinSourceSetProto>): Set<String> { return mutableSetOf<String>().apply { addAll(dependsOnSourceSets) dependsOnSourceSets.map(sourceSetsByName::getValue).forEach { dependsOnSourceSet -> addAll(dependsOnSourceSet.allDependsOnSourceSets(sourceSetsByName)) } } } class KotlinAndroidSourceSetInfoImpl( override val kotlinSourceSetName: String, override val androidSourceSetName: String, override val androidVariantNames: Set<String> ): KotlinAndroidSourceSetInfo { constructor(info: KotlinAndroidSourceSetInfo) : this( kotlinSourceSetName = info.kotlinSourceSetName, androidSourceSetName = info.androidSourceSetName, androidVariantNames = info.androidVariantNames.toSet() ) } class KotlinSourceSetImpl( override val name: String, override val languageSettings: KotlinLanguageSettings, override val sourceDirs: Set<File>, override val resourceDirs: Set<File>, override val regularDependencies: Array<KotlinDependencyId>, override val intransitiveDependencies: Array<KotlinDependencyId>, override val declaredDependsOnSourceSets: Set<String>, @Suppress("OverridingDeprecatedMember") override val allDependsOnSourceSets: Set<String>, override val additionalVisibleSourceSets: Set<String>, override val androidSourceSetInfo: KotlinAndroidSourceSetInfo?, actualPlatforms: KotlinPlatformContainerImpl = KotlinPlatformContainerImpl(), isTestComponent: Boolean = false, ) : KotlinSourceSet { override val dependencies: Array<KotlinDependencyId> = regularDependencies + intransitiveDependencies @Suppress("DEPRECATION") constructor(kotlinSourceSet: KotlinSourceSet) : this( name = kotlinSourceSet.name, languageSettings = KotlinLanguageSettingsImpl(kotlinSourceSet.languageSettings), sourceDirs = HashSet(kotlinSourceSet.sourceDirs), resourceDirs = HashSet(kotlinSourceSet.resourceDirs), regularDependencies = kotlinSourceSet.regularDependencies.clone(), intransitiveDependencies = kotlinSourceSet.intransitiveDependencies.clone(), declaredDependsOnSourceSets = HashSet(kotlinSourceSet.declaredDependsOnSourceSets), allDependsOnSourceSets = HashSet(kotlinSourceSet.allDependsOnSourceSets), additionalVisibleSourceSets = HashSet(kotlinSourceSet.additionalVisibleSourceSets), androidSourceSetInfo = kotlinSourceSet.androidSourceSetInfo?.let(::KotlinAndroidSourceSetInfoImpl), actualPlatforms = KotlinPlatformContainerImpl(kotlinSourceSet.actualPlatforms) ) { this.isTestComponent = kotlinSourceSet.isTestComponent } override var actualPlatforms: KotlinPlatformContainer = actualPlatforms internal set override var isTestComponent: Boolean = isTestComponent internal set override fun toString() = name init { @Suppress("DEPRECATION") require(allDependsOnSourceSets.containsAll(declaredDependsOnSourceSets)) { "Inconsistent source set dependencies: 'allDependsOnSourceSets' is expected to contain all 'declaredDependsOnSourceSets'" } } } data class KotlinLanguageSettingsImpl( override val languageVersion: String?, override val apiVersion: String?, override val isProgressiveMode: Boolean, override val enabledLanguageFeatures: Set<String>, override val optInAnnotationsInUse: Set<String>, override val compilerPluginArguments: Array<String>, override val compilerPluginClasspath: Set<File>, override val freeCompilerArgs: Array<String> ) : KotlinLanguageSettings { constructor(settings: KotlinLanguageSettings) : this( languageVersion = settings.languageVersion, apiVersion = settings.apiVersion, isProgressiveMode = settings.isProgressiveMode, enabledLanguageFeatures = settings.enabledLanguageFeatures, optInAnnotationsInUse = settings.optInAnnotationsInUse, compilerPluginArguments = settings.compilerPluginArguments, compilerPluginClasspath = settings.compilerPluginClasspath, freeCompilerArgs = settings.freeCompilerArgs ) } data class KotlinCompilationOutputImpl( override val classesDirs: Set<File>, override val effectiveClassesDir: File?, override val resourcesDir: File? ) : KotlinCompilationOutput { constructor(output: KotlinCompilationOutput) : this( HashSet(output.classesDirs), output.effectiveClassesDir, output.resourcesDir ) } @Deprecated("Use org.jetbrains.kotlin.idea.projectModel.CachedArgsInfo instead", level = DeprecationLevel.ERROR) @Suppress("DEPRECATION_ERROR") data class KotlinCompilationArgumentsImpl( override val defaultArguments: Array<String>, override val currentArguments: Array<String> ) : KotlinCompilationArguments { constructor(arguments: KotlinCompilationArguments) : this( arguments.defaultArguments, arguments.currentArguments ) } data class KotlinNativeCompilationExtensionsImpl( override val konanTarget: String ) : KotlinNativeCompilationExtensions { constructor(extensions: KotlinNativeCompilationExtensions) : this(extensions.konanTarget) } data class KotlinCompilationCoordinatesImpl( override val targetName: String, override val compilationName: String ) : KotlinCompilationCoordinates { constructor(coordinates: KotlinCompilationCoordinates) : this( targetName = coordinates.targetName, compilationName = coordinates.compilationName ) } @Suppress("DEPRECATION_ERROR") data class KotlinCompilationImpl( override val name: String, override val allSourceSets: Collection<KotlinSourceSet>, override val declaredSourceSets: Collection<KotlinSourceSet>, override val dependencies: Array<KotlinDependencyId>, override val output: KotlinCompilationOutput, @Suppress("OverridingDeprecatedMember", "DEPRECATION_ERROR") override val arguments: KotlinCompilationArguments, @Suppress("OverridingDeprecatedMember", "DEPRECATION_ERROR") override val dependencyClasspath: Array<String>, override val cachedArgsInfo: CachedArgsInfo<*>, override val kotlinTaskProperties: KotlinTaskProperties, override val nativeExtensions: KotlinNativeCompilationExtensions?, override val associateCompilations: Set<KotlinCompilationCoordinates> ) : KotlinCompilation { // create deep copy constructor(kotlinCompilation: KotlinCompilation, cloningCache: MutableMap<Any, Any>) : this( name = kotlinCompilation.name, declaredSourceSets = cloneSourceSetsWithCaching(kotlinCompilation.declaredSourceSets, cloningCache), allSourceSets = cloneSourceSetsWithCaching(kotlinCompilation.allSourceSets, cloningCache), dependencies = kotlinCompilation.dependencies, output = KotlinCompilationOutputImpl(kotlinCompilation.output), arguments = KotlinCompilationArgumentsImpl(kotlinCompilation.arguments), dependencyClasspath = kotlinCompilation.dependencyClasspath, cachedArgsInfo = createCachedArgsInfo(kotlinCompilation.cachedArgsInfo, cloningCache), kotlinTaskProperties = KotlinTaskPropertiesImpl(kotlinCompilation.kotlinTaskProperties), nativeExtensions = kotlinCompilation.nativeExtensions?.let(::KotlinNativeCompilationExtensionsImpl), associateCompilations = cloneCompilationCoordinatesWithCaching(kotlinCompilation.associateCompilations, cloningCache) ) { disambiguationClassifier = kotlinCompilation.disambiguationClassifier platform = kotlinCompilation.platform } override var disambiguationClassifier: String? = null internal set override lateinit var platform: KotlinPlatform internal set // TODO: Logic like this is duplicated *and different* override val isTestComponent: Boolean get() = name == KotlinCompilation.TEST_COMPILATION_NAME || platform == KotlinPlatform.ANDROID && name.contains("Test") override fun toString() = name companion object { private fun cloneSourceSetsWithCaching( sourceSets: Collection<KotlinSourceSet>, cloningCache: MutableMap<Any, Any> ): List<KotlinSourceSet> = sourceSets.map { initialSourceSet -> (cloningCache[initialSourceSet] as? KotlinSourceSet) ?: KotlinSourceSetImpl(initialSourceSet).also { cloningCache[initialSourceSet] = it } } private fun cloneCompilationCoordinatesWithCaching( coordinates: Set<KotlinCompilationCoordinates>, cloningCache: MutableMap<Any, Any> ): Set<KotlinCompilationCoordinates> = coordinates.map { initial -> cloningCache.getOrPut(initial) { KotlinCompilationCoordinatesImpl(initial) } as KotlinCompilationCoordinates }.toSet() } } data class KotlinTargetJarImpl( override val archiveFile: File? ) : KotlinTargetJar data class KotlinTargetImpl( override val name: String, override val presetName: String?, override val disambiguationClassifier: String?, override val platform: KotlinPlatform, override val compilations: Collection<KotlinCompilation>, override val testRunTasks: Collection<KotlinTestRunTask>, override val nativeMainRunTasks: Collection<KotlinNativeMainRunTask>, override val jar: KotlinTargetJar?, override val konanArtifacts: List<KonanArtifactModel> ) : KotlinTarget { override fun toString() = name constructor(target: KotlinTarget, cloningCache: MutableMap<Any, Any>) : this( target.name, target.presetName, target.disambiguationClassifier, KotlinPlatform.byId(target.platform.id) ?: KotlinPlatform.COMMON, target.compilations.map { initialCompilation -> (cloningCache[initialCompilation] as? KotlinCompilation) ?: KotlinCompilationImpl(initialCompilation, cloningCache).also { cloningCache[initialCompilation] = it } }.toList(), target.testRunTasks.map { initialTestTask -> (cloningCache[initialTestTask] as? KotlinTestRunTask) ?: KotlinTestRunTaskImpl( initialTestTask.taskName, initialTestTask.compilationName ).also { cloningCache[initialTestTask] = it } }, target.nativeMainRunTasks.map { initialTestTask -> (cloningCache[initialTestTask] as? KotlinNativeMainRunTask) ?: KotlinNativeMainRunTaskImpl( initialTestTask.taskName, initialTestTask.compilationName, initialTestTask.entryPoint, initialTestTask.debuggable ).also { cloningCache[initialTestTask] = it } }, KotlinTargetJarImpl(target.jar?.archiveFile), target.konanArtifacts.map { KonanArtifactModelImpl(it) }.toList() ) } data class KotlinTestRunTaskImpl( override val taskName: String, override val compilationName: String ) : KotlinTestRunTask data class KotlinNativeMainRunTaskImpl( override val taskName: String, override val compilationName: String, override val entryPoint: String, override val debuggable: Boolean ) : KotlinNativeMainRunTask data class ExtraFeaturesImpl( override val coroutinesState: String?, override val isHMPPEnabled: Boolean, ) : ExtraFeatures data class KotlinMPPGradleModelImpl( override val sourceSetsByName: Map<String, KotlinSourceSet>, override val targets: Collection<KotlinTarget>, override val extraFeatures: ExtraFeatures, override val kotlinNativeHome: String, override val dependencyMap: Map<KotlinDependencyId, KotlinDependency>, override val cacheAware: CompilerArgumentsCacheAware, override val kotlinImportingDiagnostics: KotlinImportingDiagnosticsContainer = mutableSetOf(), override val kotlinGradlePluginVersion: KotlinGradlePluginVersion? ) : KotlinMPPGradleModel { constructor(mppModel: KotlinMPPGradleModel, cloningCache: MutableMap<Any, Any>) : this( sourceSetsByName = mppModel.sourceSetsByName.mapValues { initialSourceSet -> (cloningCache[initialSourceSet] as? KotlinSourceSet) ?: KotlinSourceSetImpl(initialSourceSet.value) .also { cloningCache[initialSourceSet] = it } }, targets = mppModel.targets.map { initialTarget -> (cloningCache[initialTarget] as? KotlinTarget) ?: KotlinTargetImpl(initialTarget, cloningCache).also { cloningCache[initialTarget] = it } }.toList(), extraFeatures = ExtraFeaturesImpl( mppModel.extraFeatures.coroutinesState, mppModel.extraFeatures.isHMPPEnabled, ), kotlinNativeHome = mppModel.kotlinNativeHome, dependencyMap = mppModel.dependencyMap.map { it.key to it.value.deepCopy(cloningCache) }.toMap(), cacheAware = CompilerArgumentsCacheAwareImpl(mppModel.cacheAware), kotlinImportingDiagnostics = mppModel.kotlinImportingDiagnostics.mapTo(mutableSetOf()) { it.deepCopy(cloningCache) }, kotlinGradlePluginVersion = mppModel.kotlinGradlePluginVersion?.reparse() ) @Deprecated( "Use KotlinGradleModel#cacheAware instead", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("KotlinMPPGradleModel#cacheAware") ) @Suppress("OverridingDeprecatedMember") override val partialCacheAware: CompilerArgumentsCacheAware get() = cacheAware } class KotlinPlatformContainerImpl() : KotlinPlatformContainer { private val defaultCommonPlatform = setOf(KotlinPlatform.COMMON) private var myPlatforms: MutableSet<KotlinPlatform>? = null override val arePlatformsInitialized: Boolean get() = myPlatforms != null constructor(platform: KotlinPlatformContainer) : this() { myPlatforms = HashSet(platform.platforms) } override val platforms: Set<KotlinPlatform> get() = myPlatforms ?: defaultCommonPlatform override fun supports(simplePlatform: KotlinPlatform): Boolean = platforms.contains(simplePlatform) override fun pushPlatforms(platforms: Iterable<KotlinPlatform>) { myPlatforms = (myPlatforms ?: LinkedHashSet()).apply { addAll(platforms) if (contains(KotlinPlatform.COMMON)) { clear() addAll(defaultCommonPlatform) } } } } data class KonanArtifactModelImpl( override val targetName: String, override val executableName: String, override val type: String, override val targetPlatform: String, override val file: File, override val buildTaskPath: String, override val runConfiguration: KonanRunConfigurationModel, override val isTests: Boolean, override val freeCompilerArgs: Array<String>? = emptyArray(), // nullable for backwards compatibility override val exportDependencies: Array<KotlinDependencyId>? = emptyArray(), // nullable for backwards compatibility override val binaryOptions: Array<String>? = emptyArray(), // nullable for backwards compatibility ) : KonanArtifactModel { constructor(artifact: KonanArtifactModel) : this( artifact.targetName, artifact.executableName, artifact.type, artifact.targetPlatform, artifact.file, artifact.buildTaskPath, KonanRunConfigurationModelImpl(artifact.runConfiguration), artifact.isTests, checkNotNull(artifact.freeCompilerArgs) { "free compiler arguments are unexpectedly null" }, checkNotNull(artifact.exportDependencies) { "export dependencies are unexpectedly null" }, checkNotNull(artifact.binaryOptions) { "binary compiler options are unexpectedly null" }, ) } data class KonanRunConfigurationModelImpl( override val workingDirectory: String, override val programParameters: List<String>, override val environmentVariables: Map<String, String> ) : KonanRunConfigurationModel { constructor(configuration: KonanRunConfigurationModel) : this( configuration.workingDirectory, ArrayList(configuration.programParameters), HashMap(configuration.environmentVariables) ) constructor(runTask: Exec?) : this( runTask?.workingDir?.path ?: KonanRunConfigurationModel.NO_WORKING_DIRECTORY, runTask?.args as List<String>? ?: KonanRunConfigurationModel.NO_PROGRAM_PARAMETERS, (runTask?.environment as Map<String, Any>?) ?.mapValues { it.value.toString() } ?: KonanRunConfigurationModel.NO_ENVIRONMENT_VARIABLES ) }
plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinMPPGradleModelImpl.kt
1660767790
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.FileModificationService import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler import org.jetbrains.kotlin.idea.refactoring.rename.RenameKotlinImplicitLambdaParameter.Companion.convertImplicitItToExplicit import org.jetbrains.kotlin.idea.refactoring.rename.RenameKotlinImplicitLambdaParameter.Companion.isAutoCreatedItUsage import org.jetbrains.kotlin.psi.KtNameReferenceExpression class ReplaceItWithExplicitFunctionLiteralParamIntention : SelfTargetingOffsetIndependentIntention<KtNameReferenceExpression>( KtNameReferenceExpression::class.java, KotlinBundle.lazyMessage("replace.it.with.explicit.parameter") ) { override fun isApplicableTo(element: KtNameReferenceExpression) = isAutoCreatedItUsage(element) override fun startInWriteAction(): Boolean = false override fun applyTo(element: KtNameReferenceExpression, editor: Editor?) { if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return if (editor == null) throw IllegalArgumentException("This intention requires an editor") val paramToRename = convertImplicitItToExplicit(element, editor) ?: return editor.caretModel.moveToOffset(element.textOffset) KotlinVariableInplaceRenameHandler().doRename(paramToRename, editor, null) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceItWithExplicitFunctionLiteralParamIntention.kt
635361387
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.components.dialog import com.intellij.ui.dsl.builder.bindIntText import com.intellij.ui.dsl.builder.panel /** * @author Konstantin Bulenkov */ internal class UIFreezeAction : DumbAwareAction("UI Freeze") { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) { var seconds = 15 val ui = panel { row("Duration in seconds:") { intTextField(IntRange(1, 300)) .bindIntText({ seconds }, { seconds = it }) } } if (dialog("Set Freeze Duration", ui).showAndGet()) { Thread.sleep(seconds * 1_000L) } } }
platform/platform-impl/src/com/intellij/internal/UIFreezeAction.kt
2622430904
/* * This file is part of dtmlibs. * * Copyright (c) 2017 Jeremy Wood * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dtmlibs.logging /** * Marks a class as being an owner of logs belonging to various [Loggable] objects. * * See [Logging]. */ interface LogOwner : Loggable { override val logOwner get() = this::class.java }
logging/src/main/kotlin/dtmlibs/logging/LogOwner.kt
3090155381
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.execution import com.intellij.execution.target.HostPort import com.intellij.execution.target.TargetEnvironmentConfiguration import com.intellij.openapi.externalSystem.service.execution.TargetEnvironmentConfigurationProvider import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental interface GradleServerConfigurationProvider : TargetEnvironmentConfigurationProvider { fun getServerBindingAddress(targetEnvironmentConfiguration: TargetEnvironmentConfiguration): HostPort? = null fun getClientCommunicationAddress(targetEnvironmentConfiguration: TargetEnvironmentConfiguration, gradleServerHostPort: HostPort): HostPort? = null }
plugins/gradle/src/org/jetbrains/plugins/gradle/service/execution/GradleServerConfigurationProvider.kt
3776665508
fun xfoo(p: () -> Unit = {}){} fun test() { xfo<caret> } // ELEMENT: xfoo // TAIL_TEXT: " {...} (p: () -> Unit = ...) (<root>)"
plugins/kotlin/completion/tests/testData/handlers/basic/highOrderFunctions/OptionalParameters3.kt
4228989500
// INTENTION_CLASS: org.jetbrains.kotlin.android.intention.AddServiceToManifest // NOT_AVAILABLE package com.myapp import android.app.Service import android.content.Intent import android.os.IBinder abstract class <caret>MyService : Service() { override fun onBind(intent: Intent?): IBinder { TODO("not implemented") } }
plugins/kotlin/idea/tests/testData/android/intention/addServiceToManifest/abstract.kt
3356644694
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.application.impl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.util.ui.EDT import kotlinx.coroutines.MainCoroutineDispatcher import kotlinx.coroutines.Runnable import kotlinx.coroutines.job import kotlin.coroutines.CoroutineContext internal sealed class EdtCoroutineDispatcher : MainCoroutineDispatcher() { override val immediate: MainCoroutineDispatcher get() = Immediate override fun dispatch(context: CoroutineContext, block: Runnable) { val state = context[ModalityStateElement]?.modalityState ?: ModalityState.any() val runnable = if (state === ModalityState.any()) { block } else { DispatchedRunnable(context.job, block) } ApplicationManager.getApplication().invokeLater(runnable, state) } companion object : EdtCoroutineDispatcher() { override fun toString() = "EDT" } object Immediate : EdtCoroutineDispatcher() { override fun isDispatchNeeded(context: CoroutineContext): Boolean { if (!EDT.isCurrentThreadEdt()) { return true } // The current coroutine is executed with the correct modality state // (the execution would be postponed otherwise) // => there is no need to check modality state here. return false } override fun toString() = "EDT.immediate" } }
platform/core-impl/src/com/intellij/openapi/application/impl/EdtCoroutineDispatcher.kt
1246681274
// IntelliJ API Decompiler stub source generated from a class file // Implementation of methods is not available package test public interface Inherited : dependency.Base { public companion object { public final val INT_CONST: kotlin.Int /* compiled code */ } }
plugins/kotlin/idea/tests/testData/decompiler/decompiledText/Inherited.expected.kt
3550206428
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.tree import org.jetbrains.kotlin.utils.SmartList class JKComment(val text: String, val indent: String? = null) { val isSingleline get() = text.startsWith("//") } class JKTokenElementImpl(override val text: String) : JKTokenElement { override val trailingComments: MutableList<JKComment> = SmartList() override val leadingComments: MutableList<JKComment> = SmartList() override var hasTrailingLineBreak: Boolean = false override var hasLeadingLineBreak: Boolean = false } interface JKFormattingOwner { val trailingComments: MutableList<JKComment> val leadingComments: MutableList<JKComment> var hasTrailingLineBreak: Boolean var hasLeadingLineBreak: Boolean } fun <T : JKFormattingOwner> T.withFormattingFrom(other: JKFormattingOwner): T = also { trailingComments += other.trailingComments leadingComments += other.leadingComments hasTrailingLineBreak = other.hasTrailingLineBreak hasLeadingLineBreak = other.hasLeadingLineBreak } fun <T, S> T.withPsiAndFormattingFrom( other: S ): T where T : JKFormattingOwner, T : PsiOwner, S : JKFormattingOwner, S : PsiOwner = also { withFormattingFrom(other) this.psi = other.psi } inline fun <reified T : JKFormattingOwner> List<T>.withFormattingFrom(other: JKFormattingOwner): List<T> = also { if (isNotEmpty()) { it.first().trailingComments += other.trailingComments it.first().hasTrailingLineBreak = other.hasTrailingLineBreak it.last().leadingComments += other.leadingComments it.last().hasLeadingLineBreak = other.hasLeadingLineBreak } } fun JKFormattingOwner.clearFormatting() { trailingComments.clear() leadingComments.clear() hasTrailingLineBreak = false hasLeadingLineBreak = false } interface JKTokenElement : JKFormattingOwner { val text: String } fun JKFormattingOwner.containsNewLine(): Boolean = hasTrailingLineBreak || hasLeadingLineBreak
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/formatting.kt
3701113831
package <%= appPackage %>.data import <%= appPackage %>.data.local.PreferencesDataSource import <%= appPackage %>.data.local.db.UserDao import <%= appPackage %>.data.model.User import <%= appPackage %>.data.remote.AppApi import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Observable interface UserDataSource { fun getLastQuery(): Flowable<String> fun insertUser(user: User): Completable fun getUser(login: String): Observable<User> } class UserRepository(private val appApi: AppApi, val userDao: UserDao, private val preferencesDataSource: PreferencesDataSource): UserDataSource { override fun getUser(login: String): Observable<User> = appApi.getUser(login).doOnNext { preferencesDataSource.storeUser(it.login) } override fun insertUser(user: User): Completable = Completable.create { userDao.insertUser(user) } override fun getLastQuery(): Flowable<String> { return userDao.getLastQuery() .map { user -> user.login } } }
app/templates/app_arch_comp/src/main/kotlin/data/UserDataSource.kt
3484160253
typealias <caret>R1 = Runnable val r1 = R1 {} // (1) val r2 = object : R1 { // (2) override fun run() {} }
plugins/kotlin/idea/tests/testData/refactoring/inline/inlineTypeAlias/lambdaExpression.kt
3544548009
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.gradle import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.project.Project import com.intellij.testFramework.LightPlatformTestCase import org.jetbrains.kotlin.idea.gradle.configuration.ResolveModulesPerSourceSetInMppBuildIssue import org.jetbrains.plugins.gradle.service.project.open.setupGradleSettings import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import java.util.concurrent.CompletableFuture import java.util.concurrent.atomic.AtomicInteger class ResolveModulesPerSourceSetInMppBuildIssueTest : LightPlatformTestCase() { override fun tearDown() { GradleSettings.getInstance(project).apply { linkedProjectsSettings.forEach { projectSetting -> unlinkExternalProject(projectSetting.externalProjectPath) } } super.tearDown() } fun `test description contains QuickFix id`() { val buildIssue = ResolveModulesPerSourceSetInMppBuildIssue() assertTrue( "Expected link to the QuickFix in the build issues description", buildIssue.quickFixes.single().id in buildIssue.description ) } fun `test quickFix updates GradleProjectSettings`() { val gradleSettings = GradleSettings.getInstance(project) gradleSettings.setupGradleSettings() gradleSettings.linkProject(GradleProjectSettings().apply { externalProjectPath = project.basePath isResolveModulePerSourceSet = false }) assertFalse( "Expected isResolveModulePerSourceSet is false before running QuickFix", gradleSettings.linkedProjectsSettings.single().isResolveModulePerSourceSet ) val testProjectRefresher = TestProjectRefresher() ResolveModulesPerSourceSetInMppBuildIssue(testProjectRefresher) .quickFixes.single() .runQuickFix(project, DataContext {}) .get() assertTrue( "Expected isResolveModulePerSourceSet is true after running QuickFix", gradleSettings.linkedProjectsSettings.single().isResolveModulePerSourceSet ) assertEquals( "Expect single invocation of project refresher", 1, testProjectRefresher.invocationCount.get() ) } } private class TestProjectRefresher( ) : ResolveModulesPerSourceSetInMppBuildIssue.ProjectRefresher { val invocationCount = AtomicInteger(0) override fun invoke(project: Project): CompletableFuture<*> { invocationCount.getAndIncrement() return CompletableFuture.completedFuture(null) } }
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/gradle/ResolveModulesPerSourceSetInMppBuildIssueTest.kt
974071617
// WITH_STDLIB // IS_APPLICABLE: false // IS_APPLICABLE_2: false fun foo(list: List<String>): Int? { <caret>for ((index, s) in list.withIndex()) { if (s.isBlank()) continue val x = s.length * index if (x > 1000) return x } return null }
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/map/mapUsesOldIndexAfterFilter.kt
4028488426
package net.coding.program.push.xiaomi import android.annotation.SuppressLint import android.content.Context import android.net.Uri import android.text.TextUtils import android.util.Log import com.xiaomi.mipush.sdk.* import org.greenrobot.eventbus.EventBus import java.net.URLDecoder import java.text.SimpleDateFormat import java.util.* /** * 1、PushMessageReceiver 是个抽象类,该类继承了 BroadcastReceiver。<br></br> * 2、需要将自定义的 DemoMessageReceiver 注册在 AndroidManifest.xml 文件中: * <pre> * `<receiver * android:name="com.xiaomi.mipushdemo.DemoMessageReceiver" * android:exported="true"> * <intent-filter> * <action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" /> * </intent-filter> * <intent-filter> * <action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" /> * </intent-filter> * <intent-filter> * <action android:name="com.xiaomi.mipush.ERROR" /> * </intent-filter> * </receiver> `</pre> * * 3、DemoMessageReceiver 的 onReceivePassThroughMessage 方法用来接收服务器向客户端发送的透传消息。<br></br> * 4、DemoMessageReceiver 的 onNotificationMessageClicked 方法用来接收服务器向客户端发送的通知消息, * 这个回调方法会在用户手动点击通知后触发。<br></br> * 5、DemoMessageReceiver 的 onNotificationMessageArrived 方法用来接收服务器向客户端发送的通知消息, * 这个回调方法是在通知消息到达客户端时触发。另外应用在前台时不弹出通知的通知消息到达客户端也会触发这个回调函数。<br></br> * 6、DemoMessageReceiver 的 onCommandResult 方法用来接收客户端向服务器发送命令后的响应结果。<br></br> * 7、DemoMessageReceiver 的 onReceiveRegisterResult 方法用来接收客户端向服务器发送注册命令后的响应结果。<br></br> * 8、以上这些方法运行在非 UI 线程中。 * * @author mayixiang */ class XiaomiPushReceiver : PushMessageReceiver() { private var mRegId: String? = null private val mTopic: String? = null private val mAlias: String? = null private val mAccount: String? = null private val mStartTime: String? = null private val mEndTime: String? = null private val simpleDate: String @SuppressLint("SimpleDateFormat") get() = SimpleDateFormat("MM-dd hh:mm:ss").format(Date()) override fun onReceivePassThroughMessage(context: Context?, message: MiPushMessage?) { Log.v(PushAction.TAG, "onReceivePassThroughMessage is called. " + message!!.toString()) // String log = context.getString(R.string.recv_passthrough_message, message.getContent()); // MainActivity.logList.add(0, getSimpleDate() + " " + log); // // if (!TextUtils.isEmpty(message.getTopic())) { // mTopic = message.getTopic(); // } else if (!TextUtils.isEmpty(message.getAlias())) { // mAlias = message.getAlias(); // } // // Message msg = Message.obtain(); // msg.obj = log; // DemoApplication.getHandler().sendMessage(msg); } override fun onNotificationMessageClicked(context: Context?, message: MiPushMessage?) { Log.v(PushAction.TAG, "onNotificationMessageClicked is called. " + message!!.toString()) val s = message.content if (TextUtils.isEmpty(s)) { return } val extra = HashMap<String, String>() try { val uri = Uri.parse("https://coding.net?" + s) val keyUrl = "param_url" val paramUrl = uri.getQueryParameter(keyUrl) if (!TextUtils.isEmpty(paramUrl)) { extra[keyUrl] = URLDecoder.decode(paramUrl) } val idKey = "notification_id" val paramId = uri.getQueryParameter(idKey) if (!TextUtils.isEmpty(paramId)) { extra[idKey] = paramId } } catch (e: Exception) { Log.e(PushAction.TAG, e.toString()) } if (!extra.isEmpty()) { XiaomiPush.clickPushAction?.click(context!!, extra) } } override fun onNotificationMessageArrived(context: Context?, message: MiPushMessage?) { Log.v(PushAction.TAG, "onNotificationMessageArrived is called. " + message!!.toString()) // String log = context.getString(R.string.arrive_notification_message, message.getContent()); // MainActivity.logList.add(0, getSimpleDate() + " " + log); // // if (!TextUtils.isEmpty(message.getTopic())) { // mTopic = message.getTopic(); // } else if (!TextUtils.isEmpty(message.getAlias())) { // mAlias = message.getAlias(); // } // // Message msg = Message.obtain(); // msg.obj = log; // DemoApplication.getHandler().sendMessage(msg); } override fun onCommandResult(context: Context?, message: MiPushCommandMessage?) { Log.v(PushAction.TAG, "onCommandResult is called. " + message!!.toString()) // String command = message.getCommand(); // List<String> arguments = message.getCommandArguments(); // String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null); // String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null); // String log; // if (MiPushClient.COMMAND_REGISTER.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mRegId = cmdArg1; // log = context.getString(R.string.register_success); // } else { // log = context.getString(R.string.register_fail); // } // } else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mAlias = cmdArg1; // log = context.getString(R.string.set_alias_success, mAlias); // } else { // log = context.getString(R.string.set_alias_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mAlias = cmdArg1; // log = context.getString(R.string.unset_alias_success, mAlias); // } else { // log = context.getString(R.string.unset_alias_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_SET_ACCOUNT.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mAccount = cmdArg1; // log = context.getString(R.string.set_account_success, mAccount); // } else { // log = context.getString(R.string.set_account_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_UNSET_ACCOUNT.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mAccount = cmdArg1; // log = context.getString(R.string.unset_account_success, mAccount); // } else { // log = context.getString(R.string.unset_account_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mTopic = cmdArg1; // log = context.getString(R.string.subscribe_topic_success, mTopic); // } else { // log = context.getString(R.string.subscribe_topic_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mTopic = cmdArg1; // log = context.getString(R.string.unsubscribe_topic_success, mTopic); // } else { // log = context.getString(R.string.unsubscribe_topic_fail, message.getReason()); // } // } else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) { // if (message.getResultCode() == ErrorCode.SUCCESS) { // mStartTime = cmdArg1; // mEndTime = cmdArg2; // log = context.getString(R.string.set_accept_time_success, mStartTime, mEndTime); // } else { // log = context.getString(R.string.set_accept_time_fail, message.getReason()); // } // } else { // log = message.getReason(); // } // MainActivity.logList.add(0, getSimpleDate() + " " + log); // // Message msg = Message.obtain(); // msg.obj = log; // DemoApplication.getHandler().sendMessage(msg); } override fun onReceiveRegisterResult(context: Context?, message: MiPushCommandMessage?) { Log.v(PushAction.TAG, "onReceiveRegisterResult is called. " + message!!.toString()) if (MiPushClient.COMMAND_REGISTER == message.command && message.resultCode == ErrorCode.SUCCESS.toLong()) { message.commandArguments?.let { if (it.size > 0) mRegId = it[0] else mRegId = null } EventBus.getDefault().postSticky(EventPushToken("xiaomi", MiPushClient.getRegId(context))) } } }
push-xiaomi/src/main/java/net/coding/program/push/xiaomi/XiaomiPushReceiver.kt
914642626
package com.sample.lib fun main(args: Array<String>) { println("Hello, world") JavaClass() } fun out(num1: Int) : Float { return num1 / .66f }
test/com/facebook/buck/android/testdata/android_project/kotlin/com/sample/lib/Example.kt
3403323250
package pl.pw.mgr.lightsensor.regression import pl.pw.mgr.lightsensor.data.model.Point object Measurements { val NOTE_1_NAME = "Note 1" val NOTE_2_NAME = "Note 2" val GALAXY_NAME = "Galaxy S3" val HTC_NAME = "HTC One S" val NOTE_1: List<Point> = listOf( Point(1.00f, 10f), Point(2.00f, 20f), Point(5.00f, 30f), Point(5.89f, 40f), Point(6.14f, 50f), Point(7.00f, 60f), Point(8.00f, 70f), Point(8.00f, 80f), Point(8.89f, 90f), Point(9.17f, 100f), Point(9.89f, 110f), Point(10.31f, 120f), Point(10.75f, 130f), Point(12.60f, 140f), Point(12.97f, 150f), Point(13.96f, 160f), Point(14.52f, 170f), Point(14.57f, 180f), Point(15.05f, 190f), Point(15.59f, 200f), Point(18.06f, 250f), Point(20.16f, 300f), Point(22.43f, 350f), Point(24.07f, 400f), Point(25.67f, 450f), Point(26.83f, 500f), Point(29.38f, 550f), Point(31.34f, 600f), Point(32.23f, 650f), Point(34.04f, 700f), Point(34.88f, 750f), Point(37.13f, 800f), Point(38.10f, 850f), Point(38.69f, 900f), Point(40.09f, 950f), Point(40.87f, 1000f) ) val NOTE_2: List<Point> = listOf( Point(14.00f, 10f), Point(28.83f, 20f), Point(44.06f, 30f), Point(56.08f, 40f), Point(70.09f, 50f), Point(84.15f, 60f), Point(99.07f, 70f), Point(112.55f, 80f), Point(127.20f, 90f), Point(141.26f, 100f), Point(156.00f, 110f), Point(170.78f, 120f), Point(183.48f, 130f), Point(197.59f, 140f), Point(212.13f, 150f), Point(225.74f, 160f), Point(241.20f, 170f), Point(259.50f, 180f), Point(275.66f, 190f), Point(288.10f, 200f), Point(363.43f, 250f), Point(433.55f, 300f), Point(514.18f, 350f), Point(587.27f, 400f), Point(664.96f, 450f), Point(735.36f, 500f), Point(813.92f, 550f), Point(881.51f, 600f), Point(958.91f, 650f), Point(1036.43f, 700f), Point(1110.03f, 750f), Point(1194.42f, 800f), Point(1265.88f, 850f), Point(1342.03f, 900f), Point(1422.43f, 950f), Point(1571.28f, 1000f) ) val GALAXY: List<Point> = listOf( Point(14.77f, 10f), Point(29.00f, 20f), Point(42.85f, 30f), Point(56.24f, 40f), Point(69.72f, 50f), Point(84.17f, 60f), Point(97.85f, 70f), Point(112.04f, 80f), Point(126.31f, 90f), Point(138.92f, 100f), Point(153.35f, 110f), Point(166.12f, 120f), Point(181.00f, 130f), Point(193.87f, 140f), Point(208.62f, 150f), Point(221.11f, 160f), Point(235.22f, 170f), Point(250.09f, 180f), Point(264.12f, 190f), Point(278.38f, 200f), Point(349.76f, 250f), Point(419.54f, 300f), Point(487.17f, 350f), Point(560.23f, 400f), Point(632.24f, 450f), Point(701.05f, 500f), Point(772.42f, 550f), Point(826.52f, 600f), Point(894.02f, 650f), Point(965.97f, 700f), Point(1035.21f, 750f), Point(1106.63f, 800f), Point(1181.49f, 850f), Point(1250.52f, 900f), Point(1324.03f, 950f), Point(1387.16f, 1000f) ) val HTC: List<Point> = listOf( Point(320.00f, 10f), Point(320.00f, 20f), Point(640.00f, 30f), Point(640.00f, 40f), Point(1280.00f, 50f), Point(1280.00f, 60f), Point(1280.00f, 70f), Point(1280.00f, 80f), Point(2600.00f, 90f), Point(2600.00f, 100f), Point(2600.00f, 110f), Point(2600.00f, 120f), Point(2600.00f, 130f), Point(10240.00f, 140f), Point(10240.00f, 150f), Point(10240.00f, 160f), Point(10240.00f, 170f), Point(10240.00f, 180f), Point(10240.00f, 190f), Point(10240.00f, 200f), Point(10240.00f, 250f), Point(10240.00f, 300f), Point(10240.00f, 350f), Point(10240.00f, 400f), Point(10240.00f, 450f), Point(10240.00f, 500f), Point(10240.00f, 550f), Point(10240.00f, 600f), Point(10240.00f, 650f), Point(10240.00f, 700f), Point(10240.00f, 750f), Point(10240.00f, 800f), Point(10240.00f, 850f), Point(10240.00f, 900f), Point(10240.00f, 950f), Point(10240.00f, 1000f) ) }
app/src/main/java/pl/pw/mgr/lightsensor/regression/Measurements.kt
1327415885
package fr.free.nrw.commons.review import com.nhaarman.mockitokotlin2.whenever import fr.free.nrw.commons.Media import fr.free.nrw.commons.media.MediaClient import io.reactivex.Observable import io.reactivex.Single import junit.framework.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.MockitoAnnotations import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.dataclient.mwapi.MwQueryResponse import org.wikipedia.dataclient.mwapi.MwQueryResult import org.wikipedia.dataclient.mwapi.RecentChange /** * Test class for ReviewHelper */ class ReviewHelperTest { @Mock internal var reviewInterface: ReviewInterface? = null @Mock internal var mediaClient: MediaClient? = null @InjectMocks var reviewHelper: ReviewHelper? = null /** * Init mocks */ @Before @Throws(Exception::class) fun setUp() { MockitoAnnotations.initMocks(this) val mwQueryPage = mock(MwQueryPage::class.java) val mockRevision = mock(MwQueryPage.Revision::class.java) `when`(mockRevision.user).thenReturn("TestUser") `when`(mwQueryPage.revisions()).thenReturn(listOf(mockRevision)) val recentChange = getMockRecentChange("log", "File:Test1.jpeg", 0) val recentChange1 = getMockRecentChange("log", "File:Test2.png", 0) val recentChange2 = getMockRecentChange("log", "File:Test3.jpg", 0) val mwQueryResult = mock(MwQueryResult::class.java) `when`(mwQueryResult.recentChanges).thenReturn(listOf(recentChange, recentChange1, recentChange2)) `when`(mwQueryResult.firstPage()).thenReturn(mwQueryPage) `when`(mwQueryResult.pages()).thenReturn(listOf(mwQueryPage)) val mockResponse = mock(MwQueryResponse::class.java) `when`(mockResponse.query()).thenReturn(mwQueryResult) `when`(reviewInterface?.getRecentChanges(ArgumentMatchers.anyString())) .thenReturn(Observable.just(mockResponse)) `when`(reviewInterface?.getFirstRevisionOfFile(ArgumentMatchers.anyString())) .thenReturn(Observable.just(mockResponse)) val media = mock(Media::class.java) whenever(media.filename).thenReturn("Test file.jpg") `when`(mediaClient?.getMedia(ArgumentMatchers.anyString())) .thenReturn(Single.just(media)) } /** * Test for getting random media */ @Test fun getRandomMedia() { `when`(mediaClient?.checkPageExistsUsingTitle(ArgumentMatchers.anyString())) .thenReturn(Single.just(false)) `when`(mediaClient?.checkPageExistsUsingTitle(ArgumentMatchers.anyString())) .thenReturn(Single.just(false)) reviewHelper?.randomMedia verify(reviewInterface, times(1))!!.getRecentChanges(ArgumentMatchers.anyString()) } /** * Test scenario when all media is already nominated for deletion */ @Test(expected = RuntimeException::class) fun getRandomMediaWithWithAllMediaNominatedForDeletion() { `when`(mediaClient?.checkPageExistsUsingTitle(ArgumentMatchers.anyString())) .thenReturn(Single.just(true)) val media = reviewHelper?.randomMedia?.blockingGet() assertNull(media) verify(reviewInterface, times(1))!!.getRecentChanges(ArgumentMatchers.anyString()) } /** * Test scenario when first media is already nominated for deletion */ @Test fun getRandomMediaWithWithOneMediaNominatedForDeletion() { `when`(mediaClient?.checkPageExistsUsingTitle("Commons:Deletion_requests/File:Test1.jpeg")) .thenReturn(Single.just(true)) `when`(mediaClient?.checkPageExistsUsingTitle("Commons:Deletion_requests/File:Test2.png")) .thenReturn(Single.just(false)) `when`(mediaClient?.checkPageExistsUsingTitle("Commons:Deletion_requests/File:Test3.jpg")) .thenReturn(Single.just(true)) reviewHelper?.randomMedia verify(reviewInterface, times(1))!!.getRecentChanges(ArgumentMatchers.anyString()) } private fun getMockRecentChange(type: String, title: String, oldRevisionId: Long): RecentChange { val recentChange = mock(RecentChange::class.java) `when`(recentChange!!.type).thenReturn(type) `when`(recentChange.title).thenReturn(title) `when`(recentChange.oldRevisionId).thenReturn(oldRevisionId) return recentChange } /** * Test for getting first revision of file */ @Test fun getFirstRevisionOfFile() { val firstRevisionOfFile = reviewHelper?.getFirstRevisionOfFile("Test.jpg")?.blockingFirst() assertTrue(firstRevisionOfFile is MwQueryPage.Revision) } }
app/src/test/kotlin/fr/free/nrw/commons/review/ReviewHelperTest.kt
497067073
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.stardroid.gallery import android.content.res.Resources import com.google.android.stardroid.gallery.GalleryImage import com.google.android.stardroid.gallery.GalleryFactory import com.google.android.stardroid.gallery.HardcodedGallery import com.google.android.stardroid.R import java.util.* /** * A collection of gallery images. * * @author John Taylor */ class HardcodedGallery internal constructor(private val resources: Resources) : Gallery { override val galleryImages: List<GalleryImage> /** * Adds an image to the gallery, but using an internationalized search term. * Note, that for this to work the internationalized name _must_ be in the * search index. */ private fun add( images: ArrayList<GalleryImage>, imageId: Int, nameId: Int, searchTermId: Int ) { images.add(GalleryImage(imageId, getString(nameId), getString(searchTermId))) } private fun createImages(): ArrayList<GalleryImage> { val galleryImages = ArrayList<GalleryImage>() // Note the internationalized names in places. Be sure that if the // search term is internationalized in the search index then it is here too. add(galleryImages, R.drawable.messenger_11_07_39, R.string.mercury, R.string.mercury) add(galleryImages, R.drawable.hubble_venus_clouds_tops, R.string.venus, R.string.venus) add(galleryImages, R.drawable.hubble_mars, R.string.mars, R.string.mars) add(galleryImages, R.drawable.hubble_jupiter, R.string.jupiter, R.string.jupiter) add(galleryImages, R.drawable.hubble_saturn, R.string.saturn, R.string.saturn) add(galleryImages, R.drawable.hubble_uranus, R.string.uranus, R.string.uranus) add(galleryImages, R.drawable.hubble_neptune, R.string.neptune, R.string.neptune) add(galleryImages, R.drawable.nh_pluto_in_false_color, R.string.pluto, R.string.pluto) add(galleryImages, R.drawable.hubble_m1, R.string.crab_nebula, R.string.crab_nebula) add(galleryImages, R.drawable.hubble_m13, R.string.hercules_gc, R.string.hercules_gc) add(galleryImages, R.drawable.hubble_m16, R.string.eagle_nebula, R.string.eagle_nebula) add(galleryImages, R.drawable.kennett_m31, R.string.andromeda_galaxy, R.string.andromeda_galaxy) add(galleryImages, R.drawable.hubble_m45, R.string.pleiades, R.string.pleiades) add(galleryImages, R.drawable.hubble_m51a, R.string.whirlpool_galaxy, R.string.whirlpool_galaxy) add(galleryImages, R.drawable.hubble_m57, R.string.ring_nebula, R.string.ring_nebula) add(galleryImages, R.drawable.hubble_m101, R.string.pinwheel_galaxy, R.string.pinwheel_galaxy) add(galleryImages, R.drawable.hubble_m104, R.string.sombrero_galaxy, R.string.sombrero_galaxy) add( galleryImages, R.drawable.hubble_catseyenebula, R.string.cats_eye_nebula, R.string.cats_eye_nebula ) add( galleryImages, R.drawable.hubble_omegacentauri, R.string.omega_centauri, R.string.omega_centauri ) add(galleryImages, R.drawable.hubble_orion, R.string.orion_nebula, R.string.orion_nebula) add( galleryImages, R.drawable.hubble_ultra_deep_field, R.string.hubble_deep_field, R.string.hubble_deep_field ) add(galleryImages, R.drawable.hubble_v838, R.string.v838_mon, R.string.v838_mon) return galleryImages } private fun getString(id: Int): String { return resources.getString(id) } init { galleryImages = Collections.unmodifiableList(createImages()) } }
app/src/main/java/com/google/android/stardroid/gallery/HardcodedGallery.kt
2549811784
package io.kotest.core.spec.style import io.kotest.core.factory.TestFactory import io.kotest.core.factory.TestFactoryConfiguration import io.kotest.core.factory.build import io.kotest.core.spec.DslDrivenSpec import io.kotest.core.spec.resolvedDefaultConfig import io.kotest.core.spec.style.scopes.FunSpecRootContext import io.kotest.core.spec.style.scopes.RootTestRegistration import io.kotest.core.test.TestCaseConfig /** * Creates a [TestFactory] from the given block. * * The receiver of the block is a [FunSpecTestFactoryConfiguration] which allows tests * to be defined using the 'fun-spec' style. */ fun funSpec(block: FunSpecTestFactoryConfiguration.() -> Unit): TestFactory { val config = FunSpecTestFactoryConfiguration() config.block() return config.build() } class FunSpecTestFactoryConfiguration : TestFactoryConfiguration(), FunSpecRootContext { override fun registration(): RootTestRegistration = RootTestRegistration.from(this) override fun defaultConfig(): TestCaseConfig = resolvedDefaultConfig() } abstract class FunSpec(body: FunSpec.() -> Unit = {}) : DslDrivenSpec(), FunSpecRootContext { init { body() } override fun defaultConfig(): TestCaseConfig = resolvedDefaultConfig() override fun registration(): RootTestRegistration = RootTestRegistration.from(this) }
kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/spec/style/funSpec.kt
1057901174
package cz.filipproch.reactor.util /** * @author Filip Prochazka (@filipproch) */ data class MethodCalled(val methodName: String, val timestamp: Long)
library/src/androidTest/java/cz/filipproch/reactor/util/MethodCalled.kt
3967413771
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.stardroid.util object FixedPoint { const val ONE = 0x00010000 /// Converts a float to a 16.16 fixed point number @JvmStatic fun floatToFixedPoint(f: Float): Int { return (65536f * f).toInt() } }
app/src/main/java/com/google/android/stardroid/util/FixedPoint.kt
1725463608
import com.github.h0tk3y.betterParse.combinators.and import com.github.h0tk3y.betterParse.combinators.use import com.github.h0tk3y.betterParse.grammar.Grammar import com.github.h0tk3y.betterParse.lexer.regexToken import com.github.h0tk3y.betterParse.parser.Parser import com.github.h0tk3y.betterParse.parser.parseToEnd import com.github.h0tk3y.betterParse.utils.components import kotlin.native.concurrent.TransferMode import kotlin.test.Test import kotlin.test.assertEquals import kotlin.native.concurrent.Worker class ConcurrentExecution { object TestGrammar : Grammar<Nothing>() { override val rootParser: Parser<Nothing> get() = throw NoSuchElementException() val a by regexToken("a") val b by regexToken("b") val parser = a and b and a use { components.map { it.type } } } @Test fun foo() { val worker = Worker.start() worker.execute(TransferMode.UNSAFE, { "aba" }) { string -> val tokens = TestGrammar.tokenizer.tokenize(string) TestGrammar.parser.parseToEnd(tokens) }.consume { result -> assertEquals(listOf(TestGrammar.a, TestGrammar.b, TestGrammar.a), result) } } }
src/linuxX64Test/kotlin/ConcurrentExecution.kt
662738256
package de.treichels.hott.vdfeditor.actions import org.junit.Before open class AbstractActionTest { protected val list = mutableListOf<String>() @Before fun setup() { list.clear() list.addAll(mutableListOf("a", "b", "c", "d")) } }
VDFEditor/src/test/kotlin/de/treichels/hott/vdfeditor/actions/AbstractActionTest.kt
2535165865
package com.github.kerubistan.kerub.utils.ipmi class IpmiSession { fun close(): Unit = TODO() }
src/main/kotlin/com/github/kerubistan/kerub/utils/ipmi/IpmiSession.kt
281647664
/** * BreadWallet * * Created by Ahsan Butt <[email protected]> on 9/17/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.platform.interfaces import com.breadwallet.BuildConfig import com.breadwallet.app.BreadApp import com.breadwallet.breadbox.hashString import com.breadwallet.breadbox.isErc20 import com.breadwallet.crypto.Transfer import com.breadwallet.crypto.WalletManagerMode import com.breadwallet.logger.logDebug import com.breadwallet.logger.logError import com.breadwallet.logger.logInfo import com.breadwallet.platform.entities.TxMetaData import com.breadwallet.platform.entities.TxMetaDataEmpty import com.breadwallet.platform.entities.TxMetaDataValue import com.breadwallet.platform.entities.WalletInfoData import com.breadwallet.platform.interfaces.AccountMetaDataProvider import com.breadwallet.protocols.messageexchange.entities.PairingMetaData import com.breadwallet.tools.crypto.CryptoHelper import com.breadwallet.tools.util.TokenUtil import com.breadwallet.tools.util.Utils import com.platform.entities.TokenListMetaData import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.onStart import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.Date import java.util.Locale @Suppress("TooManyFunctions") class MetaDataManager( private val storeProvider: KVStoreProvider ) : WalletProvider, AccountMetaDataProvider { companion object { private const val KEY_WALLET_INFO = "wallet-info" private const val KEY_TOKEN_LIST_META_DATA = "token-list-metadata" private const val KEY_MSG_INBOX = "encrypted-message-inbox-metadata" private const val KEY_ASSET_INDEX = "asset-index" private const val CURSOR = "cursor" private const val ENABLED_ASSET_IDS = "enabledAssetIds" private const val CLASS_VERSION = "classVersion" private const val CLASS_VERSION_ASSET_IDS = 2 private const val CLASS_VERSION_MSG_INBOX = 1 private const val TX_META_DATA_KEY_PREFIX = "txn2-" private const val TK_META_DATA_KEY_PREFIX = "tkxf-" private const val PAIRING_META_DATA_KEY_PREFIX = "pwd-" private val ORDERED_KEYS = listOf(KEY_WALLET_INFO, KEY_ASSET_INDEX, KEY_TOKEN_LIST_META_DATA) } override fun create(accountCreationDate: Date) { val walletInfoJson = WalletInfoData( creationDate = accountCreationDate.time, connectionModes = BreadApp.getDefaultWalletModes() ).toJSON() storeProvider.put(KEY_WALLET_INFO, walletInfoJson) putEnabledWallets(BreadApp.getDefaultEnabledWallets()) logInfo("MetaDataManager created successfully") } override suspend fun recoverAll(migrate: Boolean): Boolean { // Sync essential metadata first, migrate enabled wallets ASAP storeProvider.sync(KEY_WALLET_INFO) storeProvider.sync(KEY_ASSET_INDEX) if (migrate) { storeProvider.sync(KEY_TOKEN_LIST_META_DATA) migrateTokenList() } // Not redundant to prioritize the above in ordered keys // if above was successful, will be a no-op, and if failed, it's a retry val syncResult = storeProvider.syncAll(ORDERED_KEYS) if (storeProvider.get(KEY_ASSET_INDEX) == null) { // Something went wrong, put default wallets storeProvider.put( KEY_ASSET_INDEX, enabledWalletsToJSON(BreadApp.getDefaultEnabledWallets()) ) } return syncResult } override fun walletInfo(): Flow<WalletInfoData> = storeProvider.keyFlow(KEY_WALLET_INFO) .mapLatest { WalletInfoData.fromJsonObject(it) } .onStart { emit( getOrSync( KEY_WALLET_INFO ) { WalletInfoData().toJSON() } !!.run { WalletInfoData.fromJsonObject(this) } ) } .distinctUntilChanged() override fun getWalletInfoUnsafe(): WalletInfoData? = try { storeProvider.get(KEY_WALLET_INFO) ?.run { WalletInfoData.fromJsonObject(this) } } catch (ex: JSONException) { logError("$ex") null } override fun enabledWallets(): Flow<List<String>> = storeProvider.keyFlow(KEY_ASSET_INDEX) .mapLatest { jsonToEnabledWallets(it) } .onStart { getOrSync(KEY_ASSET_INDEX)?.run { emit(jsonToEnabledWallets(this)) } } .distinctUntilChanged() override fun enableWallet(currencyId: String) { val enabledWallets = getEnabledWalletsUnsafe()?.toMutableList() ?: mutableListOf() if (!enabledWallets.contains(currencyId)) { putEnabledWallets( enabledWallets.apply { add(currencyId) } ) } } override fun enableWallets(currencyIds: List<String>) { val enabledWallets = getEnabledWalletsUnsafe().orEmpty() putEnabledWallets(enabledWallets.union(currencyIds).toList()) } override fun disableWallet(currencyId: String) { getEnabledWalletsUnsafe() ?.toMutableList() ?.filter { !it.equals(currencyId, true) } ?.run(::putEnabledWallets) } override fun reorderWallets(currencyIds: List<String>) { putEnabledWallets(currencyIds) } override fun walletModes(): Flow<Map<String, WalletManagerMode>> = walletInfo() .mapLatest { it.connectionModes } .distinctUntilChanged() override suspend fun putWalletMode(currencyId: String, mode: WalletManagerMode) { var walletInfo = walletInfo().first() if (walletInfo.connectionModes[currencyId] == mode) return val connectionModes = walletInfo.connectionModes.toMutableMap().apply { put(currencyId, mode) } walletInfo = walletInfo.copy(connectionModes = connectionModes) storeProvider.put( KEY_WALLET_INFO, walletInfo.toJSON() ) } override fun getPairingMetadata(pubKey: ByteArray): PairingMetaData? = try { val key = pairingKey(pubKey) storeProvider.get(key)?.run(::PairingMetaData) } catch (ex: JSONException) { logError("Error getting pairing metadata", ex) null } override fun putPairingMetadata(pairingData: PairingMetaData): Boolean = when (pairingData.publicKeyHex) { null -> { logError("pairingData.getPublicKeyHex() is null!") false } else -> { val rawPubKey = CryptoHelper.hexDecode(pairingData.publicKeyHex) ?: pairingData.publicKeyHex.toByteArray(Charsets.UTF_8) storeProvider.put(pairingKey(rawPubKey), pairingData.toJSON()) } } override fun getLastCursor(): String? = try { storeProvider.get(KEY_MSG_INBOX)?.getString(CURSOR) } catch (ex: JSONException) { logError("Error getting last cursor", ex) null } override fun putLastCursor(lastCursor: String): Boolean = storeProvider.put( KEY_MSG_INBOX, JSONObject( mapOf( CLASS_VERSION to CLASS_VERSION_MSG_INBOX, CURSOR to lastCursor ) ) ) override fun txMetaData(onlyGifts: Boolean): Map<String, TxMetaData> { return storeProvider.getKeys() .filter { it.startsWith(TX_META_DATA_KEY_PREFIX) } .mapNotNull { key -> storeProvider.get(key)?.run { key to this } } .toMap() .run { if (onlyGifts) filterValues { TxMetaDataValue.hasGift(it) } else this } .mapValues { (_, v) -> TxMetaDataValue.fromJsonObject(v) } } override fun txMetaData(key: String, isErc20: Boolean): Flow<TxMetaData> { return storeProvider.keyFlow(key) .mapLatest { TxMetaDataValue.fromJsonObject(it) } .onStart { val metaData = storeProvider.get(key) if (metaData != null) emit(TxMetaDataValue.fromJsonObject(metaData)) else emit(TxMetaDataEmpty) } .distinctUntilChanged() } override fun txMetaData(transaction: Transfer): Flow<TxMetaData> { val key = getTxMetaDataKey(transaction) return txMetaData(key, isErc20 = transaction.wallet.currency.isErc20()) } override suspend fun putTxMetaData( transaction: Transfer, newTxMetaData: TxMetaDataValue ) { val key = getTxMetaDataKey(transaction) putTxMetaData(key, transaction.wallet.currency.isErc20(), newTxMetaData) } override suspend fun putTxMetaData(key: String, isErc20: Boolean, newTxMetaData: TxMetaDataValue) { var txMetaData = txMetaData(key, isErc20 = isErc20).first() var needsUpdate = false when (txMetaData) { is TxMetaDataEmpty -> { needsUpdate = !newTxMetaData.comment.isNullOrBlank() || newTxMetaData.exchangeRate != 0.0 || !newTxMetaData.gift?.keyData.isNullOrBlank() txMetaData = newTxMetaData } is TxMetaDataValue -> { val newGift = newTxMetaData.gift val oldGift = txMetaData.gift if (newGift != oldGift && newGift != null) { // Don't overwrite gift unless keyData is provided if (oldGift?.keyData == null && newGift.keyData != null) { txMetaData = txMetaData.copy( gift = newTxMetaData.gift ) needsUpdate = true } else if ( oldGift?.keyData != null && (oldGift.claimed != newGift.claimed || oldGift.reclaimed != newGift.reclaimed) ) { txMetaData = txMetaData.copy( gift = oldGift.copy( claimed = newGift.claimed, reclaimed = newGift.reclaimed ) ) needsUpdate = true } } if (newTxMetaData.comment != txMetaData.comment) { txMetaData = txMetaData.copy( comment = newTxMetaData.comment ) needsUpdate = true } if (txMetaData.exchangeRate == 0.0 && newTxMetaData.exchangeRate != 0.0) { txMetaData = txMetaData.copy( exchangeRate = newTxMetaData.exchangeRate ) needsUpdate = true } } } if (needsUpdate) { storeProvider.put(key, txMetaData.toJSON()) } } override fun getEnabledWalletsUnsafe(): List<String>? = try { storeProvider.get(KEY_ASSET_INDEX) ?.getJSONArray(ENABLED_ASSET_IDS) ?.run { List(length()) { getString(it) } } } catch (ex: JSONException) { logError("$ex") null } override fun resetDefaultWallets() { putEnabledWallets(BreadApp.getDefaultEnabledWallets()) } private fun putEnabledWallets(enabledWallets: List<String>) = enabledWalletsToJSON(enabledWallets) .also { storeProvider.put(KEY_ASSET_INDEX, it) } private fun migrateTokenList() { if (storeProvider.get(KEY_ASSET_INDEX) != null) { logDebug("Metadata for $KEY_ASSET_INDEX found, no migration needed.") return } logDebug("Migrating $KEY_TOKEN_LIST_META_DATA to $KEY_ASSET_INDEX.") try { val tokenListMetaData = storeProvider.get(KEY_TOKEN_LIST_META_DATA) ?.run(::TokenListMetaData) if (tokenListMetaData == null) { logDebug("No value for $KEY_TOKEN_LIST_META_DATA found.") return } TokenUtil.initialize(BreadApp.getBreadContext(), true, !BuildConfig.BITCOIN_TESTNET) val currencyCodeToToken = TokenUtil.getTokenItems() .associateBy { it.symbol.toLowerCase(Locale.ROOT) } tokenListMetaData.enabledCurrencies .filter { enabledToken -> // Need to also ensure not in hidden currencies list tokenListMetaData.hiddenCurrencies.find { it.symbol.equals(enabledToken.symbol, true) } == null } .mapNotNull { currencyCodeToToken[it.symbol.toLowerCase(Locale.ROOT)]?.currencyId } .apply { if (isNotEmpty()) { putEnabledWallets(this) logDebug("Migration to $KEY_ASSET_INDEX completed.") } } } catch (ex: JSONException) { logError("$ex") } } private suspend fun getOrSync( key: String, defaultProducer: (() -> JSONObject)? = null ): JSONObject? { val value = storeProvider.get(key) ?: storeProvider.sync(key) return when (value) { null -> { defaultProducer ?.invoke() ?.also { logDebug("Sync returned null. Putting default value: $key -> $it") storeProvider.put(key, it) } } else -> value } } private fun enabledWalletsToJSON(wallets: List<String>) = JSONObject( mapOf( CLASS_VERSION to CLASS_VERSION_ASSET_IDS, ENABLED_ASSET_IDS to wallets.toJSON() ) ) private fun jsonToEnabledWallets(walletsJSON: JSONObject) = walletsJSON .getJSONArray(ENABLED_ASSET_IDS) .run { List(length(), this::getString) } private fun List<String>.toJSON(): JSONArray { val json = JSONArray() forEach { json.put(it) } return json } private fun getTxMetaDataKey(transaction: Transfer, legacy: Boolean = false): String { return getTxMetaDataKey( transferHash = transaction.hashString(), isErc20 = transaction.wallet.currency.isErc20(), legacy = legacy ) } private fun getTxMetaDataKey( transferHash: String, isErc20: Boolean, legacy: Boolean = false ): String = if (legacy) { TX_META_DATA_KEY_PREFIX + Utils.bytesToHex( CryptoHelper.sha256(transferHash.toByteArray())!! ) } else { val hashString = transferHash.removePrefix("0x") val sha256hash = (CryptoHelper.hexDecode(hashString) ?: hashString.toByteArray(Charsets.UTF_8)) .apply { reverse() } .run(CryptoHelper::sha256) ?.run(CryptoHelper::hexEncode) ?: "" if (isErc20) TK_META_DATA_KEY_PREFIX + sha256hash else TX_META_DATA_KEY_PREFIX + sha256hash } private fun pairingKey(pubKey: ByteArray): String = PAIRING_META_DATA_KEY_PREFIX + CryptoHelper.hexEncode(CryptoHelper.sha256(pubKey)!!) }
app/src/main/java/com/platform/interfaces/MetaDataManager.kt
1873013364
package io.github.adven27.concordion.extensions.exam.db.commands.check import io.github.adven27.concordion.extensions.exam.core.commands.SuitableCommandParser import io.github.adven27.concordion.extensions.exam.core.commands.awaitConfig import io.github.adven27.concordion.extensions.exam.core.html.DbRowParser import io.github.adven27.concordion.extensions.exam.core.html.Html import io.github.adven27.concordion.extensions.exam.core.html.attr import io.github.adven27.concordion.extensions.exam.core.html.html import io.github.adven27.concordion.extensions.exam.db.DbTester.Companion.DEFAULT_DATASOURCE import io.github.adven27.concordion.extensions.exam.db.MarkedHasNoDefaultValue import io.github.adven27.concordion.extensions.exam.db.TableData import io.github.adven27.concordion.extensions.exam.db.builder.DataSetBuilder import io.github.adven27.concordion.extensions.exam.db.builder.ExamTable import io.github.adven27.concordion.extensions.exam.db.commands.ColParser import io.github.adven27.concordion.extensions.exam.db.commands.check.CheckCommand.Expected import org.concordion.api.CommandCall import org.concordion.api.Element import org.concordion.api.Evaluator import org.dbunit.dataset.Column import org.dbunit.dataset.DefaultTable import org.dbunit.dataset.ITable import org.dbunit.dataset.datatype.DataType abstract class CheckParser : SuitableCommandParser<Expected> { abstract fun table(command: CommandCall, evaluator: Evaluator): ITable abstract fun caption(command: CommandCall): String? override fun parse(command: CommandCall, evaluator: Evaluator) = Expected( ds = command.attr("ds", DEFAULT_DATASOURCE), caption = caption(command), table = table(command, evaluator), orderBy = command.html().takeAwayAttr("orderBy", evaluator)?.split(",")?.map { it.trim() } ?: listOf(), where = command.html().takeAwayAttr("where", evaluator) ?: "", await = command.awaitConfig() ) } class MdCheckParser : CheckParser() { override fun isSuitFor(element: Element): Boolean = element.localName != "div" override fun caption(command: CommandCall) = command.element.text.ifBlank { null } private fun root(command: CommandCall) = command.element.parentElement.parentElement override fun table(command: CommandCall, evaluator: Evaluator): ITable { val builder = DataSetBuilder() val tableName = command.expression return root(command) .let { cols(it) to values(it) } .let { (cols, rows) -> rows.forEach { row -> builder.newRowTo(tableName).withFields(cols.zip(row).toMap()).add() } builder.build().let { ExamTable( if (it.tableNames.isEmpty()) DefaultTable(tableName, toColumns(cols)) else it.getTable(tableName), evaluator ) } } } private fun toColumns(cols: List<String>) = cols.map { Column(it, DataType.UNKNOWN) }.toTypedArray() private fun cols(it: Element) = it.getFirstChildElement("thead").getFirstChildElement("tr").childElements.map { it.text.trim() } private fun values(it: Element) = it.getFirstChildElement("tbody").childElements.map { tr -> tr.childElements.map { it.text.trim() } } } open class HtmlCheckParser : CheckParser() { private val remarks = HashMap<String, Int>() private val colParser = ColParser() override fun isSuitFor(element: Element): Boolean = element.localName == "div" override fun caption(command: CommandCall) = command.html().attr("caption") override fun table(command: CommandCall, evaluator: Evaluator): ITable = command.html().let { TableData.filled( it.takeAwayAttr("table", evaluator)!!, DbRowParser(it, "row", null, null).parse(), parseCols(it), evaluator ) } protected fun parseCols(el: Html): Map<String, Any?> { val attr = el.takeAwayAttr("cols") return if (attr == null) emptyMap() else { val remarkAndVal = colParser.parse(attr) remarks += remarkAndVal.map { it.key to it.value.first }.filter { it.second > 0 } remarkAndVal.mapValues { if (it.value.second == null) MarkedHasNoDefaultValue() else it.value.second } } } }
exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/commands/check/CheckParsers.kt
1318288138
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.webencode import android.os.Bundle import android.view.MenuItem import dagger.hilt.android.AndroidEntryPoint import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.ui.app.ThemeActivity @AndroidEntryPoint class WebTextEncodeSettingActivity : ThemeActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_base) val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) supportFragmentManager.beginTransaction() .replace(R.id.container, WebTextEncodeSettingFragment()).commit() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } } }
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/webencode/WebTextEncodeSettingActivity.kt
2535990477