repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
google/intellij-community
plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/AnnotationPresentationInfo.kt
2
8508
// 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.highlighter import com.intellij.codeInsight.daemon.HighlightDisplayKey import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.impl.HighlightInfoType import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionWithOptions import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.SuppressableProblemGroup import com.intellij.openapi.editor.colors.CodeInsightColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.TextRange import com.intellij.util.containers.MultiMap import com.intellij.xml.util.XmlStringUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages import org.jetbrains.kotlin.idea.base.fe10.highlighting.KotlinBaseFe10HighlightingBundle import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode import org.jetbrains.kotlin.idea.util.application.isUnitTestMode class AnnotationPresentationInfo( val ranges: List<TextRange>, @Nls val nonDefaultMessage: String? = null, val highlightType: ProblemHighlightType? = null, val textAttributes: TextAttributesKey? = null ) { companion object { private const val KOTLIN_COMPILER_WARNING_ID = "KotlinCompilerWarningOptions" private const val KOTLIN_COMPILER_ERROR_ID = "KotlinCompilerErrorOptions" } fun processDiagnostics( holder: HighlightInfoHolder, diagnostics: Collection<Diagnostic>, highlightInfoBuilderByDiagnostic: MutableMap<Diagnostic, HighlightInfo>? = null, highlightInfoByTextRange: MutableMap<TextRange, HighlightInfo>?, fixesMap: MultiMap<Diagnostic, IntentionAction>?, calculatingInProgress: Boolean ) { for (range in ranges) { for (diagnostic in diagnostics) { create(diagnostic, range) { info -> holder.add(info) highlightInfoBuilderByDiagnostic?.put(diagnostic, info) if (fixesMap != null) { applyFixes(fixesMap, diagnostic, info) } if (calculatingInProgress && highlightInfoByTextRange?.containsKey(range) == false) { highlightInfoByTextRange[range] = info QuickFixAction.registerQuickFixAction(info, CalculatingIntentionAction()) } } } } } internal fun applyFixes( quickFixes: MultiMap<Diagnostic, IntentionAction>, diagnostic: Diagnostic, info: HighlightInfo ) { val warning = diagnostic.severity == Severity.WARNING val error = diagnostic.severity == Severity.ERROR val fixes = quickFixes[diagnostic].takeIf { it.isNotEmpty() } ?: if (warning) listOf(CompilerWarningIntentionAction(diagnostic.factory.name)) else emptyList() val keyForSuppressOptions = when { error -> HighlightDisplayKey.findOrRegister( KOTLIN_COMPILER_ERROR_ID, KotlinBaseFe10HighlightingBundle.message("kotlin.compiler.error") ) else -> HighlightDisplayKey.findOrRegister( KOTLIN_COMPILER_WARNING_ID, KotlinBaseFe10HighlightingBundle.message("kotlin.compiler.warning") ) } for (fix in fixes) { if (fix !is IntentionAction) { continue } val options = mutableListOf<IntentionAction>() if (fix is IntentionActionWithOptions) { options += fix.options } val problemGroup = info.problemGroup if (problemGroup is SuppressableProblemGroup) { options += problemGroup.getSuppressActions(diagnostic.psiElement).mapNotNull { it as IntentionAction } } val message = KotlinBaseFe10HighlightingBundle.message(if (error) "kotlin.compiler.error" else "kotlin.compiler.warning") info.registerFix(fix, options, message, null, keyForSuppressOptions) } } private fun create(diagnostic: Diagnostic, range: TextRange, consumer: (HighlightInfo) -> Unit) { val message = nonDefaultMessage ?: getDefaultMessage(diagnostic) HighlightInfo .newHighlightInfo(toHighlightInfoType(highlightType, diagnostic.severity)) .range(range) .description(message) .escapedToolTip(getMessage(diagnostic)) .also { builder -> textAttributes?.let(builder::textAttributes) ?: convertSeverityTextAttributes(highlightType, diagnostic.severity)?.let(builder::textAttributes) } .also { if (diagnostic.severity == Severity.WARNING) { it.problemGroup(KotlinSuppressableWarningProblemGroup(diagnostic.factory)) } } .createUnconditionally() .also(consumer) } @NlsContexts.Tooltip private fun getMessage(diagnostic: Diagnostic): String { var message = IdeErrorMessages.render(diagnostic) if (isApplicationInternalMode() || isUnitTestMode()) { val factoryName = diagnostic.factory.name message = if (message.startsWith("<html>")) { @Suppress("HardCodedStringLiteral") "<html>[$factoryName] ${message.substring("<html>".length)}" } else { "[$factoryName] $message" } } if (!message.startsWith("<html>")) { message = "<html><body>${XmlStringUtil.escapeString(message)}</body></html>" } return message } private fun getDefaultMessage(diagnostic: Diagnostic): String { val message = DefaultErrorMessages.render(diagnostic) return if (isApplicationInternalMode() || isUnitTestMode()) { "[${diagnostic.factory.name}] $message" } else { message } } private fun toHighlightInfoType(highlightType: ProblemHighlightType?, severity: Severity): HighlightInfoType = when (highlightType) { ProblemHighlightType.LIKE_UNUSED_SYMBOL -> HighlightInfoType.UNUSED_SYMBOL ProblemHighlightType.LIKE_UNKNOWN_SYMBOL -> HighlightInfoType.WRONG_REF ProblemHighlightType.LIKE_DEPRECATED -> HighlightInfoType.DEPRECATED ProblemHighlightType.LIKE_MARKED_FOR_REMOVAL -> HighlightInfoType.MARKED_FOR_REMOVAL else -> convertSeverity(highlightType, severity) } private fun convertSeverity(highlightType: ProblemHighlightType?, severity: Severity): HighlightInfoType = when (severity) { Severity.ERROR -> HighlightInfoType.ERROR Severity.WARNING -> { if (highlightType == ProblemHighlightType.WEAK_WARNING) { HighlightInfoType.WEAK_WARNING } else HighlightInfoType.WARNING } Severity.INFO -> HighlightInfoType.WEAK_WARNING else -> HighlightInfoType.INFORMATION } private fun convertSeverityTextAttributes(highlightType: ProblemHighlightType?, severity: Severity): TextAttributesKey? = when (highlightType) { null, ProblemHighlightType.GENERIC_ERROR_OR_WARNING -> when (severity) { Severity.ERROR -> CodeInsightColors.ERRORS_ATTRIBUTES Severity.WARNING -> { if (highlightType == ProblemHighlightType.WEAK_WARNING) { CodeInsightColors.WEAK_WARNING_ATTRIBUTES } else CodeInsightColors.WARNINGS_ATTRIBUTES } Severity.INFO -> CodeInsightColors.WARNINGS_ATTRIBUTES else -> null } ProblemHighlightType.GENERIC_ERROR -> CodeInsightColors.ERRORS_ATTRIBUTES else -> null } }
apache-2.0
6725923114dff87da42a2f691d60e76c
44.015873
176
0.659144
5.478429
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/configuration/ScriptResidenceExceptionProvider.kt
1
1498
// 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.script.configuration import com.intellij.openapi.vfs.VirtualFile internal open class ScriptResidenceExceptionProvider( private val suffix: String, private val supportedUnderSourceRoot: Boolean = false ) { open fun isSupportedScriptExtension(virtualFile: VirtualFile): Boolean = virtualFile.name.endsWith(suffix) fun isSupportedUnderSourceRoot(virtualFile: VirtualFile): Boolean = if (supportedUnderSourceRoot) isSupportedScriptExtension(virtualFile) else false } internal val scriptResidenceExceptionProviders = listOf( object : ScriptResidenceExceptionProvider(".gradle.kts", true) {}, object : ScriptResidenceExceptionProvider(".main.kts") {}, object : ScriptResidenceExceptionProvider(".space.kts") {}, object : ScriptResidenceExceptionProvider(".ws.kts", true) {}, object : ScriptResidenceExceptionProvider(".teamcity.kts", true) { override fun isSupportedScriptExtension(virtualFile: VirtualFile): Boolean { if (!virtualFile.name.endsWith(".kts")) return false var parent = virtualFile.parent while (parent != null) { if (parent.isDirectory && parent.name == ".teamcity") { return true } parent = parent.parent } return false } } )
apache-2.0
a91e6998a6f757a6b1c6b39b151a9459
38.447368
120
0.688251
4.943894
false
false
false
false
google/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/google/utils/GoogleAccountsUtils.kt
5
9327
// 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.google.utils import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.google.api.client.auth.oauth2.Credential import com.google.api.client.auth.oauth2.TokenResponse import com.google.api.client.googleapis.auth.oauth2.GoogleCredential import com.intellij.collaboration.auth.ui.AccountsPanelFactory import com.intellij.collaboration.util.ProgressIndicatorsProvider import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.ThrowableComputable import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.util.alsoIfNull import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.google.GoogleAppCredentialsException import org.intellij.plugins.markdown.google.accounts.GoogleAccountManager import org.intellij.plugins.markdown.google.accounts.GoogleAccountsDetailsLoader import org.intellij.plugins.markdown.google.accounts.GoogleAccountsListModel import org.intellij.plugins.markdown.google.accounts.GoogleUserInfoService import org.intellij.plugins.markdown.google.accounts.data.GoogleAccount import org.intellij.plugins.markdown.google.authorization.GoogleCredentials import org.intellij.plugins.markdown.google.authorization.GoogleOAuthService import org.intellij.plugins.markdown.google.authorization.getGoogleAuthRequest import org.intellij.plugins.markdown.google.authorization.getGoogleRefreshRequest import org.intellij.plugins.markdown.google.ui.GoogleChooseAccountDialog import java.net.ConnectException import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeoutException internal object GoogleAccountsUtils { data class GoogleAppCredentials(val clientId: String, val clientSecret: String) val jacksonMapper: ObjectMapper get() = jacksonObjectMapper() private val LOG = logger<GoogleOAuthService>() @RequiresEdt fun chooseAccount(project: Project): Credential? { val accountsListModel = GoogleAccountsListModel() val accountManager = service<GoogleAccountManager>() val oAuthService = service<GoogleOAuthService>() if (!GoogleChooseAccountDialog(project, accountsListModel, accountManager).showAndGet()) return null updateAccountsList(accountsListModel, accountManager) return try { val selectedAccount = accountsListModel.selectedAccount ?: error("The selected account cannot be null") val accountCredentials: GoogleCredentials = getOrUpdateUserCredentials(oAuthService, accountManager, selectedAccount) ?: tryToReLogin(project) ?: return null createCredentialsForGoogleApi(accountCredentials) } catch (e: TimeoutException) { LOG.debug(e) null } catch (e: IllegalStateException) { LOG.debug(e) null } } fun tryToReLogin(project: Project): GoogleCredentials? { var credentialsFuture: CompletableFuture<GoogleCredentials> = CompletableFuture() return try { ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { val request = getGoogleAuthRequest() credentialsFuture = service<GoogleOAuthService>().authorize(request) ProgressIndicatorUtils.awaitWithCheckCanceled(credentialsFuture) }, MarkdownBundle.message("markdown.google.account.login.progress.title"), true, project) } catch (t: Throwable) { credentialsFuture.cancel(true) null } } /** * Returns the user's credentials if the access token is still valid, otherwise updates the credentials and returns updated. */ @RequiresEdt fun getOrUpdateUserCredentials(oAuthService: GoogleOAuthService, accountManager: GoogleAccountManager, account: GoogleAccount): GoogleCredentials? = accountManager.findCredentials(account)?.let { credentials -> if (credentials.isAccessTokenValid()) return credentials val refreshRequest = getGoogleRefreshRequest(credentials.refreshToken) val credentialFuture = oAuthService.updateAccessToken(refreshRequest) return try { ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { val newCred = ProgressIndicatorUtils.awaitWithCheckCanceled(credentialFuture) accountManager.updateAccount(account, newCred) newCred }, MarkdownBundle.message("markdown.google.account.update.credentials.progress.title"), true, null) } catch (e: RuntimeException) { val message = e.cause?.cause?.localizedMessage.alsoIfNull { e.localizedMessage } LOG.warn("Failed to update user credentials:\n$message") null } } /** * @return the panel for selecting Google accounts with the ability to edit the list of accounts. */ fun createGoogleAccountPanel(disposable: Disposable, accountsListModel: GoogleAccountsListModel, accountManager: GoogleAccountManager): DialogPanel { val oAuthService = service<GoogleOAuthService>() val userInfoService = service<GoogleUserInfoService>() val scope = CoroutineScope(SupervisorJob()).also { Disposer.register(disposable) { it.cancel() } } val detailsLoader = GoogleAccountsDetailsLoader( scope, accountManager, accountsListModel, oAuthService, userInfoService ) val panelFactory = AccountsPanelFactory(accountManager, accountsListModel, detailsLoader, disposable) return panel { row { panelFactory.accountsPanelCell(this, false) .horizontalAlign(HorizontalAlign.FILL) .verticalAlign(VerticalAlign.FILL) }.resizableRow() } } /** * Credentials for Installed application from google console. * Note: In this context, the client secret is obviously not treated as a secret. * These credentials are fine to be public: https://developers.google.com/identity/protocols/oauth2#installed */ @RequiresBackgroundThread fun getGoogleAppCredentials(): GoogleAppCredentials? { val googleAppCredUrl = "https://www.jetbrains.com/config/markdown.json" try { val client = HttpClient.newHttpClient() val httpRequest: HttpRequest = HttpRequest.newBuilder() .uri(URI.create(googleAppCredUrl)) .header("Content-Type", "application/json") .GET() .build() val response = client.send(httpRequest, HttpResponse.BodyHandlers.ofString()) if (response.statusCode() == 200) { with(jacksonMapper) { val credentials = readTree(response.body()).get("google").get("auth") val clientId = credentials.get("secret-id").asText() val clientSecret = credentials.get("client-secret").asText() return GoogleAppCredentials(clientId, clientSecret) } } else { LOG.info("Status code: ${response.statusCode()}\n${response.body()}") return null } } catch (e: ConnectException) { LOG.info(GoogleAppCredentialsException()) return null } } /** * Converts internal GoogleCredentials to Credentials that the Google API can work with */ fun createCredentialsForGoogleApi(credentials: GoogleCredentials): Credential { val tokenResponse = getTokenResponse(credentials) return GoogleCredential().setFromTokenResponse(tokenResponse) } @RequiresEdt private fun updateAccountsList(accountsListModel: GoogleAccountsListModel, accountManager: GoogleAccountManager) { val newTokensMap = mutableMapOf<GoogleAccount, GoogleCredentials?>() newTokensMap.putAll(accountsListModel.newCredentials) for (account in accountsListModel.accounts) { newTokensMap.putIfAbsent(account, null) } accountManager.updateAccounts(newTokensMap) accountsListModel.clearNewCredentials() } /** * Converts GoogleCredentials to TokenResponse to further get the Credential needed to work with the Drive API */ private fun getTokenResponse(credentials: GoogleCredentials): TokenResponse = TokenResponse().apply { accessToken = credentials.accessToken tokenType = credentials.tokenType scope = credentials.scope expiresInSeconds = credentials.expiresIn } }
apache-2.0
cdcf80223d83f157efde1b8c3e736b47
40.638393
158
0.75008
4.993041
false
false
false
false
google/intellij-community
plugins/gradle/java/src/service/resolve/GradleExtensionsContributor.kt
2
6822
// 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.plugins.gradle.service.resolve import com.intellij.icons.AllIcons import com.intellij.lang.properties.IProperty import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vfs.VfsUtil import com.intellij.psi.* import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiUtilCore import com.intellij.util.castSafelyTo import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_PROJECT import org.jetbrains.plugins.gradle.service.resolve.staticModel.impl.getStaticPluginModel import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleExtensionsData import org.jetbrains.plugins.gradle.settings.GradleLocalSettings import org.jetbrains.plugins.gradle.util.PROPERTIES_FILE_NAME import org.jetbrains.plugins.gradle.util.getGradleUserHomePropertiesPath import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightField import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor import org.jetbrains.plugins.groovy.lang.resolve.getName import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.type import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessProperties import java.nio.file.Path class GradleExtensionsContributor : NonCodeMembersContributor() { override fun getClassNames(): Collection<String> { return listOf(GradleCommonClassNames.GRADLE_API_EXTRA_PROPERTIES_EXTENSION, GRADLE_API_PROJECT) } override fun processDynamicElements(qualifierType: PsiType, aClass: PsiClass?, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) { if (qualifierType !is GradleProjectAwareType && !InheritanceUtil.isInheritor(qualifierType, GradleCommonClassNames.GRADLE_API_EXTRA_PROPERTIES_EXTENSION)) return if (!processor.shouldProcessProperties()) return val file = place.containingFile val data = getExtensionsFor(file) ?: return val name = processor.getName(state) val resolvedProperties = processPropertiesFromFile(aClass, processor, place, state) val properties = if (name == null) data.findAllProperties() else listOfNotNull(data.findProperty(name)) val dynamicPropertiesNames = properties.map { it.name } val staticProperties = getStaticPluginModel(place.containingFile).extensions.filter { if (name == null) it.name !in dynamicPropertiesNames else it.name == name } for (property in properties) { if (property.name in resolvedProperties) { continue } if (!processor.execute(GradleGroovyProperty(property.name, property.typeFqn, property.value, file), state)) { return } } for (property in staticProperties) { if (property.name in resolvedProperties) { continue } if (!processor.execute(GradleGroovyProperty(property.name, property.type, null, file), state)) { return } } } private fun processPropertiesFromFile(aClass: PsiClass?, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) : Set<String> { if (aClass == null) { return emptySet() } val factory = JavaPsiFacade.getInstance(place.project) val stringType = factory.findClass(CommonClassNames.JAVA_LANG_STRING, place.resolveScope)?.type() ?: return emptySet() val properties = gradlePropertiesStream(place) val name = processor.getName(state) val processedNames = mutableSetOf<String>() for (propertyFile in properties) { if (name == null) { for (property in propertyFile.properties) { if (property.name.contains(".")) { continue } processedNames.add(property.name) val newProperty = createGroovyProperty(aClass, property, stringType) processor.execute(newProperty, state) } } else { val property = propertyFile.findPropertyByKey(name) ?: continue val newProperty = createGroovyProperty(aClass, property, stringType) processor.execute(newProperty, state) return setOf(newProperty.name) } } return processedNames } companion object { fun gradlePropertiesStream(place: PsiElement): Sequence<PropertiesFile> = sequence { val externalRootProjectPath = place.getRootGradleProjectPath() ?: return@sequence val userHomePropertiesFile = getGradleUserHomePropertiesPath()?.parent?.toString()?.getGradlePropertiesFile(place.project) if (userHomePropertiesFile != null) { yield(userHomePropertiesFile) } val projectRootPropertiesFile = externalRootProjectPath.getGradlePropertiesFile(place.project) if (projectRootPropertiesFile != null) { yield(projectRootPropertiesFile) } val localSettings = GradleLocalSettings.getInstance(place.project) val installationDirectoryPropertiesFile = localSettings.getGradleHome(externalRootProjectPath)?.getGradlePropertiesFile(place.project) if (installationDirectoryPropertiesFile != null) { yield(installationDirectoryPropertiesFile) } } private fun String.getGradlePropertiesFile(project: Project): PropertiesFile? { val file = VfsUtil.findFile(Path.of(this), false)?.findChild(PROPERTIES_FILE_NAME) return file?.let { PsiUtilCore.getPsiFile(project, it) }.castSafelyTo<PropertiesFile>() } private fun createGroovyProperty(aClass: PsiClass, property: IProperty, stringType: PsiClassType): GrLightField { val newProperty = GrLightField(aClass, property.name, stringType, property.psiElement) newProperty.setIcon(AllIcons.FileTypes.Properties) newProperty.originInfo = propertiesFileOriginInfo return newProperty } fun getExtensionsFor(psiElement: PsiElement): GradleExtensionsData? { val project = psiElement.project val virtualFile = psiElement.containingFile?.originalFile?.virtualFile ?: return null val module = ProjectFileIndex.getInstance(project).getModuleForFile(virtualFile) return GradleExtensionsSettings.getInstance(project).getExtensionsFor(module) } internal const val propertiesFileOriginInfo : String = "by gradle.properties" } }
apache-2.0
feebea6cad7c3fa6c51fe1644f27a429
44.785235
165
0.72105
5.064588
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/SearchActivity.kt
1
11594
package com.simplemobiletools.gallery.pro.activities import android.app.SearchManager import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.ViewGroup import android.widget.RelativeLayout import androidx.appcompat.widget.SearchView import androidx.core.view.MenuItemCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.NavigationIcon import com.simplemobiletools.commons.helpers.VIEW_TYPE_GRID import com.simplemobiletools.commons.helpers.ensureBackgroundThread import com.simplemobiletools.commons.models.FileDirItem import com.simplemobiletools.commons.views.MyGridLayoutManager import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.adapters.MediaAdapter import com.simplemobiletools.gallery.pro.asynctasks.GetMediaAsynctask import com.simplemobiletools.gallery.pro.extensions.* import com.simplemobiletools.gallery.pro.helpers.GridSpacingItemDecoration import com.simplemobiletools.gallery.pro.helpers.MediaFetcher import com.simplemobiletools.gallery.pro.helpers.PATH import com.simplemobiletools.gallery.pro.helpers.SHOW_ALL import com.simplemobiletools.gallery.pro.interfaces.MediaOperationsListener import com.simplemobiletools.gallery.pro.models.Medium import com.simplemobiletools.gallery.pro.models.ThumbnailItem import kotlinx.android.synthetic.main.activity_search.* import java.io.File class SearchActivity : SimpleActivity(), MediaOperationsListener { private var mIsSearchOpen = false private var mLastSearchedText = "" private var mSearchMenuItem: MenuItem? = null private var mCurrAsyncTask: GetMediaAsynctask? = null private var mAllMedia = ArrayList<ThumbnailItem>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_search) setupOptionsMenu() search_empty_text_placeholder.setTextColor(getProperTextColor()) getAllMedia() search_fastscroller.updateColors(getProperPrimaryColor()) } override fun onResume() { super.onResume() setupToolbar(search_toolbar, NavigationIcon.Arrow, searchMenuItem = mSearchMenuItem) } override fun onDestroy() { super.onDestroy() mCurrAsyncTask?.stopFetching() } private fun setupOptionsMenu() { setupSearch(search_toolbar.menu) search_toolbar.setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.toggle_filename -> toggleFilenameVisibility() else -> return@setOnMenuItemClickListener false } return@setOnMenuItemClickListener true } } private fun setupSearch(menu: Menu) { val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager mSearchMenuItem = menu.findItem(R.id.search) MenuItemCompat.setOnActionExpandListener(mSearchMenuItem, object : MenuItemCompat.OnActionExpandListener { override fun onMenuItemActionExpand(item: MenuItem?): Boolean { mIsSearchOpen = true return true } // this triggers on device rotation too, avoid doing anything override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { if (mIsSearchOpen) { mIsSearchOpen = false mLastSearchedText = "" } return true } }) mSearchMenuItem?.expandActionView() (mSearchMenuItem?.actionView as? SearchView)?.apply { setSearchableInfo(searchManager.getSearchableInfo(componentName)) isSubmitButtonEnabled = false setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String) = false override fun onQueryTextChange(newText: String): Boolean { if (mIsSearchOpen) { mLastSearchedText = newText textChanged(newText) } return true } }) } } private fun textChanged(text: String) { ensureBackgroundThread { try { val filtered = mAllMedia.filter { it is Medium && it.name.contains(text, true) } as ArrayList filtered.sortBy { it is Medium && !it.name.startsWith(text, true) } val grouped = MediaFetcher(applicationContext).groupMedia(filtered as ArrayList<Medium>, "") runOnUiThread { if (grouped.isEmpty()) { search_empty_text_placeholder.text = getString(R.string.no_items_found) search_empty_text_placeholder.beVisible() } else { search_empty_text_placeholder.beGone() } handleGridSpacing(grouped) getMediaAdapter()?.updateMedia(grouped) } } catch (ignored: Exception) { } } } private fun setupAdapter() { val currAdapter = search_grid.adapter if (currAdapter == null) { MediaAdapter(this, ArrayList(), this, false, false, "", search_grid) { if (it is Medium) { itemClicked(it.path) } }.apply { search_grid.adapter = this } setupLayoutManager() handleGridSpacing(mAllMedia) } else if (mLastSearchedText.isEmpty()) { (currAdapter as MediaAdapter).updateMedia(mAllMedia) handleGridSpacing(mAllMedia) } else { textChanged(mLastSearchedText) } setupScrollDirection() } private fun handleGridSpacing(media: ArrayList<ThumbnailItem>) { val viewType = config.getFolderViewType(SHOW_ALL) if (viewType == VIEW_TYPE_GRID) { if (search_grid.itemDecorationCount > 0) { search_grid.removeItemDecorationAt(0) } val spanCount = config.mediaColumnCnt val spacing = config.thumbnailSpacing val decoration = GridSpacingItemDecoration(spanCount, spacing, config.scrollHorizontally, config.fileRoundedCorners, media, true) search_grid.addItemDecoration(decoration) } } private fun getMediaAdapter() = search_grid.adapter as? MediaAdapter private fun toggleFilenameVisibility() { config.displayFileNames = !config.displayFileNames getMediaAdapter()?.updateDisplayFilenames(config.displayFileNames) } private fun itemClicked(path: String) { val isVideo = path.isVideoFast() if (isVideo) { openPath(path, false) } else { Intent(this, ViewPagerActivity::class.java).apply { putExtra(PATH, path) putExtra(SHOW_ALL, false) startActivity(this) } } } private fun setupLayoutManager() { val viewType = config.getFolderViewType(SHOW_ALL) if (viewType == VIEW_TYPE_GRID) { setupGridLayoutManager() } else { setupListLayoutManager() } } private fun setupGridLayoutManager() { val layoutManager = search_grid.layoutManager as MyGridLayoutManager if (config.scrollHorizontally) { layoutManager.orientation = RecyclerView.HORIZONTAL search_grid.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT) } else { layoutManager.orientation = RecyclerView.VERTICAL search_grid.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } layoutManager.spanCount = config.mediaColumnCnt val adapter = getMediaAdapter() layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (adapter?.isASectionTitle(position) == true) { layoutManager.spanCount } else { 1 } } } } private fun setupListLayoutManager() { val layoutManager = search_grid.layoutManager as MyGridLayoutManager layoutManager.spanCount = 1 layoutManager.orientation = RecyclerView.VERTICAL } private fun setupScrollDirection() { val viewType = config.getFolderViewType(SHOW_ALL) val scrollHorizontally = config.scrollHorizontally && viewType == VIEW_TYPE_GRID search_fastscroller.setScrollVertically(!scrollHorizontally) } private fun getAllMedia() { getCachedMedia("") { if (it.isNotEmpty()) { mAllMedia = it.clone() as ArrayList<ThumbnailItem> } runOnUiThread { setupAdapter() } startAsyncTask(false) } } private fun startAsyncTask(updateItems: Boolean) { mCurrAsyncTask?.stopFetching() mCurrAsyncTask = GetMediaAsynctask(applicationContext, "", showAll = true) { mAllMedia = it.clone() as ArrayList<ThumbnailItem> if (updateItems) { textChanged(mLastSearchedText) } } mCurrAsyncTask!!.execute() } override fun refreshItems() { startAsyncTask(true) } override fun tryDeleteFiles(fileDirItems: ArrayList<FileDirItem>) { val filtered = fileDirItems.filter { File(it.path).isFile && it.path.isMediaFile() } as ArrayList if (filtered.isEmpty()) { return } if (config.useRecycleBin && !filtered.first().path.startsWith(recycleBinPath)) { val movingItems = resources.getQuantityString(R.plurals.moving_items_into_bin, filtered.size, filtered.size) toast(movingItems) movePathsInRecycleBin(filtered.map { it.path } as ArrayList<String>) { if (it) { deleteFilteredFiles(filtered) } else { toast(R.string.unknown_error_occurred) } } } else { val deletingItems = resources.getQuantityString(R.plurals.deleting_items, filtered.size, filtered.size) toast(deletingItems) deleteFilteredFiles(filtered) } } private fun deleteFilteredFiles(filtered: ArrayList<FileDirItem>) { deleteFiles(filtered) { if (!it) { toast(R.string.unknown_error_occurred) return@deleteFiles } mAllMedia.removeAll { filtered.map { it.path }.contains((it as? Medium)?.path) } ensureBackgroundThread { val useRecycleBin = config.useRecycleBin filtered.forEach { if (it.path.startsWith(recycleBinPath) || !useRecycleBin) { deleteDBPath(it.path) } } } } } override fun selectedPaths(paths: ArrayList<String>) {} override fun updateMediaGridDecoration(media: ArrayList<ThumbnailItem>) {} }
gpl-3.0
ba4308ea8c79329236a6073e00de28bb
36.765472
141
0.631016
5.25805
false
false
false
false
aporter/coursera-android
ExamplesKotlin/FragmentDynamicLayout/app/src/main/java/course/examples/fragments/dynamiclayout/QuotesFragment.kt
1
3050
package course.examples.fragments.dynamiclayout import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListView import android.widget.TextView //Several Activity and Fragment lifecycle methods are instrumented to emit LogCat output //so you can follow the class' lifecycle class QuotesFragment : Fragment() { companion object { private const val TAG = "QuotesFragment" } private lateinit var mQuoteView: TextView private var mCurrIdx = ListView.INVALID_POSITION private var mQuoteArrayLen: Int = 0 // Show the Quote string at position newIndex internal fun showQuoteAtIndex(index: Int) { if (index in 0 until mQuoteArrayLen) { mQuoteView.text = QuoteViewerActivity.mQuoteArray[index] mCurrIdx = index } } override fun onCreate(savedInstanceState: Bundle?) { Log.i(TAG, "${javaClass.simpleName}: entered onCreate()") super.onCreate(savedInstanceState) retainInstance = true } // Called to create the content view for this Fragment override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { Log.i(TAG, "${javaClass.simpleName}: entered onCreateView()") // Inflate the layout defined in quote_fragment.xml // The last parameter is false because the returned view // does not need to be attached to the container ViewGroup return inflater.inflate( R.layout.quote_fragment, container, false ) } // Set up some information about the mQuoteView TextView override fun onActivityCreated(savedInstanceState: Bundle?) { Log.i(TAG, "${javaClass.simpleName}: entered onActivityCreated()") super.onActivityCreated(savedInstanceState) mQuoteView = activity!!.findViewById(R.id.quoteView) mQuoteArrayLen = QuoteViewerActivity.mQuoteArray.size showQuoteAtIndex(mCurrIdx) } override fun onStart() { Log.i(TAG, "${javaClass.simpleName}: entered onStart()") super.onStart() } override fun onResume() { Log.i(TAG, "${javaClass.simpleName}: entered onResume()") super.onResume() } override fun onPause() { Log.i(TAG, "${javaClass.simpleName}: entered onPause()") super.onPause() } override fun onStop() { Log.i(TAG, "${javaClass.simpleName}: entered onStop()") super.onStop() } override fun onDetach() { Log.i(TAG, "${javaClass.simpleName}: entered onDetach()") super.onDetach() } override fun onDestroy() { Log.i(TAG, "${javaClass.simpleName}: entered onDestroy()") super.onDestroy() } override fun onDestroyView() { Log.i(TAG, "${javaClass.simpleName}: entered onDestroyView()") super.onDestroyView() } }
mit
56d62dbedaddd1686c5544d24a08cb22
28.047619
88
0.660328
4.750779
false
false
false
false
pnemonic78/Fractals
fractals-android/app/src/main/kotlin/com/github/fractals/SaveFileObserver.kt
1
4778
/* * Copyright 2016, Moshe Waisberg * * 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.github.fractals import android.annotation.TargetApi import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.app.PendingIntent.FLAG_UPDATE_CURRENT import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.Build.VERSION_CODES import androidx.core.app.NotificationCompat import io.reactivex.rxjava3.core.Observer import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.internal.disposables.DisposableHelper /** * Task to save a bitmap to a file. * * @author Moshe Waisberg */ class SaveFileObserver(private val context: Context, private val bitmap: Bitmap) : Observer<Uri> { private var disposable: Disposable? = null private val nm: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager private lateinit var builder: NotificationCompat.Builder override fun onSubscribe(d: Disposable) { if (DisposableHelper.validate(this.disposable, d)) { this.disposable = d onStart() } } private fun onStart() { val res = context.resources val iconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width) val iconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height) val largeIcon = Bitmap.createScaledBitmap(bitmap, iconWidth, iconHeight, false) val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) val pendingIntent = PendingIntent.getActivity(context, REQUEST_APP, intent, PendingIntent.FLAG_UPDATE_CURRENT) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { initChannels(nm) } builder = NotificationCompat.Builder(context, CHANNEL_ID) .setCategory(NotificationCompat.CATEGORY_PROGRESS) .setContentTitle(context.getText(R.string.saving_title)) .setContentText(context.getText(R.string.saving_text)) .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.stat_notify) .setLargeIcon(largeIcon) .setAutoCancel(true) .setOngoing(true) nm.notify(ID_NOTIFY, builder.build()) } override fun onNext(value: Uri) { builder.setOngoing(false) val intent = Intent(Intent.ACTION_VIEW) intent.setDataAndType(value, IMAGE_MIME) val pendingIntent = PendingIntent.getActivity(context, REQUEST_VIEW, intent, FLAG_UPDATE_CURRENT) builder.setContentTitle(context.getText(R.string.saved_title)) .setContentText(context.getText(R.string.saved_text)) .setContentIntent(pendingIntent) nm.notify(ID_NOTIFY, builder.build()) } override fun onError(e: Throwable) { builder.setOngoing(false) builder.setContentText(context.getText(R.string.save_failed)) nm.notify(ID_NOTIFY, builder.build()) } override fun onComplete() { finish() } /** * Cancels the upstream's disposable. */ private fun finish() { val s = this.disposable this.disposable = DisposableHelper.DISPOSED s?.dispose() } fun cancel() { finish() nm.cancel(ID_NOTIFY) } @TargetApi(VERSION_CODES.O) private fun initChannels(nm: NotificationManager) { var channel = nm.getNotificationChannel(CHANNEL_ID) if (channel == null) { channel = android.app.NotificationChannel(CHANNEL_ID, context.getString(R.string.saving_title), NotificationManager.IMPORTANCE_DEFAULT) channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC nm.createNotificationChannel(channel) } } companion object { private const val REQUEST_APP = 0x0466 // "APP" private const val REQUEST_VIEW = 0x7133 // "VIEW" private const val ID_NOTIFY = 0x5473 // "SAVE" private const val CHANNEL_ID = "save_file" private const val IMAGE_MIME = SaveFileTask.IMAGE_MIME } }
apache-2.0
bc90c7272bcee16c30db01e3a0e03b39
34.139706
147
0.697363
4.465421
false
false
false
false
allotria/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/Typo.kt
2
4374
// Copyright 2000-2019 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.grazie.grammar import com.intellij.grazie.jlanguage.Lang import com.intellij.grazie.utils.* import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus import org.languagetool.rules.IncorrectExample import org.languagetool.rules.Rule import org.languagetool.rules.RuleMatch import org.slf4j.LoggerFactory data class Typo(val location: Location, val info: Info, val fixes: LinkedSet<String> = LinkedSet()) { companion object { private val logger = LoggerFactory.getLogger(Typo::class.java) } data class Location(val errorRange: IntRange, val patternRange: IntRange, val textRanges: Collection<IntRange> = emptyList(), val pointer: PsiPointer<PsiElement>? = null) { val element: PsiElement? get() = pointer?.element val errorText = try { pointer?.element?.text?.subSequence(errorRange)?.toString() } catch (t: Throwable) { logger.warn("Got an exception during getting typo word:\n${pointer?.element!!.text}") throw t } val patternText = try { pointer?.element?.text?.subSequence(patternRange)?.toString() } catch (t: Throwable) { logger.warn("Got an exception during getting pattern text:\n${pointer?.element!!.text}") throw t } } data class Info(val lang: Lang, val rule: Rule, private val myShortMessage: String, val message: String) { val shortMessage: String by lazy { myShortMessage.trimToNull() ?: rule.description.trimToNull() ?: rule.category.name } val incorrectExample: IncorrectExample? by lazy { val withCorrections = rule.incorrectExamples.filter { it.corrections.isNotEmpty() }.takeIf { it.isNotEmpty() } (withCorrections ?: rule.incorrectExamples).minBy { it.example.length } } } /** Constructor for LangTool, applies fixes to RuleMatch (Main constructor doesn't apply fixes) */ constructor(match: RuleMatch, lang: Lang, offset: Int = 0) : this( Location(match.toIntRange(offset), IntRange(match.patternFromPos, match.patternToPos - 1).withOffset(offset)), Info(lang, match.rule, match.shortMessage, match.messageSanitized), LinkedSet(match.getSuggestedReplacements()) ) val category: Category? @Deprecated("Use RuleGroup instead") @ApiStatus.ScheduledForRemoval(inVersion = "2020.2") get() { val category = info.rule.category.name return Category.values().find { it.name == category } } /** * A grammar typo category * * All typos have categories that can be found in the Grazie plugin UI tree in settings/preferences. */ @Deprecated("Use RuleGroup instead") @ApiStatus.ScheduledForRemoval(inVersion = "2020.2") enum class Category { /** General categories */ TEXT_ANALYSIS, /** Rules about detecting uppercase words where lowercase is required and vice versa. */ CASING, /** Rules about spelling terms as one word or as separate words. */ COMPOUNDING, GRAMMAR, /** Spelling issues. */ TYPOS, PUNCTUATION, LOGIC, /** Problems like incorrectly used dash or quote characters. */ TYPOGRAPHY, /** Words that are easily confused, like 'there' and 'their' in English. */ CONFUSED_WORDS, REPETITIONS, REDUNDANCY, /** General style issues not covered by other categories, like overly verbose wording. */ STYLE, GENDER_NEUTRALITY, /** Logic, content, and consistency problems. */ SEMANTICS, /** Colloquial style. */ COLLOQUIALISMS, /** Regionalisms: words used only in another language variant or used with different meanings. */ REGIONALISMS, /** False friends: words easily confused by language learners because a similar word exists in their native language. */ FALSE_FRIENDS, /** Rules that only make sense when editing Wikipedia (typically turned off by default in LanguageTool). */ WIKIPEDIA, /** Miscellaneous rules that don't fit elsewhere. */ MISC, /** English categories */ AMERICAN_ENGLISH, AMERICAN_ENGLISH_STYLE, BRITISH_ENGLISH, BRE_STYLE_OXFORD_SPELLING, CREATIVE_WRITING, MISUSED_TERMS_EU_PUBLICATIONS, NONSTANDARD_PHRASES, PLAIN_ENGLISH; } }
apache-2.0
f60951eb186424de3b4c1cebacfbbcb5
30.467626
140
0.692958
4.072626
false
false
false
false
farmerbb/Taskbar
app/src/test/java/com/farmerbb/taskbar/util/ToastFrameworkImplTest.kt
1
1685
package com.farmerbb.taskbar.util import android.content.Context import android.view.Gravity import android.widget.Toast import androidx.test.core.app.ApplicationProvider import com.farmerbb.taskbar.R import org.junit.Assert 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 @RunWith(RobolectricTestRunner::class) class ToastFrameworkImplTest { private lateinit var context: Context private lateinit var impl: ToastFrameworkImpl private val message = "test-message" private val length = Toast.LENGTH_LONG @Before fun setUp() { context = ApplicationProvider.getApplicationContext() impl = ToastFrameworkImpl(context, message, length) } @Test fun testShow() { impl.show() Assert.assertEquals(message, ShadowToast.getTextOfLatestToast()) val toast = ShadowToast.getLatestToast() Assert.assertEquals(length.toLong(), toast.duration.toLong()) Assert.assertEquals((Gravity.BOTTOM or Gravity.CENTER_VERTICAL).toLong(), toast.gravity.toLong()) Assert.assertEquals(0, toast.xOffset.toLong()) Assert.assertEquals( context.resources.getDimensionPixelSize(R.dimen.tb_toast_y_offset).toLong(), toast.yOffset .toLong()) } @Test fun testCancel() { impl.show() val toast = Shadows.shadowOf(ShadowToast.getLatestToast()) Assert.assertFalse(toast.isCancelled) impl.cancel() Assert.assertTrue(toast.isCancelled) } }
apache-2.0
bd363995c1d186f70c2dd2f6d0ce407d
31.403846
92
0.70089
4.641873
false
true
false
false
allotria/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/strategy/StrategyUtils.kt
2
6601
// Copyright 2000-2019 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.grazie.grammar.strategy import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy.TextDomain import com.intellij.grazie.ide.language.LanguageGrammarChecking import com.intellij.grazie.utils.LinkedSet import com.intellij.grazie.utils.Text import com.intellij.lang.LanguageExtensionPoint import com.intellij.lang.LanguageParserDefinitions import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.util.elementType object StrategyUtils { private val EMPTY_LINKED_SET = LinkedSet<Nothing>() @Suppress("UNCHECKED_CAST") internal fun <T> emptyLinkedSet(): LinkedSet<T> = EMPTY_LINKED_SET as LinkedSet<T> /** * Get extension point of [strategy] * * @return extension point */ internal fun getStrategyExtensionPoint(strategy: GrammarCheckingStrategy): LanguageExtensionPoint<GrammarCheckingStrategy> { return LanguageGrammarChecking.getExtensionPointByStrategy(strategy) ?: error("Strategy is not registered") } internal fun getTextDomainOrDefault(strategy: GrammarCheckingStrategy, root: PsiElement, default: TextDomain): TextDomain { val extension = getStrategyExtensionPoint(strategy) if (extension.language != root.language.id) return default val parser = LanguageParserDefinitions.INSTANCE.forLanguage(root.language) ?: return default return when { parser.stringLiteralElements.contains(root.elementType) -> TextDomain.LITERALS parser.commentTokens.contains(root.elementType) -> TextDomain.COMMENTS else -> default } } /** * Delete leading and trailing quotes with spaces * * @return deleted leading offset */ internal fun trimLeadingQuotesAndSpaces(str: StringBuilder): Int = with(str) { var offset = quotesOffset(this) setLength(length - offset) // remove closing quotes and whitespaces while (isNotEmpty() && get(length - 1).isWhitespace()) deleteCharAt(length - 1) while (offset < length && get(offset).isWhitespace()) offset++ repeat(offset) { deleteCharAt(0) } // remove opening quotes and whitespace return offset } /** * Convert double spaces into one after removing absorb/stealth elements * * @param position position in StringBuilder * @return true if deleted */ internal fun deleteRedundantSpace(str: StringBuilder, position: Int): Boolean = with(str) { if (position in 1 until length) { if (get(position - 1) == ' ' && (Text.isPunctuation(get(position)) || get(position) == ' ')) { deleteCharAt(position - 1) return true } } return false } /** * Finds indent indexes for each line (indent of specific [chars]) * NOTE: If you use this method in [GrammarCheckingStrategy.getStealthyRanges], * make sure that [GrammarCheckingStrategy.getReplaceCharRules] doesn't contain a [ReplaceNewLines] rule! * * @param str source text * @param chars characters, which considered as indentation * @return list of IntRanges for such indents */ fun indentIndexes(str: CharSequence, chars: Set<Char>): LinkedSet<IntRange> { val result = LinkedSet<IntRange>() var from = -1 for ((index, char) in str.withIndex()) { if ((Text.isNewline(char) || (index == 0 && char in chars)) && from == -1) { // for first line without \n from = index + if (Text.isNewline(char)) 1 else 0 } else { if (from != -1) { if (char !in chars) { if (index > from) result.add(IntRange(from, index - 1)) from = if (Text.isNewline(char)) index + 1 else -1 } } } } if (from != -1) result.add(IntRange(from, str.length - 1)) return result } /** * Get all siblings of [element] of specific [types] * which are no further than one line * * @param element element whose siblings are to be found * @param types possible types of siblings * @return sequence of siblings with whitespace tokens */ fun getNotSoDistantSiblingsOfTypes(strategy: GrammarCheckingStrategy, element: PsiElement, types: Set<IElementType>) = getNotSoDistantSiblingsOfTypes(strategy, element) { type -> type in types } /** * Get all siblings of [element] of type accepted by [checkType] * which are no further than one line * * @param element element whose siblings are to be found * @param checkType predicate to check if type is accepted * @return sequence of siblings with whitespace tokens */ fun getNotSoDistantSiblingsOfTypes(strategy: GrammarCheckingStrategy, element: PsiElement, checkType: (IElementType?) -> Boolean) = getNotSoDistantSimilarSiblings(strategy, element) { sibling -> checkType(sibling.elementType) } /** * Get all siblings of [element] that are accepted by [checkSibling] * which are no further than one line * * @param element element whose siblings are to be found * @param checkSibling predicate to check if sibling is accepted * @return sequence of siblings with whitespace tokens */ fun getNotSoDistantSimilarSiblings(strategy: GrammarCheckingStrategy, element: PsiElement, checkSibling: (PsiElement?) -> Boolean) = sequence { fun PsiElement.process(checkSibling: (PsiElement?) -> Boolean, next: Boolean) = sequence<PsiElement> { val whitespaceTokens = strategy.getWhiteSpaceTokens() var newLinesBetweenSiblingsCount = 0 var sibling: PsiElement? = this@process while (sibling != null) { val candidate = if (next) sibling.nextSibling else sibling.prevSibling val type = candidate.elementType sibling = when { checkSibling(candidate) -> { newLinesBetweenSiblingsCount = 0 candidate } type in whitespaceTokens -> { newLinesBetweenSiblingsCount += candidate.text.count { char -> char == '\n' } if (newLinesBetweenSiblingsCount > 1) null else candidate } else -> null } if (sibling != null) yield(sibling) } } yieldAll(element.process(checkSibling, false).toList().asReversed()) yield(element) yieldAll(element.process(checkSibling, true)) } private fun quotesOffset(str: CharSequence): Int { var index = 0 while (index < str.length / 2) { if (str[index] != str[str.length - index - 1] || !Text.isQuote(str[index])) { return index } index++ } return index } }
apache-2.0
9548f2ae437650f8d7d46bcffc970479
35.672222
140
0.688381
4.331365
false
false
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GrAnnotatorImpl.kt
1
2978
// Copyright 2000-2019 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.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.roots.FileIndexFacade import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.codeInspection.type.GroovyStaticTypeCheckVisitor import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.psi.util.isFake class GrAnnotatorImpl : Annotator { private val myTypeCheckVisitor = GroovyStaticTypeCheckVisitor() override fun annotate(element: PsiElement, holder: AnnotationHolder) { val file = holder.currentAnnotationSession.file if (FileIndexFacade.getInstance(file.project).isInLibrarySource(file.virtualFile)) { return } if (element is GroovyPsiElement) { element.accept(GroovyAnnotator(holder)) if (PsiUtil.isCompileStatic(element)) { myTypeCheckVisitor.accept(element, holder) } } else if (element is PsiComment) { val text = element.getText() if (text.startsWith("/*") && !text.endsWith("*/")) { val range = element.getTextRange() holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("doc.end.expected")).range( TextRange.create(range.endOffset - 1, range.endOffset)).create() } } else { val parent = element.parent if (parent is GrMethod && element == parent.nameIdentifierGroovy) { val illegalCharacters = illegalJvmNameSymbols.findAll(parent.name).mapTo(HashSet()) { it.value } if (illegalCharacters.isNotEmpty() && !parent.isFake()) { val chars = illegalCharacters.joinToString { "'$it'" } holder.newAnnotation(HighlightSeverity.WARNING, GroovyBundle.message("illegal.method.name", chars)).create() } if (parent.returnTypeElementGroovy == null) { GroovyAnnotator.checkMethodReturnType(parent, element, holder) } } else if (parent is GrField) { if (element == parent.nameIdentifierGroovy) { val getters = parent.getters for (getter in getters) { GroovyAnnotator.checkMethodReturnType(getter, parent.nameIdentifierGroovy, holder) } val setter = parent.setter if (setter != null) { GroovyAnnotator.checkMethodReturnType(setter, parent.nameIdentifierGroovy, holder) } } } } } }
apache-2.0
17db10218f07071e92cba958a5617cfa
42.15942
140
0.718267
4.471471
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/ignore/GitIgnoredFileContentProvider.kt
1
7331
// 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 git4idea.ignore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.NotIgnored import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsKey import com.intellij.openapi.vcs.actions.VcsContextFactory import com.intellij.openapi.vcs.changes.IgnoreSettingsType.* import com.intellij.openapi.vcs.changes.IgnoredFileContentProvider import com.intellij.openapi.vcs.changes.IgnoredFileDescriptor import com.intellij.openapi.vcs.changes.IgnoredFileProvider import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.project.stateStore import com.intellij.vcsUtil.VcsUtil import git4idea.GitUtil import git4idea.GitVcs import git4idea.repo.GitRepositoryFiles.GITIGNORE import git4idea.repo.GitRepositoryManager import java.io.File import java.lang.System.lineSeparator private val LOG = logger<GitIgnoredFileContentProvider>() open class GitIgnoredFileContentProvider(private val project: Project) : IgnoredFileContentProvider { private val gitIgnoreChecker = GitIgnoreChecker(project) override fun getSupportedVcs(): VcsKey = GitVcs.getKey() override fun getFileName() = GITIGNORE override fun buildIgnoreFileContent(ignoreFileRoot: VirtualFile, ignoredFileProviders: Array<IgnoredFileProvider>): String { if (!GitUtil.isUnderGit(ignoreFileRoot)) return "" //if ignore file root not under git --> return (e.g. in case if .git folder was deleted externally) val ignoreFileVcsRoot = VcsUtil.getVcsRootFor(project, ignoreFileRoot) ?: return "" val content = StringBuilder() val lineSeparator = lineSeparator() val untrackedFiles = getUntrackedFiles(ignoreFileVcsRoot) if (untrackedFiles.isEmpty()) return "" //if there is no untracked files this mean nothing to ignore for (provider in ignoredFileProviders) { val ignoredFiles = provider.getIgnoredFiles(project).ignoreBeansToRelativePaths(ignoreFileVcsRoot, ignoreFileRoot, untrackedFiles) if (ignoredFiles.isEmpty()) continue if (content.isNotEmpty()) { content.append(lineSeparator).append(lineSeparator) } val description = provider.ignoredGroupDescription if (description.isNotBlank()) { content.append(buildIgnoreGroupDescription(provider)) content.append(lineSeparator) } content.append(ignoredFiles.joinToString(lineSeparator)) } return content.toString() } private fun getUntrackedFiles(ignoreFileVcsRoot: VirtualFile): Set<FilePath> { try { val repo = GitRepositoryManager.getInstance(project).getRepositoryForRoot(ignoreFileVcsRoot) ?: return emptySet() return repo.untrackedFilesHolder.retrieveUntrackedFilePaths().toSet() } catch (e: VcsException) { LOG.warn("Cannot get untracked files: ", e) return emptySet() } } private fun Iterable<IgnoredFileDescriptor>.ignoreBeansToRelativePaths(ignoreFileVcsRoot: VirtualFile, ignoreFileRoot: VirtualFile, untrackedFiles: Set<FilePath>): List<String> { val vcsContextFactory = VcsContextFactory.SERVICE.getInstance() return filter { ignoredBean -> when (ignoredBean.type) { UNDER_DIR -> shouldIgnoreUnderDir(ignoredBean, untrackedFiles, ignoreFileRoot, ignoreFileVcsRoot, vcsContextFactory) FILE -> shouldIgnoreFile(ignoredBean, untrackedFiles, ignoreFileRoot, ignoreFileVcsRoot, vcsContextFactory) MASK -> shouldIgnoreByMask(ignoredBean, untrackedFiles) } }.map { ignoredBean -> when (ignoredBean.type) { MASK -> ignoredBean.mask!! UNDER_DIR -> buildIgnoreEntryContent(ignoreFileRoot, ignoredBean) FILE -> buildIgnoreEntryContent(ignoreFileRoot, ignoredBean) } } } private fun shouldIgnoreUnderDir(ignoredBean: IgnoredFileDescriptor, untrackedFiles: Set<FilePath>, ignoreFileRoot: VirtualFile, ignoreFileVcsRoot: VirtualFile, vcsContextFactory: VcsContextFactory) = FileUtil.exists(ignoredBean.path) && untrackedFiles.any { FileUtil.isAncestor(ignoredBean.path!!, it.path, true) } && FileUtil.isAncestor(ignoreFileRoot.path, ignoredBean.path!!, false) && Comparing.equal(ignoreFileVcsRoot, VcsUtil.getVcsRootFor(project, vcsContextFactory.createFilePath(ignoredBean.path!!, true))) && gitIgnoreChecker.isIgnored(ignoreFileVcsRoot, File(ignoredBean.path!!)) is NotIgnored && shouldNotConsiderInternalIgnoreFile(ignoredBean, ignoreFileRoot) private fun shouldIgnoreFile(ignoredBean: IgnoredFileDescriptor, untrackedFiles: Set<FilePath>, ignoreFileRoot: VirtualFile, ignoreFileVcsRoot: VirtualFile, vcsContextFactory: VcsContextFactory) = FileUtil.exists(ignoredBean.path) && untrackedFiles.any { ignoredBean.matchesFile(it) } && FileUtil.isAncestor(ignoreFileRoot.path, ignoredBean.path!!, false) && Comparing.equal(ignoreFileVcsRoot, VcsUtil.getVcsRootFor(project, vcsContextFactory.createFilePath(ignoredBean.path!!, false))) && shouldNotConsiderInternalIgnoreFile(ignoredBean, ignoreFileRoot) private fun shouldIgnoreByMask(ignoredBean: IgnoredFileDescriptor, untrackedFiles: Set<FilePath>) = untrackedFiles.any { ignoredBean.matchesFile(it) } private fun shouldNotConsiderInternalIgnoreFile(ignoredBean: IgnoredFileDescriptor, ignoreFileRoot: VirtualFile): Boolean { val insideDirectoryStore = ignoredBean.path?.contains(Project.DIRECTORY_STORE_FOLDER) ?: false if (insideDirectoryStore) { val directoryStoreOrProjectFileLocation = project.stateStore.directoryStoreFile ?: project.projectFile?.parent ?: return false return FileUtil.isAncestor(VfsUtilCore.virtualToIoFile(directoryStoreOrProjectFileLocation), VfsUtilCore.virtualToIoFile(ignoreFileRoot), false) } return true } override fun buildUnignoreContent(ignorePattern: String) = StringBuilder().apply { append(lineSeparator()) append("!$ignorePattern") }.toString() override fun buildIgnoreGroupDescription(ignoredFileProvider: IgnoredFileProvider) = prependCommentHashCharacterIfNeeded(ignoredFileProvider.ignoredGroupDescription) override fun buildIgnoreEntryContent(ignoreEntryRoot: VirtualFile, ignoredFileDescriptor: IgnoredFileDescriptor) = "/${FileUtil.getRelativePath(ignoreEntryRoot.path, ignoredFileDescriptor.path!!, '/') ?: ""}" private fun prependCommentHashCharacterIfNeeded(description: String): String = if (description.startsWith("#")) description else "# $description" /** * Disable creating a new .idea/.gitignore for [com.intellij.openapi.vcs.changes.ignore.IgnoreFilesProcessorImpl]. * This ignore file will be generated automatically by [GitIgnoreInStoreDirGenerator] */ override fun canCreateIgnoreFileInStateStoreDir() = false }
apache-2.0
ade9c2cd1a6e685cfccc8dfd94d584c0
48.201342
180
0.75133
4.997273
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/conf/Props.kt
1
3410
package slatekit.common.conf import slatekit.common.io.Alias import slatekit.common.io.Uri import slatekit.common.io.Uris import java.io.FileInputStream import java.util.* object Props { /** * Loads the typesafe config from the filename can be prefixed with a uri to indicate location, * such as: * 1. "jars://" to indicate loading from resources directory inside jar * 2. "user://" to indicate loading from user.home directory * 3. "file://" to indicate loading from file system * * e.g. * - jars://env.qa.conf * - user://${company.dir}/${group.dir}/${app.id}/conf/env.qa.conf * - file://c:/slatekit/${company.dir}/${group.dir}/${app.id}/conf/env.qa.conf * - file://./conf/env.qa.conf * * @param path : name of file e.g. email.conf * @return */ fun fromPath(cls:Class<*>, path: String?): Pair<Uri, Properties> { return when(path) { null, "" -> { val name = Confs.CONFIG_DEFAULT_PROPERTIES val uri = Uri.jar(name) val props = fromJar(cls, name) Pair(uri, props) } else -> { val uri = Uris.parse(path) val props = fromUri(cls, uri) Pair(uri, props) } } } /** * Loads properties from the Slate Kit Uri supplied which handles aliases * * ALIASES: * abs://usr/local/myapp/settings.conf -> /usr/local/myapp/settings.conf * usr://myapp/settings.conf -> ~/myapp/settings.conf * tmp://myapp/settings.conf -> ~/temp/myapp/settings.conf * cfg://settings.conf -> ./conf/settings */ fun fromUri(cls:Class<*>, uri: Uri):Properties { val props = when(uri.root) { is Alias.Jar -> fromJar(cls,uri.path ?: Confs.CONFIG_DEFAULT_PROPERTIES) is Alias.Other -> fromJar(cls,uri.path ?: Confs.CONFIG_DEFAULT_PROPERTIES) else -> fromFileRaw(uri.toFile().absolutePath) } return props } /** * Loads properties from the file / path supplied with handling for Slate Kit Aliases * @param cls: The Class load the resource from * @param path: The path to the file e.g. env.conf or /folder1/settings.conf */ fun fromJar(cls:Class<*>, path: String): Properties { // This is here to debug loading app conf val input = cls.getResourceAsStream("/" + path) val conf = Properties() conf.load(input) return conf } /** * Loads properties from the file / path supplied with handling for Slate Kit Aliases * * ALIASES: * abs://usr/local/myapp/settings.conf -> /usr/local/myapp/settings.conf * usr://myapp/settings.conf -> ~/myapp/settings.conf * tmp://myapp/settings.conf -> ~/temp/myapp/settings.conf * cfg://settings.conf -> ./conf/settings */ fun fromFile(fileName: String): Properties { val uri = Uris.parse(fileName) val path = uri.toFile().absolutePath return fromFileRaw(path) } private fun fromFileRaw(path: String): Properties { // This is here to debug loading app conf val input = FileInputStream(path) val conf = Properties() conf.load(input) return conf } }
apache-2.0
7f4b2ba71a39a765d90ce5d9d2457ef4
33.806122
99
0.571261
4.064362
false
false
false
false
chromeos/video-composition-sample
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/media/encoder/MediaEncoder.kt
1
4721
/* * 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 * * 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 dev.chromeos.videocompositionsample.presentation.media.encoder import android.content.Context import android.media.MediaMuxer import android.opengl.EGLContext import android.os.Handler import android.os.Looper import dev.chromeos.videocompositionsample.presentation.media.encoder.utils.VideoMimeType import dev.chromeos.videocompositionsample.presentation.opengl.EncoderFrameData import dev.chromeos.videocompositionsample.presentation.opengl.GlMediaData import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.io.File import java.io.IOException import java.util.concurrent.TimeUnit class MediaEncoder(private val onStopped: () -> Unit) { companion object { private const val OUTPUT_FORMAT = MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4 } enum class MediaType(val muxerChannelsCount: Int) { VideoAndAudio(2), OnlyVideo(1) } private lateinit var muxer: Muxer private var onError: ((e: Exception) -> Unit)? = null private val videoRecorder = VideoEncoder() private val audioRecorder = AudioEncoder() private var mediaType = MediaType.VideoAndAudio private var isRecording = false private var mainThreadHandler: Handler = Handler(Looper.getMainLooper()) fun start( context: Context, eglContext: EGLContext, outputFile: File, width: Int, height: Int, videoMimeType: VideoMimeType, encodeSpeedFactor: Float, glMediaData: GlMediaData, onError: (e: Exception) -> Unit ) { if (isRecording) return try { this.onError = onError muxer = Muxer(outputFile, OUTPUT_FORMAT, mediaType.muxerChannelsCount) isRecording = true videoRecorder.startRecording(context, eglContext, width, height, videoMimeType, encodeSpeedFactor, glMediaData, muxer, onError) if (mediaType == MediaType.VideoAndAudio) { audioRecorder.startRecording(glMediaData, muxer, encodeSpeedFactor, onError) } } catch (e: IOException) { stop() throw IllegalStateException("Error start Recorder", e) } } fun notifyStartMediaTrack(index: Int) { if (mediaType == MediaType.VideoAndAudio) { audioRecorder.notifyStartMediaTrack(index) } } fun notifyPauseMediaTrack(index: Int) { if (mediaType == MediaType.VideoAndAudio) { audioRecorder.notifyPauseMediaTrack(index) } } fun frameAvailable(encoderFrameData: EncoderFrameData) { videoRecorder.frameAvailable(encoderFrameData) } fun updateSharedContext(width: Int, height: Int, sharedContext: EGLContext) { videoRecorder.updateSharedContext(width, height, sharedContext) } fun stop() { videoRecorder.stopRecording() if (mediaType == MediaType.VideoAndAudio) { audioRecorder.stopRecording() } releaseMuxer() } private fun releaseMuxer() { Observable.interval(50, TimeUnit.MILLISECONDS) .take(10) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext { if (isRecording && !videoRecorder.isRecording && !audioRecorder.isRecording) { muxer.release() isRecording = false } } .doFinally { if (isRecording) { try { muxer.release() } catch (e: Exception) { mainThreadHandler.post { onError?.invoke(e) } } finally { isRecording = false } } onStopped.invoke() } .subscribe() } }
apache-2.0
d7f45cee5ad961883988ce7e89cc5f19
32.489362
139
0.617878
4.959034
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/util/HProfReadBufferSlidingWindow.kt
6
3476
/* * Copyright (C) 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 com.intellij.diagnostic.hprof.util import com.intellij.diagnostic.hprof.parser.HProfEventBasedParser import com.intellij.util.io.ByteBufferUtil import java.nio.ByteBuffer import java.nio.channels.FileChannel class HProfReadBufferSlidingWindow(private val channel: FileChannel, parser: HProfEventBasedParser) : AbstractHProfNavigatorReadBuffer(parser) { private val bufferSize = 10_000_000L private val size = channel.size() private var buffer: ByteBuffer private var bufferOffset = 0L init { buffer = channel.map(FileChannel.MapMode.READ_ONLY, bufferOffset, Math.min(bufferSize, size)) } override fun close() { ByteBufferUtil.cleanBuffer(buffer) } override fun position(newPosition: Long) { if (newPosition >= bufferOffset && newPosition <= bufferOffset + bufferSize) { buffer.position((newPosition - bufferOffset).toInt()) } else { remapBuffer(newPosition) } } private fun remapBuffer(newPosition: Long) { val oldBuffer = buffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, newPosition, Math.min(bufferSize, size - newPosition)) bufferOffset = newPosition // Force clean up previous buffer ByteBufferUtil.cleanBuffer(oldBuffer) } override fun isEof(): Boolean { return position() == size } override fun position(): Long { return bufferOffset + buffer.position() } override fun get(bytes: ByteArray) { if (bytes.size <= buffer.remaining()) { buffer.get(bytes) } else { var remaining = bytes.size var offset = 0 while (remaining > 0) { remapBuffer(position()) val bytesToFetch = Math.min(remaining, bufferSize.toInt()) buffer.get(bytes, offset, bytesToFetch) remaining -= bytesToFetch offset += bytesToFetch } } } override fun getByteBuffer(size: Int): ByteBuffer { var useSlice = false if (size < buffer.remaining()) { useSlice = true } else if (size < bufferSize) { remapBuffer(position()) useSlice = true } if (useSlice) { val slicedBuffer = buffer.slice() slicedBuffer.limit(size) skip(size) return slicedBuffer.asReadOnlyBuffer() } else { val bytes = ByteArray(size) get(bytes) return ByteBuffer.wrap(bytes) } } override fun get(): Byte { if (buffer.remaining() < 1) { remapBuffer(position()) } return buffer.get() } override fun getShort(): Short { if (buffer.remaining() < 2) { remapBuffer(position()) } return buffer.short } override fun getInt(): Int { if (buffer.remaining() < 4) { remapBuffer(position()) } return buffer.int } override fun getLong(): Long { if (buffer.remaining() < 8) { remapBuffer(position()) } return buffer.long } }
apache-2.0
462da066090c68914a1f9b03397cf893
24.947761
110
0.66916
4.147971
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/uast/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiVariable.kt
2
7319
// 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.kotlin.psi import com.intellij.psi.* import com.intellij.psi.impl.light.LightTypeElement import org.jetbrains.kotlin.asJava.elements.LightVariableBuilder import org.jetbrains.kotlin.builtins.createFunctionType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.types.isError import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.analyze import org.jetbrains.uast.kotlin.lz import org.jetbrains.uast.kotlin.orAnonymous import org.jetbrains.uast.kotlin.toPsiType class UastKotlinPsiVariable private constructor( manager: PsiManager, name: String, typeProducer: () -> PsiType, val ktInitializer: KtExpression?, psiParentProducer: () -> PsiElement?, val containingElement: UElement, val ktElement: KtElement ) : LightVariableBuilder( manager, name, UastErrorType, // Type is calculated lazily KotlinLanguage.INSTANCE ), PsiLocalVariable { val psiParent by lz(psiParentProducer) private val psiType: PsiType by lz(typeProducer) private val psiTypeElement: PsiTypeElement by lz { LightTypeElement(manager, psiType) } private val psiInitializer: PsiExpression? by lz { ktInitializer?.let { KotlinUastPsiExpression(it, containingElement) } } override fun getType(): PsiType = psiType override fun getText(): String = ktElement.text override fun getParent() = psiParent override fun hasInitializer() = ktInitializer != null override fun getInitializer(): PsiExpression? = psiInitializer override fun getTypeElement() = psiTypeElement override fun setInitializer(initializer: PsiExpression?) = throw NotImplementedError() override fun getContainingFile(): PsiFile? = ktElement.containingFile override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other::class.java != this::class.java) return false return ktElement == (other as? UastKotlinPsiVariable)?.ktElement } override fun isEquivalentTo(another: PsiElement?): Boolean = this == another || ktElement.isEquivalentTo(another) override fun hashCode() = ktElement.hashCode() companion object { fun create( declaration: KtVariableDeclaration, parent: PsiElement?, containingElement: KotlinUDeclarationsExpression, initializer: KtExpression? = null ): PsiLocalVariable { val psi = containingElement.psiAnchor ?: containingElement.sourcePsi val psiParent = psi?.getNonStrictParentOfType<KtDeclaration>() ?: parent val initializerExpression = initializer ?: declaration.initializer return UastKotlinPsiVariable( manager = declaration.manager, name = declaration.name.orAnonymous("<unnamed>"), typeProducer = { declaration.getType(containingElement) ?: UastErrorType }, ktInitializer = initializerExpression, psiParentProducer = { psiParent }, containingElement = containingElement, ktElement = declaration) } fun create(declaration: KtDestructuringDeclaration, containingElement: UElement): PsiLocalVariable = UastKotlinPsiVariable( manager = declaration.manager, name = "var" + Integer.toHexString(declaration.getHashCode()), typeProducer = { declaration.getType(containingElement) ?: UastErrorType }, ktInitializer = declaration.initializer, psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: declaration.parent }, containingElement = containingElement, ktElement = declaration ) fun create(initializer: KtExpression, containingElement: UElement, parent: PsiElement): PsiLocalVariable = UastKotlinPsiVariable( manager = initializer.manager, name = "var" + Integer.toHexString(initializer.getHashCode()), typeProducer = { initializer.getType(containingElement) ?: UastErrorType }, ktInitializer = initializer, psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: parent }, containingElement = containingElement, ktElement = initializer ) fun create(name: String, localFunction: KtFunction, containingElement: UElement): PsiLocalVariable = UastKotlinPsiVariable( manager = localFunction.manager, name = name, typeProducer = { localFunction.getFunctionType(containingElement) ?: UastErrorType }, ktInitializer = localFunction, psiParentProducer = { containingElement.getParentOfType<UDeclaration>()?.psi ?: localFunction.parent }, containingElement = containingElement, ktElement = localFunction ) } } private class KotlinUastPsiExpression(val ktExpression: KtExpression, val parent: UElement) : PsiElement by ktExpression, PsiExpression { override fun getType(): PsiType? = ktExpression.getType(parent) } private fun KtFunction.getFunctionType(parent: UElement): PsiType? { val descriptor = analyze()[BindingContext.FUNCTION, this] ?: return null val returnType = descriptor.returnType ?: return null return createFunctionType( builtIns = descriptor.builtIns, annotations = descriptor.annotations, receiverType = descriptor.extensionReceiverParameter?.type, parameterTypes = descriptor.valueParameters.map { it.type }, parameterNames = descriptor.valueParameters.map { it.name }, returnType = returnType ).toPsiType(parent, this, boxed = false) } private fun KtExpression.getType(parent: UElement): PsiType? = analyze()[BindingContext.EXPRESSION_TYPE_INFO, this]?.type?.toPsiType(parent, this, boxed = false) private fun KtDeclaration.getType(parent: UElement): PsiType? { return (analyze()[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? CallableDescriptor) ?.returnType ?.takeIf { !it.isError } ?.toPsiType(parent, this, false) } private fun PsiElement.getHashCode(): Int { var result = 42 result = 41 * result + (containingFile?.name?.hashCode() ?: 0) result = 41 * result + startOffset result = 41 * result + text.hashCode() return result }
apache-2.0
9000c828506b9a0f6b71237b62b4c12a
43.628049
158
0.663205
5.859888
false
false
false
false
Flank/flank
test_runner/src/test/kotlin/ftl/shard/ShardTest.kt
1
8315
package ftl.shard import com.google.common.truth.Truth.assertThat import ftl.api.JUnitTest import ftl.args.AndroidArgs import ftl.args.IArgs import ftl.args.IosArgs import ftl.run.exception.FlankConfigurationError import ftl.test.util.FlankTestRunner import ftl.util.FlankTestMethod import io.mockk.every import io.mockk.mockk import io.mockk.unmockkAll import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import java.nio.file.Paths import kotlin.system.measureTimeMillis @RunWith(FlankTestRunner::class) class ShardTest { @After fun tearDown() = unmockkAll() @Test fun oneTestPerShard() { val reRunTestsToRun = listOfFlankTestMethod("a", "b", "c", "d", "e", "f", "g") val suite = sample() val result = createShardsByShardCount(reRunTestsToRun, suite, mockArgs(100)) assertThat(result.size).isEqualTo(7) result.forEach { assertThat(it.testMethods.size).isEqualTo(1) } } @Test fun sampleTest() { val reRunTestsToRun = listOfFlankTestMethod("a/a", "b/b", "c/c", "d/d", "e/e", "f/f", "g/g") val suite = sample() val result = createShardsByShardCount(reRunTestsToRun, suite, mockArgs(3)) assertThat(result.size).isEqualTo(3) result.forEach { assertThat(it.testMethods).isNotEmpty() } assertThat(result.sumOf { it.time }).isEqualTo(16.5) val testNames = mutableListOf<String>() result.forEach { shard -> shard.testMethods.forEach { testNames.add(it.name) } } testNames.sort() assertThat(testNames).isEqualTo(listOf("a/a", "b/b", "c/c", "d/d", "e/e", "f/f", "g/g")) } @Test fun firstRun() { val testsToRun = listOfFlankTestMethod("a", "b", "c") val result = createShardsByShardCount(testsToRun, JUnitTest.Result(null), mockArgs(2)) assertThat(result.size).isEqualTo(2) assertThat(result.sumOf { it.time }).isEqualTo(3 * DEFAULT_TEST_TIME_SEC) val ordered = result.sortedBy { it.testMethods.size } assertThat(ordered[0].testMethods.size).isEqualTo(1) assertThat(ordered[1].testMethods.size).isEqualTo(2) } @Test fun mixedNewAndOld() { val testsToRun = listOfFlankTestMethod("a/a", "b/b", "c/c", "w", "y", "z") val result = createShardsByShardCount(testsToRun, sample(), mockArgs(4)) assertThat(result.size).isEqualTo(4) assertThat(result.sumOf { it.time }).isEqualTo(7.0 + 3 * DEFAULT_TEST_TIME_SEC) val ordered = result.sortedBy { it.testMethods.size } // Expect a/a, b/b, c/c to be in one shard, and w, y, z to each be in their own shards. assertThat(ordered[0].testMethods.size).isEqualTo(1) assertThat(ordered[1].testMethods.size).isEqualTo(1) assertThat(ordered[2].testMethods.size).isEqualTo(1) assertThat(ordered[3].testMethods.size).isEqualTo(3) } @Test fun `performance calculateShardsByTime`() { val testsToRun = mutableListOf<FlankTestMethod>() repeat(1_000_000) { index -> testsToRun.add(FlankTestMethod("$index/$index")) } val arg = AndroidArgs.loadOrDefault(Paths.get("just-be-here"), null).run { copy(commonArgs = commonArgs.copy(maxTestShards = 4)) } // The test occasionally fails on GH Actions' machines, we need to retry to exclude flakiness val maxAttempts = 5 val maxMs = 5000 var attempt = 0 var ms = Long.MAX_VALUE while (attempt++ < maxAttempts && ms >= maxMs) { ms = measureTimeMillis { createShardsByShardCount(testsToRun, JUnitTest.Result(null), arg) } println("Shards calculated in $ms ms, attempt: $attempt") } assertThat(ms).isLessThan(maxMs) } @Test(expected = FlankConfigurationError::class) fun `createShardsByShardCount throws on forcedShardCount = 0`() { createShardsByShardCount( listOf(), sample(), mockArgs(-1, 7), 0 ) } private fun newSuite(testCases: MutableList<JUnitTest.Case>): JUnitTest.Result { return JUnitTest.Result( mutableListOf( JUnitTest.Suite( "", "3", "0", -1, "0", "0", "12.032", "2019-07-27T08:15:04", "localhost", "matrix-1234_execution-asdf", testCases, null, null, null ) ) ) } private fun shardCountByTime(shardTime: Int): Int { val testsToRun = listOfFlankTestMethod("a/a", "b/b", "c/c") val testCases = mutableListOf( JUnitTest.Case("a", "a", "0.001"), JUnitTest.Case("b", "b", "0.0"), JUnitTest.Case("c", "c", "0.0") ) val oldTestResult = newSuite(testCases) return shardCountByTime( testsToRun, oldTestResult, mockArgs(-1, shardTime) ) } @Test(expected = FlankConfigurationError::class) fun `shardCountByTime throws on invalid shard time -3`() { shardCountByTime(-3) } @Test(expected = FlankConfigurationError::class) fun `shardCountByTime throws on invalid shard time -2`() { shardCountByTime(-2) } @Test(expected = FlankConfigurationError::class) fun `shardCountByTime throws on invalid shard time 0`() { shardCountByTime(0) } @Test fun `shardCountByTime shards valid times`() { assertThat(shardCountByTime(-1)).isEqualTo(-1) assertThat(shardCountByTime(1)).isEqualTo(1) assertThat(shardCountByTime(2)).isEqualTo(1) assertThat(shardCountByTime(3)).isEqualTo(1) } @Test(expected = FlankConfigurationError::class) fun `should terminate with exit status == 3 test targets is 0 and maxTestShards == -1`() { createShardsByShardCount(emptyList(), JUnitTest.Result(mutableListOf()), mockArgs(-1)) } @Test fun `tests annotated with @Ignore should have time 0 and do not hav impact on sharding`() { val androidMockedArgs = mockk<IosArgs>(relaxed = true) every { androidMockedArgs.maxTestShards } returns 2 every { androidMockedArgs.shardTime } returns 10 val testsToRun = listOf( FlankTestMethod("a/a", ignored = true), FlankTestMethod("b/b"), FlankTestMethod("c/c") ) val oldTestResult = newSuite( mutableListOf( JUnitTest.Case("a", "a", "5.0"), JUnitTest.Case("b", "b", "10.0"), JUnitTest.Case("c", "c", "10.0") ) ) val shardCount = shardCountByTime(testsToRun, oldTestResult, androidMockedArgs) assertEquals(2, shardCount) val shards = createShardsByShardCount(testsToRun, oldTestResult, androidMockedArgs, shardCount) assertEquals(2, shards.size) assertTrue(shards.flatMap { it.testMethods }.map { it.time }.filter { it == 0.0 }.count() == 1) shards.forEach { assertEquals(10.0, it.time, 0.0) } } @Test fun `tests annotated with @Ignore should not produce additional shards`() { val androidMockedArgs = mockk<IosArgs>(relaxed = true) every { androidMockedArgs.maxTestShards } returns IArgs.AVAILABLE_PHYSICAL_SHARD_COUNT_RANGE.last every { androidMockedArgs.shardTime } returns -1 val testsToRun = listOf( FlankTestMethod("a/a", ignored = true), FlankTestMethod("b/b", ignored = true), FlankTestMethod("c/c", ignored = true) ) val oldTestResult = newSuite(mutableListOf()) val shardCount = shardCountByTime(testsToRun, oldTestResult, androidMockedArgs) assertEquals(-1, shardCount) val shards = createShardsByShardCount(testsToRun, oldTestResult, androidMockedArgs, shardCount) assertEquals(1, shards.size) } }
apache-2.0
6a52d6971d25a9e0888170701c97e4fd
32.938776
105
0.603848
4.083988
false
true
false
false
Flank/flank
tool/log/format/src/main/kotlin/flank/log/Formatter.kt
1
1054
package flank.log /** * Generic formatter. */ class Formatter<T> internal constructor( val static: Map<StaticMatcher, Format<Any, T>>, val dynamic: Map<DynamicMatcher, Format<Any, T>>, ) internal typealias StaticMatcher = List<Any> internal typealias DynamicMatcher = Any.(Any) -> Boolean internal typealias Format<V, T> = V.(Any) -> T? /** * Format given [Event] into [T]. */ operator fun <T> Formatter<T>.invoke(event: Event<*>): T? = event.run { val format = static[listOf(context, type)] ?: static[listOf(type)] ?: dynamic.toList().firstOrNull { (match, _) -> match.invoke(context, value) }?.second format?.invoke(value, context) } /** * Creates [println] log [Output] from a given [Formatter]. */ val Formatter<String>.output: Output get() = output(::println).filter() /** * Creates [GenericOutput] for [log] using a given [Formatter]. * * Conditionally invoking given [log] with formatted values. */ fun <T> Formatter<T>.output(log: (T) -> Unit): GenericOutput<Event<*>> = { invoke(this)?.let(log) }
apache-2.0
8682a24971536246af39d74001ecfde1
28.277778
99
0.660342
3.513333
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationOnlyHandler2.kt
6
3955
// 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.codeInsight.navigation.actions import com.intellij.codeInsight.CodeInsightActionHandler import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.navigation.CtrlMouseData import com.intellij.codeInsight.navigation.CtrlMouseInfo import com.intellij.codeInsight.navigation.impl.* import com.intellij.codeInsight.navigation.impl.NavigationActionResult.MultipleTargets import com.intellij.codeInsight.navigation.impl.NavigationActionResult.SingleTarget import com.intellij.featureStatistics.FeatureUsageTracker import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.openapi.actionSystem.ex.ActionUtil.underModalProgress import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.ui.list.createTargetPopup internal object GotoDeclarationOnlyHandler2 : CodeInsightActionHandler { override fun startInWriteAction(): Boolean = false private fun gotoDeclaration(project: Project, editor: Editor, file: PsiFile, offset: Int): GTDActionData? { return fromGTDProviders(project, editor, offset) ?: gotoDeclaration(file, offset) } @Suppress("DEPRECATION") @Deprecated("Unused in v2 implementation") fun getCtrlMouseInfo(editor: Editor, file: PsiFile, offset: Int): CtrlMouseInfo? { return gotoDeclaration(file.project, editor, file, offset)?.ctrlMouseInfo() } fun getCtrlMouseData(editor: Editor, file: PsiFile, offset: Int): CtrlMouseData? { return gotoDeclaration(file.project, editor, file, offset)?.ctrlMouseData() } override fun invoke(project: Project, editor: Editor, file: PsiFile) { FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration.only") if (navigateToLookupItem(project)) { return } if (EditorUtil.isCaretInVirtualSpace(editor)) { return } val offset = editor.caretModel.offset val actionResult: NavigationActionResult? = try { underModalProgress(project, CodeInsightBundle.message("progress.title.resolving.reference")) { gotoDeclaration(project, editor, file, offset)?.result() } } catch (e: IndexNotReadyException) { DumbService.getInstance(project).showDumbModeNotification( CodeInsightBundle.message("popup.content.navigation.not.available.during.index.update")) return } if (actionResult == null) { notifyNowhereToGo(project, editor, file, offset) } else { gotoDeclaration(project, editor, actionResult) } } internal fun gotoDeclaration(project: Project, editor: Editor, actionResult: NavigationActionResult) { // obtain event data before showing the popup, // because showing the popup will finish the GotoDeclarationAction#actionPerformed and clear the data val eventData: List<EventPair<*>> = GotoDeclarationAction.getCurrentEventData() when (actionResult) { is SingleTarget -> { actionResult.navigationProvider?.let { GTDUCollector.recordNavigated(eventData, it.javaClass) } navigateRequest(project, actionResult.request) } is MultipleTargets -> { val popup = createTargetPopup( CodeInsightBundle.message("declaration.navigation.title"), actionResult.targets, LazyTargetWithPresentation::presentation ) { (requestor, _, navigationProvider) -> navigationProvider?.let { GTDUCollector.recordNavigated(eventData, navigationProvider.javaClass) } navigateRequestLazy(project, requestor) } popup.showInBestPositionFor(editor) } } } }
apache-2.0
90648613e737d09c7956f453e0fd26e1
40.631579
120
0.752212
4.852761
false
false
false
false
jwren/intellij-community
platform/platform-api/src/com/intellij/openapi/observable/util/ListenerUiUtil.kt
2
9257
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ListenerUiUtil") @file:Suppress("unused") package com.intellij.openapi.observable.util import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeLater import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.Disposer import com.intellij.ui.DocumentAdapter import com.intellij.ui.PopupMenuListenerAdapter import com.intellij.ui.components.DropDownLink import com.intellij.ui.table.TableView import com.intellij.util.ui.TableViewModel import com.intellij.util.ui.tree.TreeModelAdapter import org.jetbrains.annotations.ApiStatus.Experimental import org.jetbrains.annotations.ApiStatus.Internal import java.awt.Component import java.awt.ItemSelectable import java.awt.event.* import javax.swing.* import javax.swing.event.* import javax.swing.text.Document import javax.swing.text.JTextComponent import javax.swing.tree.TreeModel fun <T> JComboBox<T>.whenItemSelected(parentDisposable: Disposable? = null, listener: (T) -> Unit) { (this as ItemSelectable).whenItemSelected(parentDisposable, listener) } fun <T> DropDownLink<T>.whenItemSelected(parentDisposable: Disposable? = null, listener: (T) -> Unit) { (this as ItemSelectable).whenItemSelected(parentDisposable, listener) } fun <T> ItemSelectable.whenItemSelected(parentDisposable: Disposable? = null, listener: (T) -> Unit) { whenStateChanged(parentDisposable) { event -> if (event.stateChange == ItemEvent.SELECTED) { @Suppress("UNCHECKED_CAST") listener(event.item as T) } } } fun ItemSelectable.whenStateChanged(parentDisposable: Disposable? = null, listener: (ItemEvent) -> Unit) { addItemListener(parentDisposable, ItemListener { event -> listener(event) }) } fun JComboBox<*>.whenPopupMenuWillBecomeInvisible(parentDisposable: Disposable? = null, listener: (PopupMenuEvent) -> Unit) { addPopupMenuListener(parentDisposable, object : PopupMenuListenerAdapter() { override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent) = listener(e) }) } fun ListModel<*>.whenListChanged(parentDisposable: Disposable? = null, listener: (ListDataEvent) -> Unit) { addListDataListener(parentDisposable, object : ListDataListener { override fun intervalAdded(e: ListDataEvent) = listener(e) override fun intervalRemoved(e: ListDataEvent) = listener(e) override fun contentsChanged(e: ListDataEvent) = listener(e) }) } fun JTree.whenTreeChanged(parentDisposable: Disposable? = null, listener: (TreeModelEvent) -> Unit) { model.whenTreeChanged(parentDisposable, listener) } fun TreeModel.whenTreeChanged(parentDisposable: Disposable? = null, listener: (TreeModelEvent) -> Unit) { addTreeModelListener(parentDisposable, TreeModelAdapter.create { event, _ -> listener(event) }) } fun TableView<*>.whenTableChanged(parentDisposable: Disposable? = null, listener: (TableModelEvent) -> Unit) { tableViewModel.whenTableChanged(parentDisposable, listener) } fun TableViewModel<*>.whenTableChanged(parentDisposable: Disposable? = null, listener: (TableModelEvent) -> Unit) { addTableModelListener(parentDisposable, TableModelListener { event -> listener(event) }) } fun TextFieldWithBrowseButton.whenTextChanged(parentDisposable: Disposable? = null, listener: (DocumentEvent) -> Unit) { textField.whenTextChanged(parentDisposable, listener) } fun JTextComponent.whenTextChanged(parentDisposable: Disposable? = null, listener: (DocumentEvent) -> Unit) { document.whenTextChanged(parentDisposable, listener) } fun Document.whenTextChanged(parentDisposable: Disposable? = null, listener: (DocumentEvent) -> Unit) { addDocumentListener(parentDisposable, object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) = listener(e) }) } fun JTextComponent.whenCaretMoved(parentDisposable: Disposable? = null, listener: (CaretEvent) -> Unit) { addCaretListener(parentDisposable, CaretListener { event -> listener(event) }) } fun Component.whenFocusGained(parentDisposable: Disposable? = null, listener: (FocusEvent) -> Unit) { addFocusListener(parentDisposable, object : FocusAdapter() { override fun focusGained(e: FocusEvent) = listener(e) }) } fun Component.whenFocusLost(parentDisposable: Disposable? = null, listener: (FocusEvent) -> Unit) { addFocusListener(parentDisposable, object : FocusAdapter() { override fun focusLost(e: FocusEvent) = listener(e) }) } fun Component.onceWhenFocusGained(parentDisposable: Disposable? = null, listener: (FocusEvent) -> Unit) { addFocusListener(parentDisposable, object : FocusAdapter() { override fun focusGained(e: FocusEvent) { removeFocusListener(this) listener(e) } }) } fun Component.whenMousePressed(parentDisposable: Disposable? = null, listener: (MouseEvent) -> Unit) { addMouseListener(parentDisposable, object : MouseAdapter() { override fun mousePressed(e: MouseEvent) = listener(e) }) } fun Component.whenMouseReleased(parentDisposable: Disposable? = null, listener: (MouseEvent) -> Unit) { addMouseListener(parentDisposable, object : MouseAdapter() { override fun mouseReleased(e: MouseEvent) = listener(e) }) } fun Component.whenKeyTyped(parentDisposable: Disposable? = null, listener: (KeyEvent) -> Unit) { addKeyListener(parentDisposable, object : KeyAdapter() { override fun keyTyped(e: KeyEvent) = listener(e) }) } fun Component.whenKeyPressed(parentDisposable: Disposable? = null, listener: (KeyEvent) -> Unit) { addKeyListener(parentDisposable, object : KeyAdapter() { override fun keyPressed(e: KeyEvent) = listener(e) }) } fun Component.whenKeyReleased(parentDisposable: Disposable? = null, listener: (KeyEvent) -> Unit) { addKeyListener(parentDisposable, object : KeyAdapter() { override fun keyReleased(e: KeyEvent) = listener(e) }) } fun ItemSelectable.addItemListener(parentDisposable: Disposable? = null, listener: ItemListener) { addItemListener(listener) parentDisposable?.whenDisposed { removeItemListener(listener) } } fun JComboBox<*>.addPopupMenuListener(parentDisposable: Disposable? = null, listener: PopupMenuListener) { addPopupMenuListener(listener) parentDisposable?.whenDisposed { removePopupMenuListener(listener) } } fun ListModel<*>.addListDataListener(parentDisposable: Disposable? = null, listener: ListDataListener) { addListDataListener(listener) parentDisposable?.whenDisposed { removeListDataListener(listener) } } fun TreeModel.addTreeModelListener(parentDisposable: Disposable? = null, listener: TreeModelListener) { addTreeModelListener(listener) parentDisposable?.whenDisposed { removeTreeModelListener(listener) } } fun TableViewModel<*>.addTableModelListener(parentDisposable: Disposable? = null, listener: TableModelListener) { addTableModelListener(listener) parentDisposable?.whenDisposed { removeTableModelListener(listener) } } fun Document.addDocumentListener(parentDisposable: Disposable? = null, listener: DocumentListener) { addDocumentListener(listener) parentDisposable?.whenDisposed { removeDocumentListener(listener) } } fun JTextComponent.addCaretListener(parentDisposable: Disposable? = null, listener: CaretListener) { addCaretListener(listener) parentDisposable?.whenDisposed { removeCaretListener(listener) } } fun Component.addFocusListener(parentDisposable: Disposable? = null, listener: FocusListener) { addFocusListener(listener) parentDisposable?.whenDisposed { removeFocusListener(listener) } } fun Component.addMouseListener(parentDisposable: Disposable? = null, listener: MouseListener) { addMouseListener(listener) parentDisposable?.whenDisposed { removeMouseListener(listener) } } fun Component.addKeyListener(parentDisposable: Disposable? = null, listener: KeyListener) { addKeyListener(listener) parentDisposable?.whenDisposed { removeKeyListener(listener) } } @Internal fun Disposable.whenDisposed(listener: () -> Unit) { Disposer.register(this, Disposable { listener() }) } @Experimental fun <T> JComboBox<T>.whenItemSelectedFromUi(parentDisposable: Disposable? = null, listener: (T) -> Unit) { whenPopupMenuWillBecomeInvisible(parentDisposable) { invokeLater(ModalityState.stateForComponent(this)) { selectedItem?.let { @Suppress("UNCHECKED_CAST") listener(it as T) } } } } @Experimental fun TextFieldWithBrowseButton.whenTextChangedFromUi(parentDisposable: Disposable? = null, listener: (String) -> Unit) { textField.whenTextChangedFromUi(parentDisposable, listener) } @Experimental fun JTextComponent.whenTextChangedFromUi(parentDisposable: Disposable? = null, listener: (String) -> Unit) { whenKeyReleased(parentDisposable) { invokeLater(ModalityState.stateForComponent(this)) { listener(text) } } } @Experimental fun JCheckBox.whenStateChangedFromUi(parentDisposable: Disposable? = null, listener: (Boolean) -> Unit) { whenMouseReleased(parentDisposable) { invokeLater(ModalityState.stateForComponent(this)) { listener(isSelected) } } }
apache-2.0
fa4f9c8f4256303882aa4d5325a3c7cd
33.932075
125
0.766987
4.528865
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/viewinterop/AndroidViewTest.kt
3
28343
/* * Copyright 2020 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.viewinterop import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.os.Build import android.os.Bundle import android.os.Parcelable import android.util.DisplayMetrics import android.util.TypedValue import android.view.LayoutInflater import android.view.SurfaceView import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.SideEffect import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.runtime.setValue import androidx.compose.testutils.assertPixels import androidx.compose.ui.AbsoluteAlignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.input.canScroll import androidx.compose.ui.input.consumeScrollContainerInfo import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.platform.LocalSavedStateRegistryOwner import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.platform.findViewTreeCompositionContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.R import androidx.compose.ui.test.TestActivity import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewTreeLifecycleOwner import androidx.savedstate.SavedStateRegistry import androidx.savedstate.SavedStateRegistryOwner import androidx.savedstate.findViewTreeSavedStateRegistryOwner import androidx.test.espresso.Espresso import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withClassName import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import com.google.common.truth.Truth.assertThat import kotlin.math.roundToInt import org.hamcrest.CoreMatchers.endsWith import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.instanceOf import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) class AndroidViewTest { @get:Rule val rule = createAndroidComposeRule<TestActivity>() @Test fun androidViewWithConstructor() { rule.setContent { AndroidView({ TextView(it).apply { text = "Test" } }) } Espresso .onView(instanceOf(TextView::class.java)) .check(matches(isDisplayed())) } @Test fun androidViewWithResourceTest() { rule.setContent { AndroidView({ LayoutInflater.from(it).inflate(R.layout.test_layout, null) }) } Espresso .onView(instanceOf(RelativeLayout::class.java)) .check(matches(isDisplayed())) } @Test fun androidViewWithViewTest() { lateinit var frameLayout: FrameLayout rule.activityRule.scenario.onActivity { activity -> frameLayout = FrameLayout(activity).apply { layoutParams = ViewGroup.LayoutParams(300, 300) } } rule.setContent { AndroidView({ frameLayout }) } Espresso .onView(equalTo(frameLayout)) .check(matches(isDisplayed())) } @Test fun androidViewWithResourceTest_preservesLayoutParams() { rule.setContent { AndroidView({ LayoutInflater.from(it).inflate(R.layout.test_layout, FrameLayout(it), false) }) } Espresso .onView(withClassName(endsWith("RelativeLayout"))) .check(matches(isDisplayed())) .check { view, exception -> if (view.layoutParams.width != 300.dp.toPx(view.context.resources.displayMetrics)) { throw exception } if (view.layoutParams.height != WRAP_CONTENT) { throw exception } } } @Test fun androidViewProperlyDetached() { lateinit var frameLayout: FrameLayout rule.activityRule.scenario.onActivity { activity -> frameLayout = FrameLayout(activity).apply { layoutParams = ViewGroup.LayoutParams(300, 300) } } var emit by mutableStateOf(true) rule.setContent { if (emit) { AndroidView({ frameLayout }) } } rule.runOnUiThread { assertThat(frameLayout.parent).isNotNull() emit = false } rule.runOnIdle { assertThat(frameLayout.parent).isNull() } } @Test @LargeTest fun androidView_attachedAfterDetached_addsViewBack() { lateinit var root: FrameLayout lateinit var composeView: ComposeView lateinit var viewInsideCompose: View rule.activityRule.scenario.onActivity { activity -> root = FrameLayout(activity) composeView = ComposeView(activity) composeView.setViewCompositionStrategy( ViewCompositionStrategy.DisposeOnLifecycleDestroyed(activity) ) viewInsideCompose = View(activity) activity.setContentView(root) root.addView(composeView) composeView.setContent { AndroidView({ viewInsideCompose }) } } var viewInsideComposeHolder: ViewGroup? = null rule.runOnUiThread { assertThat(viewInsideCompose.parent).isNotNull() viewInsideComposeHolder = viewInsideCompose.parent as ViewGroup root.removeView(composeView) } rule.runOnIdle { // Views don't detach from the parent when the parent is detached assertThat(viewInsideCompose.parent).isNotNull() assertThat(viewInsideComposeHolder?.childCount).isEqualTo(1) root.addView(composeView) } rule.runOnIdle { assertThat(viewInsideCompose.parent).isEqualTo(viewInsideComposeHolder) assertThat(viewInsideComposeHolder?.childCount).isEqualTo(1) } } @Test fun androidViewWithResource_modifierIsApplied() { val size = 20.dp rule.setContent { AndroidView( { LayoutInflater.from(it).inflate(R.layout.test_layout, null) }, Modifier.requiredSize(size) ) } Espresso .onView(instanceOf(RelativeLayout::class.java)) .check(matches(isDisplayed())) .check { view, exception -> val expectedSize = size.toPx(view.context.resources.displayMetrics) if (view.width != expectedSize || view.height != expectedSize) { throw exception } } } @Test fun androidViewWithView_modifierIsApplied() { val size = 20.dp lateinit var frameLayout: FrameLayout rule.activityRule.scenario.onActivity { activity -> frameLayout = FrameLayout(activity) } rule.setContent { AndroidView({ frameLayout }, Modifier.requiredSize(size)) } Espresso .onView(equalTo(frameLayout)) .check(matches(isDisplayed())) .check { view, exception -> val expectedSize = size.toPx(view.context.resources.displayMetrics) if (view.width != expectedSize || view.height != expectedSize) { throw exception } } } @Test @LargeTest @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) fun androidViewWithView_drawModifierIsApplied() { val size = 300 lateinit var frameLayout: FrameLayout rule.activityRule.scenario.onActivity { activity -> frameLayout = FrameLayout(activity).apply { layoutParams = ViewGroup.LayoutParams(size, size) } } rule.setContent { AndroidView({ frameLayout }, Modifier .testTag("view") .background(color = Color.Blue)) } rule.onNodeWithTag("view").captureToImage().assertPixels(IntSize(size, size)) { Color.Blue } } @Test fun androidViewWithResource_modifierIsCorrectlyChanged() { val size = mutableStateOf(20.dp) rule.setContent { AndroidView( { LayoutInflater.from(it).inflate(R.layout.test_layout, null) }, Modifier.requiredSize(size.value) ) } Espresso .onView(instanceOf(RelativeLayout::class.java)) .check(matches(isDisplayed())) .check { view, exception -> val expectedSize = size.value.toPx(view.context.resources.displayMetrics) if (view.width != expectedSize || view.height != expectedSize) { throw exception } } rule.runOnIdle { size.value = 30.dp } Espresso .onView(instanceOf(RelativeLayout::class.java)) .check(matches(isDisplayed())) .check { view, exception -> val expectedSize = size.value.toPx(view.context.resources.displayMetrics) if (view.width != expectedSize || view.height != expectedSize) { throw exception } } } @Test fun androidView_notDetachedFromWindowTwice() { // Should not crash. rule.setContent { Box { AndroidView(::ComposeView) { it.setContent { Box(Modifier) } } } } } @Test fun androidView_updateObservesStateChanges() { var size by mutableStateOf(20) var obtainedSize: IntSize = IntSize.Zero rule.setContent { Box { AndroidView( ::View, Modifier.onGloballyPositioned { obtainedSize = it.size } ) { view -> view.layoutParams = ViewGroup.LayoutParams(size, size) } } } rule.runOnIdle { assertThat(obtainedSize).isEqualTo(IntSize(size, size)) size = 40 } rule.runOnIdle { assertThat(obtainedSize).isEqualTo(IntSize(size, size)) } } @Test fun androidView_propagatesDensity() { rule.setContent { val size = 50.dp val density = Density(3f) val sizeIpx = with(density) { size.roundToPx() } CompositionLocalProvider(LocalDensity provides density) { AndroidView( { FrameLayout(it) }, Modifier .requiredSize(size) .onGloballyPositioned { assertThat(it.size).isEqualTo(IntSize(sizeIpx, sizeIpx)) } ) } } rule.waitForIdle() } @Test fun androidView_propagatesViewTreeCompositionContext() { lateinit var parentComposeView: ComposeView lateinit var compositionChildView: View rule.activityRule.scenario.onActivity { activity -> parentComposeView = ComposeView(activity).apply { setContent { AndroidView(::View) { compositionChildView = it } } activity.setContentView(this) } } rule.runOnIdle { assertThat(compositionChildView.findViewTreeCompositionContext()) .isNotEqualTo(parentComposeView.findViewTreeCompositionContext()) } } @Test fun androidView_propagatesLocalsToComposeViewChildren() { val ambient = compositionLocalOf { "unset" } var childComposedAmbientValue = "uncomposed" rule.setContent { CompositionLocalProvider(ambient provides "setByParent") { AndroidView( factory = { ComposeView(it).apply { setContent { childComposedAmbientValue = ambient.current } } } ) } } rule.runOnIdle { assertThat(childComposedAmbientValue).isEqualTo("setByParent") } } @Test fun androidView_propagatesLayoutDirectionToComposeViewChildren() { var childViewLayoutDirection: Int = Int.MIN_VALUE var childCompositionLayoutDirection: LayoutDirection? = null rule.setContent { CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { AndroidView( factory = { FrameLayout(it).apply { addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> childViewLayoutDirection = layoutDirection } addView( ComposeView(it).apply { // The view hierarchy's layout direction should always override // the ambient layout direction from the parent composition. layoutDirection = android.util.LayoutDirection.LTR setContent { childCompositionLayoutDirection = LocalLayoutDirection.current } }, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) } } ) } } rule.runOnIdle { assertThat(childViewLayoutDirection).isEqualTo(android.util.LayoutDirection.RTL) assertThat(childCompositionLayoutDirection).isEqualTo(LayoutDirection.Ltr) } } @Test fun androidView_propagatesLocalLifecycleOwnerAsViewTreeOwner() { lateinit var parentLifecycleOwner: LifecycleOwner // We don't actually need to ever get the actual lifecycle. val compositionLifecycleOwner = LifecycleOwner { throw UnsupportedOperationException() } var childViewTreeLifecycleOwner: LifecycleOwner? = null rule.setContent { LocalLifecycleOwner.current.also { SideEffect { parentLifecycleOwner = it } } CompositionLocalProvider(LocalLifecycleOwner provides compositionLifecycleOwner) { AndroidView( factory = { object : FrameLayout(it) { override fun onAttachedToWindow() { super.onAttachedToWindow() childViewTreeLifecycleOwner = ViewTreeLifecycleOwner.get(this) } } } ) } } rule.runOnIdle { assertThat(childViewTreeLifecycleOwner).isSameInstanceAs(compositionLifecycleOwner) assertThat(childViewTreeLifecycleOwner).isNotSameInstanceAs(parentLifecycleOwner) } } @Test fun androidView_propagatesLocalSavedStateRegistryOwnerAsViewTreeOwner() { lateinit var parentSavedStateRegistryOwner: SavedStateRegistryOwner val compositionSavedStateRegistryOwner = object : SavedStateRegistryOwner { // We don't actually need to ever get actual instances. override fun getLifecycle(): Lifecycle = throw UnsupportedOperationException() override val savedStateRegistry: SavedStateRegistry get() = throw UnsupportedOperationException() } var childViewTreeSavedStateRegistryOwner: SavedStateRegistryOwner? = null rule.setContent { LocalSavedStateRegistryOwner.current.also { SideEffect { parentSavedStateRegistryOwner = it } } CompositionLocalProvider( LocalSavedStateRegistryOwner provides compositionSavedStateRegistryOwner ) { AndroidView( factory = { object : FrameLayout(it) { override fun onAttachedToWindow() { super.onAttachedToWindow() childViewTreeSavedStateRegistryOwner = findViewTreeSavedStateRegistryOwner() } } } ) } } rule.runOnIdle { assertThat(childViewTreeSavedStateRegistryOwner) .isSameInstanceAs(compositionSavedStateRegistryOwner) assertThat(childViewTreeSavedStateRegistryOwner) .isNotSameInstanceAs(parentSavedStateRegistryOwner) } } @Test fun androidView_runsFactoryExactlyOnce_afterFirstComposition() { var factoryRunCount = 0 rule.setContent { val view = remember { View(rule.activity) } AndroidView({ ++factoryRunCount; view }) } rule.runOnIdle { assertThat(factoryRunCount).isEqualTo(1) } } @Test fun androidView_runsFactoryExactlyOnce_evenWhenFactoryIsChanged() { var factoryRunCount = 0 var first by mutableStateOf(true) rule.setContent { val view = remember { View(rule.activity) } AndroidView( if (first) { { ++factoryRunCount; view } } else { { ++factoryRunCount; view } } ) } rule.runOnIdle { assertThat(factoryRunCount).isEqualTo(1) first = false } rule.runOnIdle { assertThat(factoryRunCount).isEqualTo(1) } } @Ignore @Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) fun androidView_clipsToBounds() { val size = 20 val sizeDp = with(rule.density) { size.toDp() } rule.setContent { Column { Box( Modifier .size(sizeDp) .background(Color.Blue) .testTag("box")) AndroidView(factory = { SurfaceView(it) }) } } rule.onNodeWithTag("box").captureToImage().assertPixels(IntSize(size, size)) { Color.Blue } } @Test fun androidView_restoresState() { var result = "" @Composable fun <T : Any> Navigation( currentScreen: T, modifier: Modifier = Modifier, content: @Composable (T) -> Unit ) { val saveableStateHolder = rememberSaveableStateHolder() Box(modifier) { saveableStateHolder.SaveableStateProvider(currentScreen) { content(currentScreen) } } } var screen by mutableStateOf("screen1") rule.setContent { Navigation(screen) { currentScreen -> if (currentScreen == "screen1") { AndroidView({ StateSavingView( "testKey", "testValue", { restoredValue -> result = restoredValue }, it ) }) } else { Box(Modifier) } } } rule.runOnIdle { screen = "screen2" } rule.runOnIdle { screen = "screen1" } rule.runOnIdle { assertThat(result).isEqualTo("testValue") } } @Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) fun androidView_noClip() { rule.setContent { Box( Modifier .fillMaxSize() .background(Color.White)) { with(LocalDensity.current) { Box( Modifier .requiredSize(150.toDp()) .testTag("box")) { Box( Modifier .size(100.toDp(), 100.toDp()) .align(AbsoluteAlignment.TopLeft) ) { AndroidView(factory = { context -> object : View(context) { init { clipToOutline = false } override fun onDraw(canvas: Canvas) { val paint = Paint() paint.color = Color.Blue.toArgb() paint.style = Paint.Style.FILL canvas.drawRect(0f, 0f, 150f, 150f, paint) } } }) } } } } } rule.onNodeWithTag("box").captureToImage().assertPixels(IntSize(150, 150)) { Color.Blue } } @Test fun scrollableViewGroup_propagates_shouldDelay() { val scrollContainerInfo = mutableStateOf({ false }) rule.activityRule.scenario.onActivity { activity -> val parentComposeView = ScrollingViewGroup(activity).apply { addView( ComposeView(activity).apply { setContent { Box(modifier = Modifier.consumeScrollContainerInfo { scrollContainerInfo.value = { it?.canScroll() == true } }) } }) } activity.setContentView(parentComposeView) } rule.runOnIdle { assertThat(scrollContainerInfo.value()).isTrue() } } @Test fun nonScrollableViewGroup_doesNotPropagate_shouldDelay() { val scrollContainerInfo = mutableStateOf({ false }) rule.activityRule.scenario.onActivity { activity -> val parentComposeView = FrameLayout(activity).apply { addView( ComposeView(activity).apply { setContent { Box(modifier = Modifier.consumeScrollContainerInfo { scrollContainerInfo.value = { it?.canScroll() == true } }) } }) } activity.setContentView(parentComposeView) } rule.runOnIdle { assertThat(scrollContainerInfo.value()).isFalse() } } @Test fun viewGroup_propagates_shouldDelayTrue() { lateinit var layout: View rule.setContent { Column(Modifier.verticalScroll(rememberScrollState())) { AndroidView( factory = { layout = LinearLayout(it) layout } ) } } rule.runOnIdle { // View#isInScrollingContainer is hidden, check the parent manually. val shouldDelay = (layout.parent as ViewGroup).shouldDelayChildPressedState() assertThat(shouldDelay).isTrue() } } @Test fun viewGroup_propagates_shouldDelayFalse() { lateinit var layout: View rule.setContent { Column { AndroidView( factory = { layout = LinearLayout(it) layout } ) } } rule.runOnIdle { // View#isInScrollingContainer is hidden, check the parent manually. val shouldDelay = (layout.parent as ViewGroup).shouldDelayChildPressedState() assertThat(shouldDelay).isFalse() } } private class StateSavingView( private val key: String, private val value: String, private val onRestoredValue: (String) -> Unit, context: Context ) : View(context) { init { id = 73 } override fun onSaveInstanceState(): Parcelable { val superState = super.onSaveInstanceState() val bundle = Bundle() bundle.putParcelable("superState", superState) bundle.putString(key, value) return bundle } @Suppress("DEPRECATION") override fun onRestoreInstanceState(state: Parcelable?) { super.onRestoreInstanceState((state as Bundle).getParcelable("superState")) onRestoredValue(state.getString(key)!!) } } private fun Dp.toPx(displayMetrics: DisplayMetrics) = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, value, displayMetrics ).roundToInt() class ScrollingViewGroup(context: Context) : FrameLayout(context) { override fun shouldDelayChildPressedState() = true } }
apache-2.0
538d79c7e98f198c749381f1b137007a
34.252488
100
0.561726
5.837899
false
true
false
false
androidx/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/Shapes.kt
3
3488
/* * 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.material import androidx.compose.foundation.shape.CornerBasedShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Immutable import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.unit.dp /** * <a href="https://material.io/design/shape/about-shape.html" class="external" target="_blank">Material Design shape</a>. * * Material surfaces can be displayed in different shapes. Shapes direct attention, identify * components, communicate state, and express brand. * * ![Shape image](https://developer.android.com/images/reference/androidx/compose/material/shape.png) * * Components are grouped into shape categories based on their size. These categories provide a * way to change multiple component values at once, by changing the category’s values. * Shape categories include: * - Small components * - Medium components * - Large components * * See [Material shape specification](https://material.io/design/shape/applying-shape-to-ui.html) */ @Immutable class Shapes( /** * Shape used by small components like [Button] or [Snackbar]. Components like * [FloatingActionButton], [ExtendedFloatingActionButton] use this shape, but override * the corner size to be 50%. [TextField] uses this shape with overriding the bottom corners * to zero. */ val small: CornerBasedShape = RoundedCornerShape(4.dp), /** * Shape used by medium components like [Card] or [AlertDialog]. */ val medium: CornerBasedShape = RoundedCornerShape(4.dp), /** * Shape used by large components like [ModalDrawer] or [ModalBottomSheetLayout]. */ val large: CornerBasedShape = RoundedCornerShape(0.dp) ) { /** * Returns a copy of this Shapes, optionally overriding some of the values. */ fun copy( small: CornerBasedShape = this.small, medium: CornerBasedShape = this.medium, large: CornerBasedShape = this.large ): Shapes = Shapes( small = small, medium = medium, large = large ) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Shapes) return false if (small != other.small) return false if (medium != other.medium) return false if (large != other.large) return false return true } override fun hashCode(): Int { var result = small.hashCode() result = 31 * result + medium.hashCode() result = 31 * result + large.hashCode() return result } override fun toString(): String { return "Shapes(small=$small, medium=$medium, large=$large)" } } /** * CompositionLocal used to specify the default shapes for the surfaces. */ internal val LocalShapes = staticCompositionLocalOf { Shapes() }
apache-2.0
b7d5969d67da9ee8e754ccb0cb93285b
33.86
122
0.697361
4.390428
false
false
false
false
MoonlightOwl/Yui
src/main/kotlin/totoro/yui/actions/CoinAction.kt
1
3578
package totoro.yui.actions import totoro.yui.client.Command import totoro.yui.client.IRCClient import totoro.yui.util.F import totoro.yui.util.api.CryptoCompare import java.text.DecimalFormat import java.time.Duration class CoinAction : SensitivityAction("coin", "cur", "currency", "btc", "bitcoin", "eth", "ether", "ethereum", "fcn", "fantom", "fantomcoin", "doge", "dogecoin", "neo", "neocoin", "monero", "xmr", "ripple") { private val longFormat = DecimalFormat("0.#####################") private val shortFormat = DecimalFormat("0.###") private fun getCurrencyCodes(args: List<String>): Pair<String?, String?> { val codes = args.filter { !it[0].isDigit() && it[0] != 'p' } return Pair(codes.getOrNull(0), codes.getOrNull(1)) } private fun getDelta(args: List<String>): String? { return args.firstOrNull { it[0] == 'p' } } private fun getAmount(args: List<String>): Double? { args.mapNotNull { it.toDoubleOrNull() }.forEach { return it } return null } private fun formatDelta(delta: Double): String { return "(" + when { delta > 0 -> F.Green + "▴" + F.Reset delta < 0 -> F.Red + "▾" + F.Reset else -> "" } + shortFormat.format(Math.abs(delta)) + "%)" } override fun handle(client: IRCClient, command: Command): Boolean { fun get(from: String, to: String?, range: String?, amount: Double?) { val duration = if (range != null) try { Duration.parse(range.toUpperCase()) } catch (e: Exception) { null } else null val finalAmount = amount ?: 1.0 if (range != null && duration == null) { client.send(command.chan, F.Gray + "try ISO 8601 for time duration" + F.Reset) } else { CryptoCompare.get( from.toUpperCase(), to?.toUpperCase(), duration, { currency -> client.send(command.chan, "$finalAmount ${from.toUpperCase()} -> " + F.Yellow + longFormat.format(currency.price * finalAmount) + F.Reset + " ${currency.code}" + if (currency.description != null) F.Italic + " (${currency.description})" + F.Reset else "" + if (range != null) " " + formatDelta(currency.delta) else "" ) }, { client.send(command.chan, F.Gray + "cannot get the rate for this" + F.Reset) } ) } } val codes = getCurrencyCodes(command.args) val delta = getDelta(command.args) val amount = getAmount(command.args) when (command.name) { "btc", "bitcoin" -> get("BTC", codes.first, delta, amount) "eth", "ether", "ethereum" -> get("ETH", codes.first, delta, amount) "doge", "dogecoin" -> get("DOGE", codes.first, delta, amount) "neo", "neocoin" -> get("NEO", codes.first, delta, amount) "monero", "xmr" -> get("XMR", codes.first, delta, amount) "ripple" -> get("XRP", codes.first, delta, amount) "fcn", "fantom", "fantomcoin" -> get("FCN", codes.first, delta, amount) else -> get(codes.first ?: "BTC", codes.second, delta, amount) } return true } }
mit
e0eaf858f2efc9c86ebc30b3805d3aa3
40.55814
129
0.511192
4.070615
false
false
false
false
GunoH/intellij-community
jvm/jvm-analysis-java-tests/testSrc/com/intellij/codeInspection/tests/java/JavaJavaApiUsageInspectionTest.kt
5
6183
package com.intellij.codeInspection.tests.java import com.intellij.codeInspection.tests.JavaApiUsageInspectionTestBase import com.intellij.codeInspection.tests.ULanguage import com.intellij.pom.java.LanguageLevel /** * This is a base test case for test cases that highlight all the use of API * that were introduced in later language levels comparing to the current language level * * In order to add a new test case: * <ol> * <li>Go to "community/jvm/jvm-analysis-java-tests/testData/codeInspection/apiUsage"</li> * <li>Add a new file(s) to "./src" that contains new API. It's better to define the new API as native methods.</li> * <li>Set <code>JAVA_HOME</code> to jdk 1.8. In this case it's possible to redefine JDK's own classes like <code>String</code> or <code>Class</code></li> * <li>Invoke "./compile.sh". The new class(es) will appear in "./classes"</li> * </ol> */ class JavaJavaApiUsageInspectionTest : JavaApiUsageInspectionTestBase() { fun `test constructor`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_4) myFixture.testHighlighting(ULanguage.JAVA, """ class Constructor { void foo() { throw new <error descr="Usage of API documented as @since 1.5+">IllegalArgumentException</error>("", new RuntimeException()); } } """.trimIndent()) } fun `test ignored`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_6) myFixture.addClass(""" package java.awt.geom; public class GeneralPath { public void moveTo(int x, int y) { } } """.trimIndent()) myFixture.testHighlighting(ULanguage.JAVA, """ import java.awt.geom.GeneralPath; class Ignored { void foo() { GeneralPath path = new GeneralPath(); path.moveTo(0,0); } } """.trimIndent()) } fun `test qualified reference`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_6) myFixture.testHighlighting(ULanguage.JAVA, """ import java.nio.charset.StandardCharsets; import java.nio.charset.Charset; class Main { void foo() { Charset utf = <error descr="Usage of API documented as @since 1.7+">StandardCharsets</error>.UTF_8; } } """.trimIndent()) } fun `test annotation`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_6) myFixture.testHighlighting(ULanguage.JAVA, """ class Annotation { @<error descr="Usage of API documented as @since 1.7+">SafeVarargs</error> public final void a(java.util.List<String>... ls) {} } """.trimIndent()) } fun `test override annotation`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_6) myFixture.testHighlighting(ULanguage.JAVA, """ import java.util.Map; abstract class OverrideAnnotation implements Map<String, String> { @<error descr="Usage of API documented as @since 1.8+">Override</error> public String getOrDefault(Object key, String defaultValue) { return null; } } """.trimIndent()) } fun `test minimum since highlighting`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_7) myFixture.testHighlighting(ULanguage.JAVA, """ import java.util.stream.IntStream; class MinimumSince { void test() { "foo".<error descr="Usage of API documented as @since 1.8+">chars</error>(); } } """.trimIndent()) } fun `test minimum since no higlighting`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_8) myFixture.testHighlighting(ULanguage.JAVA, """ import java.util.stream.IntStream; class MinimumSince { void test() { "foo".chars(); } } """.trimIndent()) } fun `test default methods`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_6) myFixture.testHighlighting(ULanguage.JAVA, """ import java.util.Iterator; class <error descr="Default method 'remove' is not overridden. It would cause compilation problems with JDK 6">DefaultMethods</error> implements Iterator<String> { @Override public boolean hasNext() { return false; } @Override public String next() { return null; } static class T implements Iterator<String> { @Override public boolean hasNext() { return false; } @Override public String next() { return null; } @Override public void remove() {} } { Iterator<String> it = new <error descr="Default method 'remove' is not overridden. It would cause compilation problems with JDK 6">Iterator</error><String>() { @Override public boolean hasNext(){ return false; } @Override public String next(){ return null; } }; } } """.trimIndent()) } fun `test raw inherit from newly generified`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_6) myFixture.addClass(""" package javax.swing; public class AbstractListModel<K> {} """.trimIndent()) myFixture.testHighlighting(ULanguage.JAVA, """ class RawInheritFromNewlyGenerified { private AbstractCCM<String> myModel; } abstract class AbstractCCM<T> extends javax.swing.AbstractListModel { } """.trimIndent()) } fun `test generified`() { myFixture.setLanguageLevel(LanguageLevel.JDK_1_6) myFixture.addClass(""" package javax.swing; public interface ListModel<E> { } """.trimIndent()) myFixture.addClass(""" package javax.swing; public class AbstractListModel<K> implements ListModel<E> { } """.trimIndent()) myFixture.testHighlighting(ULanguage.JAVA, """ import javax.swing.AbstractListModel; abstract class AbstractCCM<T> extends <error descr="Usage of generified after 1.6 API which would cause compilation problems with JDK 6">AbstractListModel<T></error> { } """.trimIndent()) } }
apache-2.0
1dd2a7234988aa5dd8d67c471d67c65c
30.232323
175
0.623807
4.513139
false
true
false
false
JetBrains/xodus
environment/src/test/kotlin/jetbrains/exodus/gc/GarbageCollectorLowCacheTest.kt
1
3206
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * 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 jetbrains.exodus.gc import jetbrains.exodus.bindings.IntegerBinding import jetbrains.exodus.bindings.StringBinding import jetbrains.exodus.env.EnvironmentConfig import jetbrains.exodus.env.EnvironmentTestsBase import jetbrains.exodus.env.StoreConfig import jetbrains.exodus.log.LogConfig import org.junit.Test import java.io.IOException open class GarbageCollectorLowCacheTest : EnvironmentTestsBase() { protected open val config: StoreConfig get() = StoreConfig.WITHOUT_DUPLICATES override fun createEnvironment() { env = newEnvironmentInstance(LogConfig.create(reader, writer), EnvironmentConfig().setMemoryUsage(1).setMemoryUsagePercentage(0)) } @Test @Throws(IOException::class, InterruptedException::class) fun collectExpiredPageWithKeyAddressPointingToDeletedFile() { /** * o. low cache, small file size * 1. create tree IP->BP(N1),BP(N2) * 2. save a lot of updates to last key of BP(N2), * so ther're a lot of files with expired version of BP(N2) and * links to min key of BP(N2), that was saved in a very first file * 3. clean first file, with min key of BP(N2) * 4. clean second file with expired version of BP(N2) and link to min key in removed file */ set1KbFileWithoutGC() env.environmentConfig.treeMaxPageSize = 16 env.environmentConfig.memoryUsage = 0 reopenEnvironment() val store = openStoreAutoCommit("duplicates", config) putAutoCommit(store, IntegerBinding.intToEntry(1), StringBinding.stringToEntry("value1")) putAutoCommit(store, IntegerBinding.intToEntry(2), StringBinding.stringToEntry("value2")) putAutoCommit(store, IntegerBinding.intToEntry(3), StringBinding.stringToEntry("value3")) putAutoCommit(store, IntegerBinding.intToEntry(4), StringBinding.stringToEntry("value4")) putAutoCommit(store, IntegerBinding.intToEntry(5), StringBinding.stringToEntry("value5")) putAutoCommit(store, IntegerBinding.intToEntry(6), StringBinding.stringToEntry("value6")) for (i in 0..999) { putAutoCommit(store, IntegerBinding.intToEntry(6), StringBinding.stringToEntry("value6")) } val log = log val gc = environment.gc val highFileAddress = log.highFileAddress var fileAddress = log.lowAddress while (fileAddress != highFileAddress) { gc.doCleanFile(fileAddress) fileAddress = log.getNextFileAddress(fileAddress) gc.testDeletePendingFiles() } } }
apache-2.0
cb164d768678e28ba1e4a9ba7c1dc54c
40.102564
137
0.710231
4.286096
false
true
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/fragment/SettingFragmentViewModel.kt
1
2962
/* * Copyright (c) 2017. Rei Matsushita * * 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 me.rei_m.hbfavmaterial.viewmodel.widget.fragment import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.databinding.ObservableBoolean import android.databinding.ObservableField import android.view.View import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.PublishSubject import me.rei_m.hbfavmaterial.model.UserModel class SettingFragmentViewModel(userModel: UserModel) : ViewModel() { val userId: ObservableField<String> = ObservableField("") val isAuthorisedHatena: ObservableBoolean = ObservableBoolean(false) val isAuthorisedTwitter: ObservableBoolean = ObservableBoolean(false) private val onClickHatenaAuthStatusEventSubject = PublishSubject.create<Unit>() val onClickHatenaAuthStatus: Observable<Unit> = onClickHatenaAuthStatusEventSubject private var showEditHatenaIdDialogEventSubject = PublishSubject.create<Unit>() val showEditHatenaIdDialogEvent: Observable<Unit> = showEditHatenaIdDialogEventSubject private var startAuthoriseTwitterEventSubject = PublishSubject.create<Unit>() val startAuthoriseTwitterEvent: Observable<Unit> = startAuthoriseTwitterEventSubject private val disposable: CompositeDisposable = CompositeDisposable() init { disposable.addAll(userModel.user.subscribe { userId.set(it.id) }) } override fun onCleared() { disposable.dispose() super.onCleared() } @Suppress("UNUSED_PARAMETER") fun onClickHatenaId(view: View) { showEditHatenaIdDialogEventSubject.onNext(Unit) } @Suppress("UNUSED_PARAMETER") fun onClickHatenaAuthStatus(view: View) { onClickHatenaAuthStatusEventSubject.onNext(Unit) } @Suppress("UNUSED_PARAMETER") fun onClickTwitterAuthStatus(view: View) { startAuthoriseTwitterEventSubject.onNext(Unit) } class Factory(private val userModel: UserModel) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(SettingFragmentViewModel::class.java)) { return SettingFragmentViewModel(userModel) as T } throw IllegalArgumentException("Unknown class name") } } }
apache-2.0
6033c7315a7257a9a51f17ac7e5a9107
36.025
112
0.747806
4.671924
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/MutableCodeToInline.kt
7
4763
// 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.codeInliner import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.psi.BuilderByPattern import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.ImportPath private val POST_INSERTION_ACTION: Key<(KtElement) -> Unit> = Key("POST_INSERTION_ACTION") private val PRE_COMMIT_ACTION: Key<(KtElement) -> Unit> = Key("PRE_COMMIT_ACTION_KEY") internal class MutableCodeToInline( var mainExpression: KtExpression?, val statementsBefore: MutableList<KtExpression>, val fqNamesToImport: MutableCollection<ImportPath>, val alwaysKeepMainExpression: Boolean, var extraComments: CommentHolder?, ) { fun <TElement : KtElement> addPostInsertionAction(element: TElement, action: (TElement) -> Unit) { assert(element in this) @Suppress("UNCHECKED_CAST") element.putCopyableUserData(POST_INSERTION_ACTION, action as (KtElement) -> Unit) } fun <TElement : KtElement> addPreCommitAction(element: TElement, action: (TElement) -> Unit) { @Suppress("UNCHECKED_CAST") element.putCopyableUserData(PRE_COMMIT_ACTION, action as (KtElement) -> Unit) } fun performPostInsertionActions(elements: Collection<PsiElement>) { for (element in elements) { element.forEachDescendantOfType<KtElement> { performAction(it, POST_INSERTION_ACTION) } } } fun addExtraComments(commentHolder: CommentHolder) { extraComments = extraComments?.merge(commentHolder) ?: commentHolder } fun BuilderByPattern<KtExpression>.appendExpressionsFromCodeToInline(postfixForMainExpression: String = "") { for (statement in statementsBefore) { appendExpression(statement) appendFixedText("\n") } if (mainExpression != null) { appendExpression(mainExpression) appendFixedText(postfixForMainExpression) } } fun replaceExpression(oldExpression: KtExpression, newExpression: KtExpression): KtExpression { assert(oldExpression in this) if (oldExpression == mainExpression) { mainExpression = newExpression return newExpression } val index = statementsBefore.indexOf(oldExpression) if (index >= 0) { statementsBefore[index] = newExpression return newExpression } return oldExpression.replace(newExpression) as KtExpression } val expressions: Collection<KtExpression> get() = statementsBefore + listOfNotNull(mainExpression) operator fun contains(element: PsiElement): Boolean = expressions.any { it.isAncestor(element) } } internal fun CodeToInline.toMutable(): MutableCodeToInline = MutableCodeToInline( mainExpression?.copied(), statementsBefore.asSequence().map { it.copied() }.toMutableList(), fqNamesToImport.toMutableSet(), alwaysKeepMainExpression, extraComments, ) private fun performAction(element: KtElement, actionKey: Key<(KtElement) -> Unit>) { val action = element.getCopyableUserData(actionKey) if (action != null) { element.putCopyableUserData(actionKey, null) action.invoke(element) } } private fun performPreCommitActions(expressions: Collection<KtExpression>) = expressions.asSequence() .flatMap { it.collectDescendantsOfType<KtElement> { element -> element.getCopyableUserData(PRE_COMMIT_ACTION) != null } } .sortedWith(compareByDescending(KtElement::startOffset).thenBy(PsiElement::getTextLength)) .forEach { performAction(it, PRE_COMMIT_ACTION) } internal fun MutableCodeToInline.toNonMutable(): CodeToInline { performPreCommitActions(expressions) return CodeToInline( mainExpression, statementsBefore, fqNamesToImport, alwaysKeepMainExpression, extraComments ) } internal inline fun <reified T : PsiElement> MutableCodeToInline.collectDescendantsOfType(noinline predicate: (T) -> Boolean = { true }): List<T> { return expressions.flatMap { it.collectDescendantsOfType({ true }, predicate) } } internal inline fun <reified T : PsiElement> MutableCodeToInline.forEachDescendantOfType(noinline action: (T) -> Unit) { expressions.forEach { it.forEachDescendantOfType(action) } }
apache-2.0
6e869eb14c468a2af01accd30163c5ed
38.040984
147
0.727273
4.910309
false
false
false
false
GunoH/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/tracker/CompletionFileLoggerProvider.kt
4
1508
// 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 com.intellij.stats.completion.tracker import com.intellij.internal.statistic.eventLog.EventLogConfiguration import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.stats.completion.logger.ClientSessionValidator import com.intellij.stats.completion.logger.EventLoggerWithValidation import com.intellij.stats.completion.logger.LogFileManager import java.util.* class CompletionFileLoggerProvider : Disposable, CompletionLoggerProvider() { private val eventLogger = EventLoggerWithValidation(LogFileManager(service()), ClientSessionValidator()) override fun dispose() { eventLogger.dispose() } override fun newCompletionLogger(languageName: String, shouldLogElementFeatures: Boolean): CompletionLogger { val installationUID = service<InstallationIdProvider>().installationId() val completionUID = UUID.randomUUID().toString() val bucket = EventLogConfiguration.getInstance().bucket.toString() return CompletionFileLogger(installationUID.shortedUUID(), completionUID.shortedUUID(), bucket, languageName, shouldLogElementFeatures, eventLogger) } } private fun String.shortedUUID(): String { val start = this.lastIndexOf('-') if (start > 0 && start + 1 < this.length) { return this.substring(start + 1) } return this }
apache-2.0
f7af7137ddf014198922a29b95667ea3
43.382353
158
0.779178
4.772152
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt
1
21294
// 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.rename import com.google.gson.JsonObject import com.google.gson.JsonParser.parseString import com.intellij.codeInsight.TargetElementUtil import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.lang.properties.psi.Property import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileVisitor import com.intellij.psi.* import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.BaseRefactoringProcessor.ConflictsInTestsException import com.intellij.refactoring.rename.* import com.intellij.refactoring.rename.inplace.VariableInplaceRenameHandler import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory import com.intellij.refactoring.util.CommonRefactoringUtil.RefactoringErrorHintException import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.fixtures.CodeInsightTestUtil import org.jetbrains.kotlin.asJava.finder.KtLightPackage import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.findClassAcrossModuleDependencies import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.jsonUtils.getNullableString import org.jetbrains.kotlin.idea.jsonUtils.getString import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.* import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.junit.Assert import java.io.File enum class RenameType { JAVA_CLASS, JAVA_METHOD, KOTLIN_CLASS, KOTLIN_FUNCTION, KOTLIN_PROPERTY, KOTLIN_PACKAGE, MARKED_ELEMENT, FILE, BUNDLE_PROPERTY, AUTO_DETECT } abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { inner class TestContext( val testFile: File, val project: Project = getProject(), val javaFacade: JavaPsiFacade = myFixture.javaFacade, val module: Module = myFixture.module ) override fun getProjectDescriptor(): LightProjectDescriptor { val testConfigurationFile = File(testDataPath, fileName()) val renameObject = loadTestConfiguration(testConfigurationFile) val withRuntime = renameObject.getNullableString("withRuntime") val libraryInfos = renameObject.getAsJsonArray("libraries")?.map { it.asString!! } if (libraryInfos != null) { val jarPaths = listOf(KotlinArtifacts.instance.kotlinStdlib) + libraryInfos.map { File(PlatformTestUtil.getCommunityPath(), it.substringAfter("@")) } return KotlinWithJdkAndRuntimeLightProjectDescriptor(jarPaths, listOf(KotlinArtifacts.instance.kotlinStdlibSources)) } if (withRuntime != null) { return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE } return KotlinLightProjectDescriptor.INSTANCE } open fun doTest(path: String) { val testFile = File(path) val renameObject = loadTestConfiguration(testFile) val renameTypeStr = renameObject.getString("type") val hintDirective = renameObject.getNullableString("hint") val fixtureClasses = renameObject.getAsJsonArray("fixtureClasses")?.map { it.asString } ?: emptyList() try { fixtureClasses.forEach { TestFixtureExtension.loadFixture(it, module) } val context = TestContext(testFile) when (RenameType.valueOf(renameTypeStr)) { RenameType.JAVA_CLASS -> renameJavaClassTest(renameObject, context) RenameType.JAVA_METHOD -> renameJavaMethodTest(renameObject, context) RenameType.KOTLIN_CLASS -> renameKotlinClassTest(renameObject, context) RenameType.KOTLIN_FUNCTION -> renameKotlinFunctionTest(renameObject, context) RenameType.KOTLIN_PROPERTY -> renameKotlinPropertyTest(renameObject, context) RenameType.KOTLIN_PACKAGE -> renameKotlinPackageTest(renameObject, context) RenameType.MARKED_ELEMENT -> renameMarkedElement(renameObject, context) RenameType.FILE -> renameFile(renameObject, context) RenameType.BUNDLE_PROPERTY -> renameBundleProperty(renameObject, context) RenameType.AUTO_DETECT -> renameWithAutoDetection(renameObject, context) } if (hintDirective != null) { Assert.fail("""Hint "$hintDirective" was expected""") } if (renameObject["checkErrorsAfter"]?.asBoolean == true) { val psiManager = myFixture.psiManager val visitor = object : VirtualFileVisitor<Any>() { override fun visitFile(file: VirtualFile): Boolean { (psiManager.findFile(file) as? KtFile)?.let { DirectiveBasedActionUtils.checkForUnexpectedErrors(it) } return true } } for (sourceRoot in ModuleRootManager.getInstance(module).sourceRoots) { VfsUtilCore.visitChildrenRecursively(sourceRoot, visitor) } } } catch (e: Exception) { if (e !is RefactoringErrorHintException && e !is ConflictsInTestsException) throw e val hintExceptionUnquoted = StringUtil.unquoteString(e.message!!) if (hintDirective != null) { Assert.assertEquals(hintDirective, hintExceptionUnquoted) } else { Assert.fail("""Unexpected "hint: $hintExceptionUnquoted" """) } } finally { fixtureClasses.forEach { TestFixtureExtension.unloadFixture(it) } } } protected open fun configExtra(rootDir: VirtualFile, renameParamsObject: JsonObject) { } private fun renameMarkedElement(renameParamsObject: JsonObject, context: TestContext) { val mainFilePath = renameParamsObject.getString("mainFile") doTestCommittingDocuments(context) { rootDir -> configExtra(rootDir, renameParamsObject) val psiFile = myFixture.configureFromTempProjectFile(mainFilePath) doRenameMarkedElement(renameParamsObject, psiFile) } } private fun renameJavaClassTest(renameParamsObject: JsonObject, context: TestContext) { val classFQN = renameParamsObject.getString("classId").toClassId().asSingleFqName().asString() val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { _ -> val aClass = context.javaFacade.findClass(classFQN, context.project.allScope())!! val substitution = RenamePsiElementProcessor.forElement(aClass).substituteElementToRename(aClass, null) runRenameProcessor(context.project, newName, substitution, renameParamsObject, true, true) } } private fun renameJavaMethodTest(renameParamsObject: JsonObject, context: TestContext) { val classFQN = renameParamsObject.getString("classId").toClassId().asSingleFqName().asString() val methodSignature = renameParamsObject.getString("methodSignature") val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { val aClass = context.javaFacade.findClass(classFQN, GlobalSearchScope.moduleScope(context.module))!! val methodText = context.javaFacade.elementFactory.createMethodFromText("$methodSignature{}", null) val method = aClass.findMethodBySignature(methodText, false) if (method == null) throw IllegalStateException("Method with signature '$methodSignature' wasn't found in class $classFQN") val substitution = RenamePsiElementProcessor.forElement(method).substituteElementToRename(method, null) runRenameProcessor(context.project, newName, substitution, renameParamsObject, false, false) } } private fun renameKotlinFunctionTest(renameParamsObject: JsonObject, context: TestContext) { val oldMethodName = Name.identifier(renameParamsObject.getString("oldName")) doRenameInKotlinClassOrPackage(renameParamsObject, context) { _, scope -> scope.getContributedFunctions( oldMethodName, NoLookupLocation.FROM_TEST ).first() } } private fun renameKotlinPropertyTest(renameParamsObject: JsonObject, context: TestContext) { val oldPropertyName = Name.identifier(renameParamsObject.getString("oldName")) doRenameInKotlinClassOrPackage(renameParamsObject, context) { _, scope -> scope.getContributedVariables( oldPropertyName, NoLookupLocation.FROM_TEST ).first() } } private fun renameKotlinClassTest(renameParamsObject: JsonObject, context: TestContext) { renameParamsObject.getString("classId") //assertion doRenameInKotlinClassOrPackage(renameParamsObject, context) { declaration, _ -> declaration as ClassDescriptor } } private fun renameKotlinPackageTest(renameParamsObject: JsonObject, context: TestContext) { val fqn = FqNameUnsafe(renameParamsObject.getString("fqn")).toSafe() val newName = renameParamsObject.getString("newName") val mainFilePath = renameParamsObject.getNullableString("mainFile") ?: "${getTestDirName(false)}.kt" doTestCommittingDocuments(context) { val mainFile = myFixture.configureFromTempProjectFile(mainFilePath) as KtFile val fileFqn = mainFile.packageFqName Assert.assertTrue("File '${mainFilePath}' should have package containing ${fqn}", fileFqn.isSubpackageOf(fqn)) val packageDirective = mainFile.packageDirective!! val packageSegment = packageDirective.packageNames[fqn.pathSegments().size - 1] val segmentReference = packageSegment.mainReference val psiElement = segmentReference.resolve() ?: error("unable to resolve '${segmentReference.element.text}' from $packageDirective '${packageDirective.text}'") val substitution = RenamePsiElementProcessor.forElement(psiElement).substituteElementToRename(psiElement, null) runRenameProcessor(context.project, newName, substitution, renameParamsObject, true, true) } } private fun renameFile(renameParamsObject: JsonObject, context: TestContext) { val file = renameParamsObject.getString("file") val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { val psiFile = myFixture.configureFromTempProjectFile(file) runRenameProcessor(context.project, newName, psiFile, renameParamsObject, true, true) } } private fun renameBundleProperty(renameParamsObject: JsonObject, context: TestContext) { val file = renameParamsObject.getString("file") val oldName = renameParamsObject.getString("oldName") val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { val mainFile = myFixture.configureFromTempProjectFile(file) as PropertiesFile val property = mainFile.findPropertyByKey(oldName) as Property runRenameProcessor(context.project, newName, property, renameParamsObject, true, true) } } private fun doRenameInKotlinClassOrPackage( renameParamsObject: JsonObject, context: TestContext, findDescriptorToRename: (DeclarationDescriptor, MemberScope) -> DeclarationDescriptor ) { val classIdStr = renameParamsObject.getNullableString("classId") val packageFqnStr = renameParamsObject.getNullableString("packageFqn") if (classIdStr != null && packageFqnStr != null) { throw AssertionError("Both classId and packageFqn are defined. Where should I search: in class or in package?") } else if (classIdStr == null && packageFqnStr == null) { throw AssertionError("Define classId or packageFqn") } val newName = renameParamsObject.getString("newName") val mainFilePath = renameParamsObject.getNullableString("mainFile") ?: "${getTestDirName(false)}.kt" doTestCommittingDocuments(context) { val ktFile = myFixture.configureFromTempProjectFile(mainFilePath) as KtFile val module = ktFile.analyzeWithAllCompilerChecks().moduleDescriptor val (declaration, scopeToSearch) = if (classIdStr != null) { module.findClassAcrossModuleDependencies(classIdStr.toClassId())!!.let { it to it.defaultType.memberScope } } else { module.getPackage(FqName(packageFqnStr!!)).let { it to it.memberScope } } val psiElement = DescriptorToSourceUtils.descriptorToDeclaration(findDescriptorToRename(declaration, scopeToSearch))!! // The Java processor always chooses renaming the base element when running in unit test mode, // so if we want to rename only the inherited element, we need to skip the substitutor. val skipSubstitute = renameParamsObject["skipSubstitute"]?.asBoolean ?: false val substitution = if (skipSubstitute) psiElement else RenamePsiElementProcessor.forElement(psiElement).substituteElementToRename(psiElement, null) runRenameProcessor(context.project, newName, substitution, renameParamsObject, true, true) } } private fun renameWithAutoDetection(renameParamsObject: JsonObject, context: TestContext) { val mainFilePath = renameParamsObject.getString("mainFile") val newName = renameParamsObject.getString("newName") doTestCommittingDocuments(context) { rootDir -> configExtra(rootDir, renameParamsObject) val psiFile = myFixture.configureFromTempProjectFile(mainFilePath) val doc = PsiDocumentManager.getInstance(project).getDocument(psiFile)!! val marker = doc.extractMarkerOffset(project, "/*rename*/") assert(marker != -1) editor.caretModel.moveToOffset(marker) val currentCaret = editor.caretModel.currentCaret val dataContext = createTextEditorBasedDataContext(project, editor, currentCaret) { add(PsiElementRenameHandler.DEFAULT_NAME, newName) } var handler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext) ?: return@doTestCommittingDocuments Assert.assertTrue(handler.isAvailableOnDataContext(dataContext)) if (handler is KotlinRenameDispatcherHandler) { handler = handler.getRenameHandler(dataContext)!! } if (handler is VariableInplaceRenameHandler) { val elementToRename = psiFile.findElementAt(currentCaret.offset)!!.getNonStrictParentOfType<PsiNamedElement>()!! CodeInsightTestUtil.doInlineRename(handler, newName, editor, elementToRename) } else { handler.invoke(project, editor, psiFile, dataContext) } } } protected fun getTestDirName(lowercaseFirstLetter: Boolean): String { val testName = getTestName(lowercaseFirstLetter) return testName.substring(0, testName.indexOf('_')) } protected fun doTestCommittingDocuments(context: TestContext, action: (VirtualFile) -> Unit) { val beforeDir = context.testFile.parentFile.name + "/before" val beforeVFile = myFixture.copyDirectoryToProject(beforeDir, "") PsiDocumentManager.getInstance(myFixture.project).commitAllDocuments() val afterDir = File(context.testFile.parentFile, "after") action(beforeVFile) PsiDocumentManager.getInstance(project).commitAllDocuments() FileDocumentManager.getInstance().saveAllDocuments() val afterVFile = LocalFileSystem.getInstance().findFileByIoFile(afterDir)?.apply { UsefulTestCase.refreshRecursively(this) } ?: error("`after` directory not found") PlatformTestUtil.assertDirectoriesEqual(afterVFile, beforeVFile) } } private fun String.toClassId(): ClassId { val relativeClassName = FqName(substringAfterLast('/')) val packageFqName = FqName(substringBeforeLast('/', "").replace('/', '.')) return ClassId(packageFqName, relativeClassName, false) } fun loadTestConfiguration(testFile: File): JsonObject { val fileText = FileUtil.loadFile(testFile, true) return parseString(fileText) as JsonObject } fun runRenameProcessor( project: Project, newName: String, substitution: PsiElement?, renameParamsObject: JsonObject, isSearchInComments: Boolean, isSearchTextOccurrences: Boolean ) { if (substitution == null) return fun createProcessor(): BaseRefactoringProcessor { if (substitution is PsiPackage && substitution !is KtLightPackage) { val oldName = substitution.qualifiedName if (StringUtil.getPackageName(oldName) != StringUtil.getPackageName(newName)) { return RenamePsiPackageProcessor.createRenameMoveProcessor( newName, substitution, isSearchInComments, isSearchTextOccurrences ) } } return RenameProcessor(project, substitution, newName, isSearchInComments, isSearchTextOccurrences) } val processor = createProcessor() if (renameParamsObject["overloadRenamer.onlyPrimaryElement"]?.asBoolean == true) { with(AutomaticOverloadsRenamer) { substitution.elementFilter = { false } } } if (processor is RenameProcessor) { @Suppress("DEPRECATION") Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME).forEach { processor.addRenamerFactory(it) } } processor.run() } fun doRenameMarkedElement(renameParamsObject: JsonObject, psiFile: PsiFile) { val project = psiFile.project val newName = renameParamsObject.getString("newName") val doc = PsiDocumentManager.getInstance(project).getDocument(psiFile)!! val marker = doc.extractMarkerOffset(project, "/*rename*/") assert(marker != -1) val editorFactory = EditorFactory.getInstance() var editor = editorFactory.getEditors(doc).firstOrNull() var shouldReleaseEditor = false if (editor == null) { editor = editorFactory.createEditor(doc) shouldReleaseEditor = true } try { val isByRef = renameParamsObject["byRef"]?.asBoolean ?: false val isInjected = renameParamsObject["injected"]?.asBoolean ?: false var currentEditor = editor!! var currentFile: PsiFile = psiFile if (isByRef || isInjected) { currentEditor.caretModel.moveToOffset(marker) if (isInjected) { currentFile = InjectedLanguageUtil.findInjectedPsiNoCommit(psiFile, marker)!! currentEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, currentFile) } } val toRename = if (isByRef) { TargetElementUtil.findTargetElement(currentEditor, TargetElementUtil.getInstance().allAccepted)!! } else { currentFile.findElementAt(marker)!!.getNonStrictParentOfType<PsiNamedElement>()!! } val substitution = RenamePsiElementProcessor.forElement(toRename).substituteElementToRename(toRename, null) val searchInComments = renameParamsObject["searchInComments"]?.asBoolean ?: true val searchInTextOccurrences = renameParamsObject["searchInTextOccurrences"]?.asBoolean ?: true runRenameProcessor(project, newName, substitution, renameParamsObject, searchInComments, searchInTextOccurrences) } finally { if (shouldReleaseEditor) { editorFactory.releaseEditor(editor!!) } } }
apache-2.0
d1518128872a5f550427c52fb3793a09
44.793548
170
0.707148
5.355634
false
true
false
false
smmribeiro/intellij-community
platform/lang-impl/testSources/com/intellij/openapi/roots/ui/configuration/SdkTypeRegistrationTest.kt
5
2894
// 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 com.intellij.openapi.roots.ui.configuration import com.intellij.openapi.Disposable import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.projectRoots.* import com.intellij.openapi.projectRoots.impl.UnknownSdkType import com.intellij.openapi.util.Disposer import com.intellij.testFramework.HeavyPlatformTestCase import org.jdom.Element class SdkTypeRegistrationTest : HeavyPlatformTestCase() { fun `test unregister sdk type and register again`() { val sdkTable = ProjectJdkTable.getInstance() runWithRegisteredType { val sdk = sdkTable.createSdk("foo", MockSdkType.getInstance()) val modificator = sdk.sdkModificator modificator.sdkAdditionalData = MockSdkAdditionalData("bar") modificator.commitChanges() runWriteAction { sdkTable.addJdk(sdk, testRootDisposable) } assertEquals("foo", assertOneElement(sdkTable.getSdksOfType(MockSdkType.getInstance())).name) } assertOneElement(sdkTable.getSdksOfType(UnknownSdkType.getInstance("Mock"))) registerSdkType(testRootDisposable) val reloadedSdk = assertOneElement(sdkTable.getSdksOfType(MockSdkType.getInstance())) assertEquals("foo", reloadedSdk.name) } private fun runWithRegisteredType(action: () -> Unit) { val sdkTypeDisposable = Disposer.newDisposable() registerSdkType(sdkTypeDisposable) try { action() } finally { Disposer.dispose(sdkTypeDisposable) } } private fun registerSdkType(disposable: Disposable) { val sdkTypeDisposable = Disposer.newDisposable() Disposer.register(disposable, Disposable { runWriteAction { Disposer.dispose(sdkTypeDisposable) } }) SdkType.EP_NAME.getPoint().registerExtension(MockSdkType(), sdkTypeDisposable) } } private class MockSdkType : SdkType("Mock") { companion object { @JvmStatic fun getInstance() = findInstance(MockSdkType::class.java) } override fun suggestHomePath(): String? = null override fun isValidSdkHome(path: String): Boolean = false override fun suggestSdkName(currentSdkName: String?, sdkHome: String): String = "" override fun createAdditionalDataConfigurable(sdkModel: SdkModel, sdkModificator: SdkModificator): AdditionalDataConfigurable? = null override fun getPresentableName(): String = "Mock" override fun saveAdditionalData(additionalData: SdkAdditionalData, additional: Element) { additional.setAttribute("data", (additionalData as MockSdkAdditionalData).data) } override fun loadAdditionalData(additional: Element): SdkAdditionalData? { return MockSdkAdditionalData(additional.getAttributeValue("data") ?: "") } } private class MockSdkAdditionalData(var data: String) : SdkAdditionalData
apache-2.0
0cd5b17682cc232c3062c72a6a320a2a
35.1875
140
0.758466
4.905085
false
true
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/ui/SuggestionPresenter.kt
1
3849
package training.featuresSuggester.ui import com.intellij.ide.BrowserUtil import com.intellij.ide.util.TipAndTrickBean import com.intellij.notification.Notification import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.project.Project import training.featuresSuggester.DocumentationSuggestion import training.featuresSuggester.FeatureSuggesterBundle import training.featuresSuggester.PopupSuggestion import training.featuresSuggester.TipSuggestion import training.featuresSuggester.settings.FeatureSuggesterSettings import training.featuresSuggester.statistics.FeatureSuggesterStatistics interface SuggestionPresenter { fun showSuggestion(project: Project, suggestion: PopupSuggestion) } @Suppress("UnstableApiUsage", "DialogTitleCapitalization") class NotificationSuggestionPresenter : SuggestionPresenter { private val notificationGroup: NotificationGroup = NotificationGroupManager.getInstance() .getNotificationGroup("IDE Feature Suggester") override fun showSuggestion(project: Project, suggestion: PopupSuggestion) { val notification = notificationGroup.createNotification( title = FeatureSuggesterBundle.message("notification.title"), content = suggestion.message, type = NotificationType.INFORMATION ).apply { when (suggestion) { is TipSuggestion -> { val action = createShowTipAction(project, this, suggestion) if (action != null) { addAction(action) } } is DocumentationSuggestion -> { addAction(createGoToDocumentationAction(this, suggestion)) } } addAction(createDontSuggestAction(this, suggestion)) } notification.notify(project) FeatureSuggesterStatistics.logNotificationShowed(suggestion.suggesterId) } private fun createDontSuggestAction(notification: Notification, suggestion: PopupSuggestion): AnAction { return object : AnAction(FeatureSuggesterBundle.message("notification.dont.suggest")) { override fun actionPerformed(e: AnActionEvent) { val settings = FeatureSuggesterSettings.instance() settings.setEnabled(suggestion.suggesterId, false) notification.hideBalloon() FeatureSuggesterStatistics.logNotificationDontSuggest(suggestion.suggesterId) } } } private fun createGoToDocumentationAction( notification: Notification, suggestion: DocumentationSuggestion ): AnAction { return object : AnAction( FeatureSuggesterBundle.message( "notification.open.help", ApplicationNamesInfo.getInstance().productName ) ) { override fun actionPerformed(e: AnActionEvent) { BrowserUtil.open(suggestion.documentURL) notification.hideBalloon() FeatureSuggesterStatistics.logNotificationLearnMore(suggestion.suggesterId) } } } private fun createShowTipAction( project: Project, notification: Notification, suggestion: TipSuggestion ): AnAction? { val tip = getTipByFilename(suggestion.suggestingTipFilename) ?: return null return object : AnAction(FeatureSuggesterBundle.message("notification.learn.more")) { override fun actionPerformed(e: AnActionEvent) { SingleTipDialog.showForProject(project, tip) notification.hideBalloon() FeatureSuggesterStatistics.logNotificationLearnMore(suggestion.suggesterId) } } } private fun getTipByFilename(tipFilename: String): TipAndTrickBean? { return TipAndTrickBean.EP_NAME.extensions.find { it.fileName == tipFilename } } }
apache-2.0
9cf2ae34f105e4634c6659ec9a4966aa
37.108911
106
0.765913
5.390756
false
false
false
false
ReactiveX/RxKotlin
src/main/kotlin/io/reactivex/rxkotlin/completable.kt
1
1661
@file:Suppress("HasPlatformType", "unused") package io.reactivex.rxkotlin import io.reactivex.Completable import io.reactivex.CompletableSource import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.annotations.BackpressureKind import io.reactivex.annotations.BackpressureSupport import io.reactivex.annotations.CheckReturnValue import io.reactivex.annotations.SchedulerSupport import io.reactivex.functions.Action import java.util.concurrent.Callable import java.util.concurrent.Future fun Action.toCompletable(): Completable = Completable.fromAction(this) fun Callable<out Any>.toCompletable(): Completable = Completable.fromCallable(this) fun Future<out Any>.toCompletable(): Completable = Completable.fromFuture(this) fun (() -> Any).toCompletable(): Completable = Completable.fromCallable(this) // EXTENSION FUNCTION OPERATORS /** * Merges the emissions of a Observable<Completable>. Same as calling `flatMapSingle { it }`. */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun Observable<Completable>.mergeAllCompletables(): Completable = flatMapCompletable { it } /** * Merges the emissions of a Flowable<Completable>. Same as calling `flatMap { it }`. */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) fun Flowable<Completable>.mergeAllCompletables(): Completable = flatMapCompletable { it } /** * Concats an Iterable of completables into flowable. Same as calling `Completable.concat(this)` */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun Iterable<CompletableSource>.concatAll(): Completable = Completable.concat(this)
apache-2.0
7b9bf838df462b0b0fa2957672a64948
35.911111
96
0.810957
4.639665
false
false
false
false
mr-max/anko
dsl/testData/functional/sdk23/ComplexListenerSetterTest.kt
8
3547
public fun android.view.View.onAttachStateChangeListener(init: __View_OnAttachStateChangeListener.() -> Unit) { val listener = __View_OnAttachStateChangeListener() listener.init() addOnAttachStateChangeListener(listener) } public fun android.widget.TextView.textChangedListener(init: __TextWatcher.() -> Unit) { val listener = __TextWatcher() listener.init() addTextChangedListener(listener) } public fun android.gesture.GestureOverlayView.onGestureListener(init: __GestureOverlayView_OnGestureListener.() -> Unit) { val listener = __GestureOverlayView_OnGestureListener() listener.init() addOnGestureListener(listener) } public fun android.gesture.GestureOverlayView.onGesturingListener(init: __GestureOverlayView_OnGesturingListener.() -> Unit) { val listener = __GestureOverlayView_OnGesturingListener() listener.init() addOnGesturingListener(listener) } public fun android.view.ViewGroup.onHierarchyChangeListener(init: __ViewGroup_OnHierarchyChangeListener.() -> Unit) { val listener = __ViewGroup_OnHierarchyChangeListener() listener.init() setOnHierarchyChangeListener(listener) } public fun android.widget.AbsListView.onScrollListener(init: __AbsListView_OnScrollListener.() -> Unit) { val listener = __AbsListView_OnScrollListener() listener.init() setOnScrollListener(listener) } public fun android.widget.AdapterView<out android.widget.Adapter?>.onItemSelectedListener(init: __AdapterView_OnItemSelectedListener.() -> Unit) { val listener = __AdapterView_OnItemSelectedListener() listener.init() setOnItemSelectedListener(listener) } public fun android.widget.AutoCompleteTextView.onItemSelectedListener(init: __AdapterView_OnItemSelectedListener.() -> Unit) { val listener = __AdapterView_OnItemSelectedListener() listener.init() setOnItemSelectedListener(listener) } public fun android.widget.RadioGroup.onHierarchyChangeListener(init: __ViewGroup_OnHierarchyChangeListener.() -> Unit) { val listener = __ViewGroup_OnHierarchyChangeListener() listener.init() setOnHierarchyChangeListener(listener) } public fun android.widget.SearchView.onQueryTextListener(init: __SearchView_OnQueryTextListener.() -> Unit) { val listener = __SearchView_OnQueryTextListener() listener.init() setOnQueryTextListener(listener) } public fun android.widget.SearchView.onSuggestionListener(init: __SearchView_OnSuggestionListener.() -> Unit) { val listener = __SearchView_OnSuggestionListener() listener.init() setOnSuggestionListener(listener) } public fun android.widget.SeekBar.onSeekBarChangeListener(init: __SeekBar_OnSeekBarChangeListener.() -> Unit) { val listener = __SeekBar_OnSeekBarChangeListener() listener.init() setOnSeekBarChangeListener(listener) } public fun android.widget.SlidingDrawer.onDrawerScrollListener(init: __SlidingDrawer_OnDrawerScrollListener.() -> Unit) { val listener = __SlidingDrawer_OnDrawerScrollListener() listener.init() setOnDrawerScrollListener(listener) } public fun android.widget.TableLayout.onHierarchyChangeListener(init: __ViewGroup_OnHierarchyChangeListener.() -> Unit) { val listener = __ViewGroup_OnHierarchyChangeListener() listener.init() setOnHierarchyChangeListener(listener) } public fun android.widget.TableRow.onHierarchyChangeListener(init: __ViewGroup_OnHierarchyChangeListener.() -> Unit) { val listener = __ViewGroup_OnHierarchyChangeListener() listener.init() setOnHierarchyChangeListener(listener) }
apache-2.0
cf003ee5cb3ffa94fe56674c0d199c58
38.865169
146
0.771074
5.185673
false
false
false
false
hsz/idea-gitignore
src/main/kotlin/mobi/hsz/idea/gitignore/psi/IgnoreFile.kt
1
1908
// 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 mobi.hsz.idea.gitignore.psi import com.intellij.lang.Language import com.intellij.lang.LanguageParserDefinitions import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiElementVisitor import com.intellij.psi.impl.source.PsiFileImpl import mobi.hsz.idea.gitignore.IgnoreException import mobi.hsz.idea.gitignore.file.type.IgnoreFileType import mobi.hsz.idea.gitignore.lang.IgnoreLanguage /** * Base plugin file. */ class IgnoreFile(viewProvider: FileViewProvider, private val fileType: IgnoreFileType) : PsiFileImpl(viewProvider) { private val language = findLanguage(fileType.language, viewProvider) companion object { /** * Searches for the matching language in [FileViewProvider]. * * @param baseLanguage language to look for * @param viewProvider current [FileViewProvider] * @return matched [Language] */ private fun findLanguage(baseLanguage: Language, viewProvider: FileViewProvider): Language = viewProvider.languages.run { find { it.isKindOf(baseLanguage) }?.let { return it } find { it is IgnoreLanguage }?.let { return it } throw AssertionError("Language $baseLanguage doesn't participate in view provider $viewProvider: $this") } } init { LanguageParserDefinitions.INSTANCE.forLanguage(language).apply { init(fileNodeType, fileNodeType) } ?: throw IgnoreException("PsiFileBase: language.getParserDefinition() returned null for: $language") } override fun accept(visitor: PsiElementVisitor) { visitor.visitFile(this) } override fun getLanguage() = language override fun getFileType() = fileType override fun toString() = fileType.name }
mit
1ba4aa3a4ab5b5c0105cf869cbc216b3
37.16
140
0.716981
4.79397
false
false
false
false
mapzen/eraser-map
app/src/test/kotlin/com/mapzen/erasermap/TestUtils.kt
1
1045
package com.mapzen.erasermap import com.google.common.io.Files import com.mapzen.pelias.gson.Feature import com.mapzen.pelias.gson.Geometry import com.mapzen.pelias.gson.Properties import com.mapzen.valhalla.Instruction import org.json.JSONObject import java.io.File class TestUtils { companion object { fun getInstruction(name: String):Instruction { return Instruction(JSONObject(getFixture(name + ".instruction"))) } private fun getFixture(name: String): String { val basedir = System.getProperty("user.dir") val file = File(basedir + "/src/test/fixtures/" + name) var fixture = "" try { fixture = Files.toString(file, com.google.common.base.Charsets.UTF_8) } catch (e: Exception) { fixture = "not found" } return fixture } fun getFeature(): Feature { val feature = Feature() feature.geometry = Geometry() feature.geometry.coordinates = arrayListOf(0.0, 0.0) feature.properties = Properties() return feature } } }
gpl-3.0
39337e197b390932187a9b198338fcb5
24.512195
77
0.673684
3.958333
false
false
false
false
Adven27/Exam
exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/commands/set/SetRenderers.kt
1
1367
package io.github.adven27.concordion.extensions.exam.db.commands.set import io.github.adven27.concordion.extensions.exam.core.commands.SetUpEvent import io.github.adven27.concordion.extensions.exam.core.commands.SuitableSetUpListener import io.github.adven27.concordion.extensions.exam.db.DbPlugin.ValuePrinter import io.github.adven27.concordion.extensions.exam.db.commands.renderTable import org.concordion.api.Element import org.concordion.api.listener.AbstractElementEvent class MdSetRenderer(printer: ValuePrinter) : BaseSetRenderer(printer) { override fun root(event: AbstractElementEvent): Element = event.element.parentElement.parentElement override fun isSuitFor(element: Element) = element.localName != "div" } class HtmlSetRenderer(printer: ValuePrinter) : BaseSetRenderer(printer) { override fun root(event: AbstractElementEvent): Element = event.element override fun isSuitFor(element: Element) = element.localName == "div" } abstract class BaseSetRenderer(private val printer: ValuePrinter) : SuitableSetUpListener<SetCommand.Operation>() { abstract fun root(event: AbstractElementEvent): Element override fun setUpCompleted(event: SetUpEvent<SetCommand.Operation>) = with(root(event)) { appendSister(renderTable(event.target.table, printer, event.target.caption).el) parentElement.removeChild(this) } }
mit
1a89576237a4f2687357ab1900f42eb1
49.62963
115
0.801756
4.080597
false
false
false
false
kpspemu/kpspemu
src/nativeCommonMain/kotlin/com/soywiz/kpspemu/native/cpu/registerDyna.kt
1
4566
package com.soywiz.kpspemu.cpu import kotlinx.cinterop.* import platform.posix.* import kotlin.reflect.* import com.soywiz.dynarek2.* import com.soywiz.kpspemu.* import com.soywiz.kpspemu.cpu.* val COpaquePointer.asCpuState get() = this.asStableRef<CpuState>().get() fun _dyna_syscall(ptr: COpaquePointer, syscall: Int): Int = dyna_syscall(ptr.asCpuState, syscall) fun _dyna_checkFNan(ptr: COpaquePointer, FD: Float): Int = dyna_checkFNan(ptr.asCpuState, FD) fun _dyna_fmul(ptr: COpaquePointer, RS: Float, RT: Float): Float = dyna_fmul(ptr.asCpuState, RS, RT) fun _dyna_cvt_w_s(ptr: COpaquePointer, FS: Float): Int = dyna_cvt_w_s(ptr.asCpuState, FS) actual fun D2Context.registerDyna(): Unit { registerFunc(::iprint, staticCFunction(::iprint).asLong) // Plain registerFunc(::dyna_clz, staticCFunction(::dyna_clz).asLong) registerFunc(::dyna_clo, staticCFunction(::dyna_clo).asLong) registerFunc(::dyna_ext, staticCFunction(::dyna_ext).asLong) registerFunc(::dyna_ins, staticCFunction(::dyna_ins).asLong) registerFunc(::dyna_movz, staticCFunction(::dyna_movz).asLong) registerFunc(::dyna_movn, staticCFunction(::dyna_movn).asLong) registerFunc(::dyna_seb, staticCFunction(::dyna_seb).asLong) registerFunc(::dyna_seh, staticCFunction(::dyna_seh).asLong) registerFunc(::dyna_wsbh, staticCFunction(::dyna_wsbh).asLong) registerFunc(::dyna_wsbw, staticCFunction(::dyna_wsbw).asLong) registerFunc(::dyna_max, staticCFunction(::dyna_max).asLong) registerFunc(::dyna_min, staticCFunction(::dyna_min).asLong) registerFunc(::dyna_bitrev32, staticCFunction(::dyna_bitrev32).asLong) registerFunc(::dyna_rotr, staticCFunction(::dyna_rotr).asLong) registerFunc(::dyna_sll, staticCFunction(::dyna_sll).asLong) registerFunc(::dyna_sra, staticCFunction(::dyna_sra).asLong) registerFunc(::dyna_srl, staticCFunction(::dyna_srl).asLong) registerFunc(::dyna_divu_LO, staticCFunction(::dyna_divu_LO).asLong) registerFunc(::dyna_divu_HI, staticCFunction(::dyna_divu_HI).asLong) registerFunc(::dyna_mult, staticCFunction(::dyna_mult).asLong) registerFunc(::dyna_mult_LO, staticCFunction(::dyna_mult_LO).asLong) registerFunc(::dyna_multu_LO, staticCFunction(::dyna_multu_LO).asLong) registerFunc(::dyna_mult_HI, staticCFunction(::dyna_mult_HI).asLong) registerFunc(::dyna_multu_HI, staticCFunction(::dyna_multu_HI).asLong) registerFunc(::dyna_madd, staticCFunction(::dyna_madd).asLong) registerFunc(::dyna_maddu, staticCFunction(::dyna_maddu).asLong) registerFunc(::dyna_msub, staticCFunction(::dyna_msub).asLong) registerFunc(::dyna_msubu, staticCFunction(::dyna_msubu).asLong) registerFunc(::dyna_fadd, staticCFunction(::dyna_fadd).asLong) registerFunc(::dyna_fsub, staticCFunction(::dyna_fsub).asLong) registerFunc(::dyna_fdiv, staticCFunction(::dyna_fdiv).asLong) registerFunc(::dyna_fneg, staticCFunction(::dyna_fneg).asLong) registerFunc(::dyna_fabs, staticCFunction(::dyna_fabs).asLong) registerFunc(::dyna_fsqrt, staticCFunction(::dyna_fsqrt).asLong) registerFunc(::dyna_break, staticCFunction(::dyna_break).asLong) registerFunc(::dyna_slt, staticCFunction(::dyna_slt).asLong) registerFunc(::dyna_sltu, staticCFunction(::dyna_sltu).asLong) registerFunc(::dyna_trunc_w_s, staticCFunction(::dyna_trunc_w_s).asLong) registerFunc(::dyna_round_w_s, staticCFunction(::dyna_round_w_s).asLong) registerFunc(::dyna_ceil_w_s, staticCFunction(::dyna_ceil_w_s).asLong) registerFunc(::dyna_floor_w_s, staticCFunction(::dyna_floor_w_s).asLong) registerFunc(::dyna_cvt_s_w, staticCFunction(::dyna_cvt_s_w).asLong) registerFunc(::dyna_c_f_s, staticCFunction(::dyna_c_f_s).asLong) registerFunc(::dyna_c_un_s, staticCFunction(::dyna_c_un_s).asLong) registerFunc(::dyna_c_eq_s, staticCFunction(::dyna_c_eq_s).asLong) registerFunc(::dyna_c_ueq_s, staticCFunction(::dyna_c_ueq_s).asLong) registerFunc(::dyna_c_olt_s, staticCFunction(::dyna_c_olt_s).asLong) registerFunc(::dyna_c_ult_s, staticCFunction(::dyna_c_ult_s).asLong) registerFunc(::dyna_c_ole_s, staticCFunction(::dyna_c_ole_s).asLong) registerFunc(::dyna_c_ule_s, staticCFunction(::dyna_c_ule_s).asLong) // With EXTERNAL CpuState registerFunc(::dyna_fmul, staticCFunction(::_dyna_fmul).asLong) registerFunc(::dyna_syscall, staticCFunction(::_dyna_syscall).asLong) registerFunc(::dyna_checkFNan, staticCFunction(::_dyna_checkFNan).asLong) registerFunc(::dyna_cvt_w_s, staticCFunction(::_dyna_cvt_w_s).asLong) }
mit
d90bd4124b39f412946ff38011e60586
58.298701
100
0.725361
3.06443
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/maps/movement/MovementManager.kt
1
19976
package nl.rsdt.japp.jotial.maps.movement import android.content.SharedPreferences import android.graphics.BitmapFactory import android.graphics.Color import android.location.Location import android.os.Bundle import android.util.Pair import android.view.View import com.google.android.gms.location.LocationListener import com.google.android.gms.location.LocationRequest import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.LocationSource import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.google.android.gms.maps.model.PolylineOptions import com.google.android.material.snackbar.Snackbar import com.google.firebase.messaging.FirebaseMessaging import com.google.gson.Gson import com.google.gson.reflect.TypeToken import nl.rsdt.japp.R import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.jotial.data.bodies.AutoUpdateTaakPostBody import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo import nl.rsdt.japp.jotial.io.AppData import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier import nl.rsdt.japp.jotial.maps.misc.AnimateMarkerTool import nl.rsdt.japp.jotial.maps.misc.LatLngInterpolator import nl.rsdt.japp.jotial.maps.wrapper.ICameraPosition import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap import nl.rsdt.japp.jotial.maps.wrapper.IMarker import nl.rsdt.japp.jotial.maps.wrapper.IPolyline import nl.rsdt.japp.jotial.net.apis.AutoApi import nl.rsdt.japp.service.LocationService import nl.rsdt.japp.service.ServiceManager import retrofit2.Call import retrofit2.Callback import retrofit2.Response import kotlin.collections.ArrayList /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 2-8-2016 * Description... */ class MovementManager : ServiceManager.OnBindCallback<LocationService.LocationBinder>, LocationListener, SharedPreferences.OnSharedPreferenceChangeListener { private val MAX_SIZE_LONG_TAIL = 60 override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { if (key == JappPreferences.TAIL_LENGTH){ smallTailPoints.maxSize = JappPreferences.tailLength smallTail?.points = smallTailPoints hourTailPoints.maxSize = JappPreferences.tailLength hourTail?.points = hourTailPoints hourTailPoints.onremoveCallback = ::addToLongTail } } private val fastestInterval: Long = 100 private val locationInterval: Long = 1500 private var service: LocationService? = null private var jotiMap: IJotiMap? = null private var marker: IMarker? = null private var smallTail: IPolyline? = null private val smallTailPoints: TailPoints<LatLng> = TailPoints(JappPreferences.tailLength) private var hourTail: IPolyline? = null private val hourTailPoints: TailPoints<LatLng> = TailPoints(MAX_SIZE_LONG_TAIL) private var bearing: Float = 0f private var lastLocation: Location? = null private var lastHourLocationTime: Long = System.currentTimeMillis() private var activeSession: FollowSession? = null private var deelgebied: Deelgebied? = null private var snackBarView: View? = null private var listener: LocationService.OnResolutionRequiredListener? = null fun addToLongTail(location: LatLng, addedOn: Long){ if (lastHourLocationTime - addedOn > 60 * 60 * 1000){ lastHourLocationTime = addedOn hourTailPoints.add(location) hourTail?.points = hourTailPoints } } fun setListener(listener: LocationService.OnResolutionRequiredListener) { this.listener = listener } fun setSnackBarView(snackBarView: View) { this.snackBarView = snackBarView } fun newSession(jotiMap: IJotiMap,before: ICameraPosition, zoom: Float, aoa: Float): FollowSession? { if (activeSession != null) { activeSession!!.end() activeSession = null } activeSession = FollowSession(jotiMap,before, zoom, aoa) return activeSession } fun onCreate(savedInstanceState: Bundle?) { val list:ArrayList<Pair<LatLng,Long>>? = AppData.getObject<ArrayList<Pair<LatLng,Long>>>( STORAGE_KEY, object : TypeToken<ArrayList<Pair<LatLng,Long>>>() {}.type) if (list != null) { smallTailPoints.setPoints(list) smallTail?.points = smallTailPoints } } fun onSaveInstanceState(saveInstanceState: Bundle?) { save() } override fun onLocationChanged(l: Location) { Japp.lastLocation = l var location = Japp.lastLocation?:l var nextLocation = Japp.lastLocation?:l do { onNewLocation(location) location = nextLocation nextLocation = Japp.lastLocation?:l } while(location != nextLocation) } fun onNewLocation(location: Location){ val ldeelgebied = deelgebied if (marker != null) { if (lastLocation != null) { bearing = lastLocation!!.bearingTo(location) /** * Animate the marker to the new position */ AnimateMarkerTool.animateMarkerToICS(marker, LatLng(location.latitude, location.longitude), LatLngInterpolator.Linear(), 1000) marker?.setRotation(bearing) } else { marker?.position = LatLng(location.latitude, location.longitude) } smallTailPoints.add(LatLng(location.latitude, location.longitude)) smallTail?.points = smallTailPoints } val refresh = if (ldeelgebied != null) { if (!ldeelgebied.containsLocation(location)) { /** * Unsubscribe from the current deelgebied messages */ FirebaseMessaging.getInstance().unsubscribeFromTopic(ldeelgebied.name) true } else { false } } else { true } if (refresh) { deelgebied = Deelgebied.resolveOnLocation(location) if (deelgebied != null && snackBarView != null) { Snackbar.make(snackBarView!!, """Welkom in deelgebied ${deelgebied?.name}""", Snackbar.LENGTH_LONG).show() /** * Subscribe to the new deelgebied messages. */ FirebaseMessaging.getInstance().subscribeToTopic(deelgebied?.name) val coordinatesSmall: List<LatLng> = smallTailPoints smallTail?.remove() hourTail?.remove() smallTail = jotiMap!!.addPolyline( PolylineOptions() .width(3f) .color(getTailColor()?:Color.BLUE) .addAll(coordinatesSmall)) val coordinatesHour: List<LatLng> = smallTailPoints hourTail = jotiMap!!.addPolyline( PolylineOptions() .width(3f) .color(getTailColor()?:Color.BLUE) .addAll(coordinatesHour)) } } /** * Make the marker visible */ if (marker?.isVisible == false) { marker?.isVisible = true } updateAutoTaak(location) if (activeSession != null) { activeSession!!.onLocationChanged(location) } lastLocation = location } private fun getTailColor(): Int? { val color = deelgebied?.color return if (color != null) Color.rgb(255 - Color.red(color), 255 - Color.green(color), 255 - Color.blue(color)) else null } private fun updateAutoTaak(location: Location) { if (JappPreferences.autoTaak) { val autoApi = Japp.getApi(AutoApi::class.java) autoApi.getInfoById(JappPreferences.accountKey, JappPreferences.accountId).enqueue(object : Callback<AutoInzittendeInfo> { override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) { //TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) { val newTaak = """${deelgebied?.name}${Japp.getString(R.string.automatisch)}""" if (deelgebied != null && newTaak.toLowerCase() != response.body()?.taak?.toLowerCase()) { val body: AutoUpdateTaakPostBody = AutoUpdateTaakPostBody.default body.setTaak(newTaak) autoApi.updateTaak(body).enqueue(object : Callback<Void> { override fun onFailure(call: Call<Void>, t: Throwable) { //TODO("not implemented") } override fun onResponse(call: Call<Void>, response: Response<Void>) { if (response.isSuccessful) { Snackbar.make(snackBarView!!, """taak upgedate: ${deelgebied?.name}""", Snackbar.LENGTH_LONG).show() } } }) } } }) } } override fun onBind(binder: LocationService.LocationBinder) { val service = binder.instance service.setListener(listener) service.add(this) service.request = LocationRequest() .setInterval(locationInterval) .setFastestInterval(fastestInterval) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) this.service = service } fun postResolutionResultToService(code: Int) { service?.handleResolutionResult(code) } fun requestLocationSettingRequest() { service?.checkLocationSettings() } fun onMapReady(jotiMap: IJotiMap) { this.jotiMap = jotiMap val identifier = MarkerIdentifier.Builder() .setType(MarkerIdentifier.TYPE_ME) .add("icon", R.drawable.me.toString()) .create() marker = jotiMap.addMarker(Pair( MarkerOptions() .position(LatLng(52.021818, 6.059603)) .visible(false) .flat(true) .title(Gson().toJson(identifier)), BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.me))) smallTail = jotiMap.addPolyline( PolylineOptions() .width(3f) .color(getTailColor()?:Color.BLUE)) hourTail = jotiMap.addPolyline( PolylineOptions() .width(3f) .color(getTailColor()?:Color.BLUE)) if (smallTailPoints.isNotEmpty()) { smallTail!!.points = smallTailPoints val last = smallTailPoints.size - 1 marker?.position = smallTailPoints[last] marker?.isVisible = true } } inner class FollowSession(private val jotiMap: IJotiMap, private val before: ICameraPosition, zoom: Float, aoa: Float) : LocationSource.OnLocationChangedListener { private var zoom = 19f private var aoa = 45f init { this.zoom = zoom this.aoa = aoa /** * Enable controls. */ jotiMap.uiSettings.setAllGesturesEnabled(true) jotiMap.uiSettings.setCompassEnabled(true) jotiMap.setOnCameraMoveStartedListener(GoogleMap.OnCameraMoveStartedListener { i -> if (i == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) { val position = jotiMap.previousCameraPosition setZoom(position.zoom) setAngleOfAttack(position.tilt) } }) } private fun setZoom(zoom: Float) { this.zoom = zoom } private fun setAngleOfAttack(aoa: Float) { this.aoa = aoa } override fun onLocationChanged(location: Location) { /** * Animate the camera to the new position */ if (JappPreferences.followNorth()) { jotiMap.cameraToLocation(true, location, zoom, aoa, 0f) } else { jotiMap.cameraToLocation(true, location, zoom, aoa, bearing) } } fun end() { /** * Save the settings of the session to the release_preferences */ JappPreferences.followZoom = zoom JappPreferences.setFollowAoa(aoa) /** * Disable controls */ jotiMap.uiSettings.setCompassEnabled(false) /** * Remove callback */ jotiMap.setOnCameraMoveStartedListener(null) /** * Move the camera to the before position */ //googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(before)); activeSession = null } } fun onResume() { service?.request = LocationRequest() .setInterval(locationInterval) .setFastestInterval(fastestInterval) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) } fun onPause() { service?.apply { request = standard } } private fun save() { val list1 = smallTailPoints.toArrayList() val list2 = hourTailPoints.toArrayList() val list3 = ArrayList<Pair<LatLng, Long>>() list3.addAll(list2) list3.addAll(list1) list3.sortBy { it.second } AppData.saveObjectAsJsonInBackground(list3, STORAGE_KEY) } fun onDestroy() { marker?.remove() smallTail?.remove() smallTail = null smallTailPoints.clear() hourTail?.remove() hourTailPoints.clear() hourTail = null if (jotiMap != null) { jotiMap = null } if (marker != null) { marker?.remove() marker = null } if (lastLocation != null) { lastLocation = null } if (activeSession != null) { activeSession = null } if (service != null) { service?.setListener(null) service?.remove(this) service = null } snackBarView = null } companion object { private val STORAGE_KEY = "TAIL" private val BUNDLE_KEY = "MovementManager" } } class TailPoints<T>(maxSize:Int) : List<T>{ private var list: ArrayList<T> = ArrayList() private var addedOn: MutableMap<T,Long> = HashMap() private var currentFirst = 0 var onremoveCallback: (T, Long) -> Unit= {element, timeAdded -> } internal var maxSize:Int = maxSize set(value) { rearrangeList() if (value < list.size){ val toRemove = list.subList(value, list.size) for (el in toRemove){ addedOn.remove(el) } list.removeAll(toRemove) } field = value } private fun toListIndex(tailIndex: Int):Int{ return (currentFirst + tailIndex) % maxSize } private fun toTailIndex(listIndex:Int ): Int{ return when { listIndex > currentFirst -> listIndex - currentFirst listIndex < currentFirst -> listIndex + currentFirst else -> 0 } } private fun incrementCurrentFirst() { currentFirst++ if (currentFirst >= maxSize){ currentFirst = 0 } } private fun rearrangeList(){ val first = list.subList(currentFirst, list.size) val second = list.subList(0, currentFirst) val result = ArrayList<T>() result.addAll(first) result.addAll(second) currentFirst = 0 list = result } override fun iterator(): kotlin.collections.Iterator<T> { return Iterator(0) } override val size: Int get() = list.size override fun contains(element: T): Boolean { return list.contains(element) } override fun containsAll(elements: Collection<T>): Boolean { return list.containsAll(elements) } override fun get(index: Int): T { return list[toListIndex(index)] } override fun indexOf(element: T): Int { return toTailIndex(list.indexOf(element)) } override fun isEmpty(): Boolean { return list.isEmpty() } override fun lastIndexOf(element: T): Int { return toTailIndex(list.lastIndexOf(element)) } override fun subList(fromIndex: Int, toIndex: Int): List<T> { val fromIndexList = toListIndex(fromIndex) val toIndexList = toListIndex(toIndex) return when { fromIndexList == toIndexList -> listOf() fromIndexList < toIndexList -> list.subList(fromIndexList, toIndexList) else -> { val result = list.subList(0, toIndexList) result.addAll(list.subList(fromIndexList, maxSize)) result } } } override fun listIterator(): ListIterator<T> { return Iterator(0) } override fun listIterator(index: Int): ListIterator<T> { return Iterator(index) } fun toArrayList():ArrayList<Pair<T, Long>>{ rearrangeList() return ArrayList(list.map {Pair(it, addedOn[it]!!)}) } fun add(element: T): Boolean { if (list.contains(element)){ return false } addedOn[element] = System.currentTimeMillis() return if (list.size < maxSize){ assert(currentFirst == 0) {currentFirst} list.add(element) } else { onremoveCallback(list[currentFirst], addedOn[list[currentFirst]]!!) addedOn.remove(list[currentFirst]) list[currentFirst] = element incrementCurrentFirst() true } } fun clear() { list.clear() addedOn.clear() currentFirst = 0 } fun setPoints(list: List<Pair<T,Long>>) { clear() if (list.size <= maxSize) { this.list.addAll(list.map { it.first }) list.forEach{ addedOn[it.first] = it.second } }else{ val overflow = list.size - maxSize val sublist = list.subList(overflow, list.size) this.list.addAll(sublist.map { it.first }) sublist.forEach { addedOn[it.first] = it.second } } assert(this.list.size <= maxSize) } inner class Iterator(private var currentIndex: Int): ListIterator<T> { override fun hasNext(): Boolean { return currentIndex + 1 < size } override fun next(): T { val nextE = get(currentIndex) currentIndex++ return nextE } override fun hasPrevious(): Boolean { return currentIndex - 1 > maxSize } override fun nextIndex(): Int { return currentIndex + 1 } override fun previous(): T { val prevE = get(currentIndex) currentIndex-- return prevE } override fun previousIndex(): Int { return currentIndex - 1 } } }
apache-2.0
173ec653587cf287cde4c1c3c33e5062
31.167472
167
0.582048
5.067478
false
false
false
false
fgsguedes/notes
app/src/main/java/io/guedes/notes/app/note/list/ui/ListNotesActivity.kt
1
4401
package io.guedes.notes.app.note.list.ui import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Parcelable import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.ItemTouchHelper import com.google.android.material.snackbar.Snackbar import io.guedes.notes.app.R import io.guedes.notes.app.dependencies.provideFactory import io.guedes.notes.app.note.create.ui.CreateNoteActivity import io.guedes.notes.app.note.list.viewmodel.ListNotesViewModel import io.guedes.notes.app.note.list.viewmodel.ListNotesViewModelFactory import io.guedes.notes.domain.model.Note import kotlinx.android.synthetic.main.activity_list_notes.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import io.guedes.notes.app.note.list.ListNotesNavigation as Navigation import io.guedes.notes.app.note.list.ListNotesState as State @FlowPreview @ExperimentalCoroutinesApi class ListNotesActivity : AppCompatActivity(R.layout.activity_list_notes) { private val viewModel: ListNotesViewModel by viewModels { provideFactory<ListNotesViewModelFactory>() } private val adapter by lazy { NotesAdapter() } private val swipeListener by lazy { HorizontalSwipeListener() } private var deleteInProgress: Long = 0 private var undoSnackBar: Snackbar? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initUi(savedInstanceState) initVm() } override fun onSaveInstanceState(outState: Bundle) { outState.putParcelable( KEY_RECYCLER_VIEW_STATE, rvNotes.layoutManager?.onSaveInstanceState() ) super.onSaveInstanceState(outState) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == createNoteRequestCode && resultCode == Activity.RESULT_OK) { viewModel.onNoteCreated() } else super.onActivityResult(requestCode, resultCode, data) } private fun initUi(bundle: Bundle?) { setSupportActionBar(toolbar) ivSorting.setOnClickListener { viewModel.onUpdateSorting() } fabCreateNote.setOnClickListener { viewModel.onCreateNote() } val state = bundle?.getParcelable<Parcelable>(KEY_RECYCLER_VIEW_STATE) if (state != null) rvNotes.layoutManager?.onRestoreInstanceState(state) rvNotes.adapter = adapter ItemTouchHelper(swipeListener).attachToRecyclerView(rvNotes) lifecycleScope.launch(Dispatchers.Default) { launch { swipeListener.swipes().collect { viewModel.onItemSwipe(it) } } launch { adapter.clicks().collect { viewModel.onNoteClick(it) } } } } private fun initVm() { lifecycleScope.launch(Dispatchers.Main) { launch { viewModel.state().collect { onStateChanged(it) } } launch { viewModel.navigation().collect { onNavigation(it) } } } } private fun onStateChanged(state: State) { adapter.submitList(state.notes) if (state.deleteInProgress != 0L) showUndoSnackbar(state.deleteInProgress) else hideUndoSnackbar() } private fun onNavigation(navigation: Navigation) = when (navigation) { is Navigation.NoteForm -> openCreateNoteForm(navigation.note) } private fun showUndoSnackbar(deleteInProgress: Long) { if (this.deleteInProgress == deleteInProgress) return this.deleteInProgress = deleteInProgress undoSnackBar?.dismiss() undoSnackBar = Snackbar.make(clListNotes, "Deleted", Snackbar.LENGTH_INDEFINITE) .setAction("Undo") { viewModel.onUndoDelete(deleteInProgress) } .also { it.show() } } private fun hideUndoSnackbar() { deleteInProgress = 0 undoSnackBar?.dismiss() } private fun openCreateNoteForm(note: Note?) { val intent = CreateNoteActivity.newIntent(this, note) startActivityForResult(intent, createNoteRequestCode) } companion object { const val createNoteRequestCode = 1 const val KEY_RECYCLER_VIEW_STATE = "KEY_RECYCLER_VIEW_STATE" } }
gpl-3.0
f11d9cd210c9a02373b605c9db29b322
34.780488
88
0.723017
4.551189
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/database/table/RPKStoreItemTable.kt
1
6715
/* * Copyright 2022 Ren Binden * * 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.rpkit.store.bukkit.database.table import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.core.plugin.RPKPlugin import com.rpkit.store.bukkit.RPKStoresBukkit import com.rpkit.store.bukkit.database.create import com.rpkit.store.bukkit.database.jooq.Tables.RPKIT_STORE_ITEM import com.rpkit.store.bukkit.storeitem.RPKStoreItem import com.rpkit.store.bukkit.storeitem.RPKStoreItemId import java.util.concurrent.CompletableFuture import java.util.logging.Level class RPKStoreItemTable( private val database: Database, private val plugin: RPKStoresBukkit ) : Table { private val cache = if (plugin.config.getBoolean("caching.rpkit_store_item.id.enabled")) { database.cacheManager.createCache( "rpkit-stores-bukkit.rpkit_store_item.id", Int::class.javaObjectType, RPKStoreItem::class.java, plugin.config.getLong("caching.rpkit_store_item.id.size") ) } else { null } fun insert(entity: RPKStoreItem): CompletableFuture<RPKStoreItemId> { return CompletableFuture.supplyAsync { database.create .insertInto( RPKIT_STORE_ITEM, RPKIT_STORE_ITEM.PLUGIN, RPKIT_STORE_ITEM.IDENTIFIER, RPKIT_STORE_ITEM.DESCRIPTION, RPKIT_STORE_ITEM.COST ) .values( entity.plugin, entity.identifier, entity.description, entity.cost ) .execute() val id = database.create.lastID().toInt() entity.id = RPKStoreItemId(id) cache?.set(id, entity) return@supplyAsync RPKStoreItemId(id) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to insert store item", exception) throw exception } } fun update(entity: RPKStoreItem): CompletableFuture<Void> { val id = entity.id ?: return CompletableFuture.completedFuture(null) return CompletableFuture.runAsync { database.create .update(RPKIT_STORE_ITEM) .set(RPKIT_STORE_ITEM.PLUGIN, entity.plugin) .set(RPKIT_STORE_ITEM.IDENTIFIER, entity.identifier) .set(RPKIT_STORE_ITEM.DESCRIPTION, entity.description) .set(RPKIT_STORE_ITEM.COST, entity.cost) .where(RPKIT_STORE_ITEM.ID.eq(id.value)) .execute() cache?.set(id.value, entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to update store item", exception) throw exception } } operator fun get(id: RPKStoreItemId): CompletableFuture<RPKStoreItem?> { if (cache?.containsKey(id.value) == true) return CompletableFuture.completedFuture(cache[id.value]) return CompletableFuture.supplyAsync { var storeItem: RPKStoreItem? = database.getTable(RPKConsumableStoreItemTable::class.java)[id].join() if (storeItem != null) { cache?.set(id.value, storeItem) return@supplyAsync storeItem } else { cache?.remove(id.value) } storeItem = database.getTable(RPKPermanentStoreItemTable::class.java)[id].join() if (storeItem != null) { cache?.set(id.value, storeItem) return@supplyAsync storeItem } else { cache?.remove(id.value) } storeItem = database.getTable(RPKTimedStoreItemTable::class.java)[id].join() if (storeItem != null) { cache?.set(id.value, storeItem) return@supplyAsync storeItem } else { cache?.remove(id.value) } return@supplyAsync null }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get store item", exception) throw exception } } fun get(plugin: RPKPlugin, identifier: String): CompletableFuture<RPKStoreItem?> { return CompletableFuture.supplyAsync { val result = database.create .select(RPKIT_STORE_ITEM.ID) .from(RPKIT_STORE_ITEM) .where(RPKIT_STORE_ITEM.PLUGIN.eq(plugin.getName())) .and(RPKIT_STORE_ITEM.IDENTIFIER.eq(identifier)) .fetchOne() ?: return@supplyAsync null return@supplyAsync get(RPKStoreItemId(result[RPKIT_STORE_ITEM.ID])).join() }.exceptionally { exception -> this.plugin.logger.log(Level.SEVERE, "Failed to get store item", exception) throw exception } } fun getAll(): CompletableFuture<List<RPKStoreItem>> { return CompletableFuture.supplyAsync { val result = database.create .select(RPKIT_STORE_ITEM.ID) .from(RPKIT_STORE_ITEM) .fetch() val storeItemFutures = result.map { row -> get(RPKStoreItemId(row[RPKIT_STORE_ITEM.ID])) } CompletableFuture.allOf(*storeItemFutures.toTypedArray()).join() return@supplyAsync storeItemFutures.mapNotNull(CompletableFuture<RPKStoreItem?>::join) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get all store items", exception) throw exception } } fun delete(entity: RPKStoreItem): CompletableFuture<Void> { val id = entity.id ?: return CompletableFuture.completedFuture(null) return CompletableFuture.runAsync { database.create .deleteFrom(RPKIT_STORE_ITEM) .where(RPKIT_STORE_ITEM.ID.eq(id.value)) .execute() cache?.remove(id.value) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to delete store item", exception) throw exception } } }
apache-2.0
aaffb272cfb6a78533ce5eb1d42ca314
39.457831
112
0.607595
4.708976
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/wordbook/WordBookView.kt
1
15972
package cn.yiiguxing.plugin.translate.wordbook import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.service.TranslationUIManager import cn.yiiguxing.plugin.translate.ui.Popups import cn.yiiguxing.plugin.translate.ui.wordbook.WordBookPanel import cn.yiiguxing.plugin.translate.ui.wordbook.WordDetailsDialog import cn.yiiguxing.plugin.translate.util.Application import cn.yiiguxing.plugin.translate.util.WordBookService import cn.yiiguxing.plugin.translate.util.assertIsDispatchThread import cn.yiiguxing.plugin.translate.util.executeOnPooledThread import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.JBMenuItem import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.tools.SimpleActionGroup import com.intellij.ui.PopupMenuListenerAdapter import com.intellij.ui.content.ContentManagerEvent import com.intellij.ui.content.ContentManagerListener import com.intellij.util.ui.JBUI import icons.TranslationIcons import java.awt.datatransfer.StringSelection import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import javax.swing.Icon import javax.swing.event.PopupMenuEvent /** * Word book view. */ class WordBookView { private var isInitialized: Boolean = false private val words: MutableList<WordBookItem> = ArrayList() private var groupedWords: Map<String, MutableList<WordBookItem>> = HashMap() private val windows: MutableMap<Project, ToolWindow> = HashMap() private val wordBookPanels: MutableMap<Project, WordBookPanel> = HashMap() fun setup(project: Project, toolWindow: ToolWindow) { assertIsDispatchThread() windows[project] = toolWindow val contentManager = toolWindow.contentManager if (!Application.isUnitTestMode) { (toolWindow as ToolWindowEx).apply { val gearActions = SimpleActionGroup().apply { add(ImportAction()) add(ExportActionGroup()) } setAdditionalGearActions(gearActions) setTitleActions(listOf(RefreshAction(), ShowWordOfTheDayAction())) } } val panel = getWordBookPanel(project) val content = contentManager.factory.createContent(panel, null, false) content.tabName = TAB_NAME_ALL contentManager.addContent(content) contentManager.addContentManagerListener(object : ContentManagerListener { override fun selectionChanged(event: ContentManagerEvent) { val words = if (event.content.tabName == TAB_NAME_ALL) { words } else { groupedWords[event.content.displayName] } wordBookPanels[project]?.apply { setWords(words ?: emptyList()) fireWordsChanged() } } }) contentManager.setSelectedContent(content) if (WordBookService.isInitialized) { refresh() panel.showTable() } else { panel.showMessagePane() } Disposer.register(TranslationUIManager.disposable(project)) { windows.remove(project) wordBookPanels.remove(project) } subscribeWordBookTopic() isInitialized = true } private fun getWordBookPanel(project: Project): WordBookPanel { return wordBookPanels.getOrPut(project) { WordBookPanel().apply { setupKeyListener() setupMenu(project) onWordDoubleClicked { word -> openWordDetails(project, word) } onDownloadDriver { if (!WordBookService.downloadDriver()) { val message = message("wordbook.window.message.in.download") Popups.showBalloonForComponent(it, message, MessageType.INFO, project, JBUI.scale(10)) } } } } } private fun WordBookPanel.setupKeyListener() { tableView.addKeyListener(object : KeyAdapter() { override fun keyPressed(event: KeyEvent) { if (event.keyCode == KeyEvent.VK_DELETE) { deleteWord(selectedWords) event.consume() } } }) } private fun deleteWord(words: List<WordBookItem>) { if (words.isEmpty()) { return } val message = if (words.size == 1) { message("wordbook.window.confirmation.delete.message", words.joinToString { it.word }) } else { message("wordbook.window.confirmation.delete.message.multiple", words.joinToString { it.word }) } val confirmed = Messages.showOkCancelDialog( message, message("wordbook.window.confirmation.delete.title"), Messages.getOkButton(), Messages.getCancelButton(), null ) == Messages.OK if (confirmed) { executeOnPooledThread { WordBookService.removeWords(words.mapNotNull { it.id }) } } } private fun WordBookPanel.setupMenu(project: Project) { val panel = this@setupMenu popupMenu = JBPopupMenu().also { menu -> val detailItem = createMenuItem(message("wordbook.window.menu.detail"), TranslationIcons.Detail) { panel.selectedWord?.let { word -> openWordDetails(project, word) } } val copyItem = createMenuItem(message("wordbook.window.menu.copy"), AllIcons.Actions.Copy) { panel.selectedWord?.let { word -> CopyPasteManager.getInstance().setContents(StringSelection(word.word)) } } val deleteItem = createMenuItem(message("wordbook.window.menu.delete"), AllIcons.Actions.Cancel) { deleteWord(panel.selectedWords) } menu.add(deleteItem) menu.addPopupMenuListener(object : PopupMenuListenerAdapter() { override fun popupMenuWillBecomeVisible(e: PopupMenuEvent) { if (!panel.isMultipleSelection) { menu.add(detailItem, 0) menu.add(copyItem, 1) } else { menu.remove(detailItem) menu.remove(copyItem) } } }) } } private inline fun createMenuItem(text: String, icon: Icon, crossinline action: () -> Unit): JBMenuItem { return JBMenuItem(text, icon).apply { addActionListener { action() } } } private fun subscribeWordBookTopic() { if (!isInitialized) { Application.messageBus .connect(TranslationUIManager.disposable()) .subscribe(WordBookListener.TOPIC, object : WordBookListener { override fun onInitialized(service: WordBookService) { assertIsDispatchThread() showWordBookTable() } override fun onWordAdded(service: WordBookService, wordBookItem: WordBookItem) { assertIsDispatchThread() words.add(wordBookItem) notifyWordsChanged() selectWord(wordBookItem) } override fun onWordUpdated(service: WordBookService, wordBookItem: WordBookItem) { assertIsDispatchThread() val index = words.indexOfFirst { it.id == wordBookItem.id } if (index >= 0) { words[index] = wordBookItem notifyWordsChanged() } } override fun onWordRemoved(service: WordBookService, id: Long) { assertIsDispatchThread() val index = words.indexOfFirst { it.id == id } if (index >= 0) { words.removeAt(index) notifyWordsChanged() } } }) } } private fun refresh() { val newWords = WordBookService.getWords() words.clear() words.addAll(newWords) notifyWordsChanged() } private fun showWordBookTable() { refresh() for ((_, panel) in wordBookPanels) { panel.showTable() } } private fun notifyWordsChanged() { updateGroupedWords() for ((project, toolWindow) in windows) { updateContent(project, toolWindow) } } private fun updateGroupedWords() { val newGroupedWords = HashMap<String, MutableList<WordBookItem>>() for (word in words) { for (tag in word.tags) { if (tag.isNotEmpty()) { newGroupedWords.getOrPut(tag) { ArrayList() } += word } } } groupedWords = newGroupedWords.toSortedMap() } private fun selectWord(wordBookItem: WordBookItem) { for ((_, toolWindow) in windows) { val contentManager = toolWindow.contentManager val allContent = contentManager.contents.find { it.tabName == TAB_NAME_ALL } ?: continue if (contentManager.selectedContent != allContent) { contentManager.setSelectedContent(allContent) } (allContent.component as? WordBookPanel)?.selectWord(wordBookItem) } } private fun updateContent(project: Project, toolWindow: ToolWindow) { if (project.isDisposed) { return } val groupedWords = groupedWords val contentManager = toolWindow.contentManager if (contentManager.isDisposed) { return } val allContent = contentManager.getContent(0)!! val groupedContents = contentManager.contents.let { contents -> if (contents.size > 1) contents.copyOfRange(1, contents.size) else emptyArray() } var selectedContent = contentManager.selectedContent if (groupedWords.isEmpty()) { allContent.displayName = null allContent.tabName = TAB_NAME_ALL for (content in groupedContents) { contentManager.removeContent(content, true) } contentManager.setSelectedContent(allContent) selectedContent = allContent } else { allContent.displayName = message("wordbook.window.ui.tab.title.all") allContent.tabName = TAB_NAME_ALL val keys = groupedWords.keys val livingContents = ArrayList<String>() for (content in groupedContents) { val isDead = content.displayName !in keys if (isDead) { contentManager.removeContent(content, true) if (selectedContent === content) { selectedContent = null } } else { livingContents += content.displayName } } val factory = contentManager.factory for (name in groupedWords.keys) { val index = livingContents.binarySearch(name) if (index < 0) { val insertIndex = -index - 1 livingContents.add(insertIndex, name) val content = factory.createContent(getWordBookPanel(project), name, false) contentManager.addContent(content, insertIndex + 1) } } selectedContent = selectedContent ?: allContent contentManager.setSelectedContent(selectedContent) } val wordsToDisplay = if (selectedContent === allContent) { words } else { groupedWords[selectedContent.displayName] ?: words } getWordBookPanel(project).apply { setWords(wordsToDisplay) fireWordsChanged() } } private fun openWordDetails(project: Project?, word: WordBookItem) { WordDetailsDialog(project, word, groupedWords.keys).show() } private abstract inner class WordBookAction(text: String, description: String? = text, icon: Icon? = null) : DumbAwareAction(text, description, icon) { final override fun actionPerformed(e: AnActionEvent) { if (WordBookService.isInitialized) { doAction(e) } else { Popups.showBalloonForComponent( e.inputEvent.component, message("wordbook.window.message.missing.driver"), MessageType.INFO, e.project, offsetY = 1 ) } } protected abstract fun doAction(e: AnActionEvent) } private inner class RefreshAction : WordBookAction( message("wordbook.window.action.refresh"), message("wordbook.window.action.refresh.desc"), AllIcons.Actions.Refresh ) { override fun doAction(e: AnActionEvent) = refresh() } private inner class ShowWordOfTheDayAction : WordBookAction( message("word.of.the.day.title"), null, AllIcons.Actions.IntentionBulb ) { override fun doAction(e: AnActionEvent) { val project = e.project if (words.isNotEmpty()) { windows[project]?.hide { TranslationUIManager.showWordOfTheDayDialog(project, words.shuffled()) } } else { Popups.showBalloonForComponent( e.inputEvent.component, message("wordbook.window.message.empty"), MessageType.INFO, project, offsetY = 1 ) } } } private inner class ImportAction : WordBookAction(message("wordbook.window.action.import")) { override fun update(e: AnActionEvent) { e.presentation.isEnabled = WordBookService.isInitialized } override fun doAction(e: AnActionEvent) = importWordBook(e.project) } private inner class ExportAction(private val exporter: WordBookExporter) : WordBookAction("${exporter.name}${if (exporter.availableForImport) message("wordbook.window.export.tip") else ""}") { override fun update(e: AnActionEvent) { e.presentation.isEnabled = WordBookService.isInitialized } override fun doAction(e: AnActionEvent) = exporter.export(e.project, words) } private inner class ExportActionGroup : ActionGroup(message("wordbook.window.action.export"), true), DumbAware { private val actions: Array<AnAction> = WORD_BOOK_EXPORTERS.map { ExportAction(it) }.toTypedArray() override fun getChildren(e: AnActionEvent?): Array<AnAction> = actions } companion object { private const val TAB_NAME_ALL = "ALL" val instance: WordBookView get() = ApplicationManager.getApplication().getService(WordBookView::class.java) } }
mit
ce8e6ba542e4bcdae89a2cbdb188af74
36.495305
125
0.592725
5.152258
false
false
false
false
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/advancefunction/19.闭包.kt
1
1769
package com.zj.example.kotlin.advancefunction /** * 闭包: * 1.函数的运行环境 * 2.持有函数的运行状态 * 3.黑叔内部可以定义函数 * 4.函数内部也可以定义类 * * Created by zhengjiong * date: 2017/9/24 10:43 */ fun main(vararg args: String) { val f = makeFun() f()//1 f()//2 f()//3 println("-------------------") var list = test1() for (it in list) { println(it) } println("-------------------") var x = add(1) println(x(2))//3 println(add(1)(2))//3 } fun makeFun(): () -> Unit { /** * 执行f()的时候, makeFun函数的作用域并没有被释放掉, count还是继续存在 */ var count = 0 return fun() { println(++count) } } fun test1(): Iterable<Long> { /** * Iterable构造函数接收的是一个lambda表达式:() -> Iterator<T>, * 返回一个Iterator接口, 所以可以直接返回实现了该接口的一个匿名内部类 */ return Iterable { -> object : LongIterator() { var next: Long = 0 override fun hasNext(): Boolean { if (next < 10) { next++ return true } else { return false } } override fun nextLong(): Long { return next } } } } /** * 闭包函数完整写法 * 简写看20.闭包简写.kt */ fun add(x: Int): (Int) -> Int { return fun(y: Int): Int { return x + y } } /** * 1.匿名闭包函数完整写法 */ var anonyAdd1 = fun(x: Int): (Int) -> Int { var innerAnonyAdd1 = fun(y: Int): Int { return x + y } return innerAnonyAdd1 }
mit
7dc92c239a7a0c8cacaf75c9884796e5
16
53
0.459352
3.232906
false
false
false
false
android/user-interface-samples
DownloadableFonts/app/src/main/java/com/example/android/downloadablefonts/MainActivity.kt
1
10042
/* * Copyright (C) 2017 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.android.downloadablefonts import android.graphics.Typeface import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.View import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.CheckBox import android.widget.ProgressBar import android.widget.SeekBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.collection.ArraySet import androidx.core.provider.FontRequest import androidx.core.provider.FontsContractCompat import com.example.android.downloadablefonts.Constants.ITALIC_DEFAULT import com.example.android.downloadablefonts.Constants.WEIGHT_DEFAULT import com.example.android.downloadablefonts.Constants.WEIGHT_MAX import com.example.android.downloadablefonts.Constants.WIDTH_DEFAULT import com.example.android.downloadablefonts.Constants.WIDTH_MAX import com.google.android.material.textfield.TextInputLayout class MainActivity : AppCompatActivity() { private lateinit var handler: Handler private lateinit var downloadableFontTextView: TextView private lateinit var widthSeekBar: SeekBar private lateinit var weightSeekBar: SeekBar private lateinit var italicSeekBar: SeekBar private lateinit var bestEffort: CheckBox private lateinit var requestDownloadButton: Button private lateinit var familyNameSet: ArraySet<String> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val handlerThread = HandlerThread("fonts") handlerThread.start() handler = Handler(handlerThread.looper) initializeSeekBars() familyNameSet = ArraySet<String>() familyNameSet.addAll(listOf(*resources.getStringArray(R.array.family_names))) downloadableFontTextView = findViewById(R.id.textview) val adapter = ArrayAdapter( this, android.R.layout.simple_dropdown_item_1line, resources.getStringArray(R.array.family_names) ) val familyNameInput = findViewById<TextInputLayout>(R.id.auto_complete_family_name_input) val autoCompleteFamilyName = findViewById<AutoCompleteTextView>(R.id.auto_complete_family_name) autoCompleteFamilyName.setAdapter<ArrayAdapter<String>>(adapter) autoCompleteFamilyName.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( charSequence: CharSequence, start: Int, count: Int, after: Int ) { // No op } override fun onTextChanged( charSequence: CharSequence, start: Int, count: Int, after: Int ) { if (isValidFamilyName(charSequence.toString())) { familyNameInput.isErrorEnabled = false familyNameInput.error = "" } else { familyNameInput.isErrorEnabled = true familyNameInput.error = getString(R.string.invalid_family_name) } } override fun afterTextChanged(editable: Editable) { // No op } }) requestDownloadButton = findViewById(R.id.button_request) requestDownloadButton.setOnClickListener(View.OnClickListener { val familyName = autoCompleteFamilyName.text.toString() if (!isValidFamilyName(familyName)) { familyNameInput.isErrorEnabled = true familyNameInput.error = getString(R.string.invalid_family_name) Toast.makeText( this@MainActivity, R.string.invalid_input, Toast.LENGTH_SHORT ).show() return@OnClickListener } requestDownload(familyName) requestDownloadButton.isEnabled = false }) bestEffort = findViewById(R.id.checkbox_best_effort) } private fun requestDownload(familyName: String) { val queryBuilder = QueryBuilder( familyName, width = progressToWidth(widthSeekBar.progress), weight = progressToWeight(weightSeekBar.progress), italic = progressToItalic(italicSeekBar.progress), bestEffort = bestEffort.isChecked ) val query = queryBuilder.build() Log.d(TAG, "Requesting a font. Query: $query") val request = FontRequest( "com.google.android.gms.fonts", "com.google.android.gms", query, R.array.com_google_android_gms_fonts_certs ) val progressBar = findViewById<ProgressBar>(R.id.progressBar) progressBar.visibility = View.VISIBLE val callback = object : FontsContractCompat.FontRequestCallback() { override fun onTypefaceRetrieved(typeface: Typeface) { downloadableFontTextView.typeface = typeface progressBar.visibility = View.GONE requestDownloadButton.isEnabled = true } override fun onTypefaceRequestFailed(reason: Int) { Toast.makeText( this@MainActivity, getString(R.string.request_failed, reason), Toast.LENGTH_LONG ) .show() progressBar.visibility = View.GONE requestDownloadButton.isEnabled = true } } FontsContractCompat .requestFont(this@MainActivity, request, callback, handler) } private fun initializeSeekBars() { widthSeekBar = findViewById(R.id.seek_bar_width) val widthValue = (100 * WIDTH_DEFAULT.toFloat() / WIDTH_MAX.toFloat()).toInt() widthSeekBar.progress = widthValue val widthTextView = findViewById<TextView>(R.id.textview_width) widthTextView.text = widthValue.toString() widthSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { widthTextView.text = progressToWidth(progress).toString() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) weightSeekBar = findViewById(R.id.seek_bar_weight) val weightValue = WEIGHT_DEFAULT.toFloat() / WEIGHT_MAX.toFloat() * 100 weightSeekBar.progress = weightValue.toInt() val weightTextView = findViewById<TextView>(R.id.textview_weight) weightTextView.text = WEIGHT_DEFAULT.toString() weightSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { weightTextView.text = progressToWeight(progress).toString() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) italicSeekBar = findViewById<SeekBar>(R.id.seek_bar_italic) italicSeekBar.progress = ITALIC_DEFAULT.toInt() val italicTextView = findViewById<TextView>(R.id.textview_italic) italicTextView.text = ITALIC_DEFAULT.toString() italicSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { italicTextView.text = progressToItalic(progress).toString() } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) } private fun isValidFamilyName(familyName: String?) = familyName != null && familyNameSet.contains(familyName) /** * Converts progress from a SeekBar to the value of width. * @param progress is passed from 0 to 100 inclusive * * * @return the converted width */ private fun progressToWidth(progress: Int): Float { return (if (progress == 0) 1 else progress * WIDTH_MAX / 100).toFloat() } /** * Converts progress from a SeekBar to the value of weight. * @param progress is passed from 0 to 100 inclusive * * * @return the converted weight */ private fun progressToWeight(progress: Int) = when (progress) { 0 -> { 1 // The range of the weight is between (0, 1000) (exclusive) } 100 -> { WEIGHT_MAX - 1 // The range of the weight is between (0, 1000) (exclusive) } else -> { WEIGHT_MAX * progress / 100 } } /** * Converts progress from a SeekBar to the value of italic. * @param progress is passed from 0 to 100 inclusive. * * * @return the converted italic */ private fun progressToItalic(progress: Int): Float { return progress.toFloat() / 100f } companion object { private const val TAG = "MainActivity" } }
apache-2.0
ccb3a8091685674a1d9f117772b93b42
37.772201
97
0.654252
5.043697
false
false
false
false
MaibornWolff/codecharta
analysis/import/SourceCodeParser/src/main/kotlin/de/maibornwolff/codecharta/importer/sourcecodeparser/ProjectTraverser.kt
1
2108
package de.maibornwolff.codecharta.importer.sourcecodeparser import org.sonar.api.internal.apachecommons.io.FilenameUtils import java.io.File import java.nio.file.Paths class ProjectTraverser(var root: File, private val exclude: Array<String> = arrayOf()) { private var fileList: MutableList<File> = mutableListOf() private val analyzerFileLists: MutableMap<String, MutableList<String>>? = HashMap() fun traverse() { val excludePatterns = exclude.joinToString(separator = "|", prefix = "(", postfix = ")").toRegex() root.walk().forEach { val standardizedPath = "/" + getRelativeFileName(it.toString()) if (it.isFile && !(exclude.isNotEmpty() && excludePatterns.containsMatchIn(standardizedPath))) { fileList.add(it) } } adjustRootFolderIfRootIsFile() assignFilesToAnalyzers() } private fun assignFilesToAnalyzers() { for (file in this.fileList) { val fileName = getRelativeFileName(file.toString()) val fileExtension = FilenameUtils.getExtension(fileName) if (!this.analyzerFileLists!!.containsKey(fileExtension)) { val fileListForType: MutableList<String> = mutableListOf() fileListForType.add(fileName) this.analyzerFileLists[fileExtension] = fileListForType } else { this.analyzerFileLists[fileExtension]!!.add(fileName) } } } fun getFileListByExtension(type: String): List<String> { return if (this.analyzerFileLists!!.containsKey(type)) { this.analyzerFileLists[type] ?: listOf() } else { ArrayList() } } private fun getRelativeFileName(fileName: String): String { return root.toPath().toAbsolutePath() .relativize(Paths.get(fileName).toAbsolutePath()) .toString() .replace('\\', '/') } private fun adjustRootFolderIfRootIsFile() { if (root.isFile) { root = root.absoluteFile.parentFile } } }
bsd-3-clause
b8e5978ffd2797afc1c46708e02a81ba
34.133333
108
0.622391
4.845977
false
false
false
false
signed/intellij-community
uast/uast-common/src/org/jetbrains/uast/UastUtils.kt
1
5616
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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. */ @file:JvmMultifileClass @file:JvmName("UastUtils") package org.jetbrains.uast import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.PsiTreeUtil import java.io.File inline fun <reified T : UElement> UElement.getParentOfType(strict: Boolean = true): T? = getParentOfType(T::class.java, strict) @JvmOverloads fun <T : UElement> UElement.getParentOfType(parentClass: Class<out UElement>, strict: Boolean = true): T? { var element = (if (strict) uastParent else this) ?: return null while (true) { if (parentClass.isInstance(element)) { @Suppress("UNCHECKED_CAST") return element as T } element = element.uastParent ?: return null } } fun <T : UElement> UElement.getParentOfType( parentClass: Class<out UElement>, strict: Boolean = true, vararg terminators: Class<out UElement> ): T? { var element = (if (strict) uastParent else this) ?: return null while (true) { if (parentClass.isInstance(element)) { @Suppress("UNCHECKED_CAST") return element as T } if (terminators.any { it.isInstance(element) }) { return null } element = element.uastParent ?: return null } } fun <T : UElement> UElement.getParentOfType( strict: Boolean = true, firstParentClass: Class<out T>, vararg parentClasses: Class<out T> ): T? { var element = (if (strict) uastParent else this) ?: return null while (true) { if (firstParentClass.isInstance(element)) { @Suppress("UNCHECKED_CAST") return element as T } if (parentClasses.any { it.isInstance(element) }) { @Suppress("UNCHECKED_CAST") return element as T } element = element.uastParent ?: return null } } fun UElement.getContainingFile() = getParentOfType<UFile>(UFile::class.java) fun UElement.getContainingUClass() = getParentOfType<UClass>(UClass::class.java) fun UElement.getContainingUMethod() = getParentOfType<UMethod>(UMethod::class.java) fun UElement.getContainingUVariable() = getParentOfType<UVariable>(UVariable::class.java) fun UElement.getContainingMethod() = getContainingUMethod()?.psi fun UElement.getContainingClass() = getContainingUClass()?.psi fun UElement.getContainingVariable() = getContainingUVariable()?.psi fun PsiElement?.getContainingClass() = this?.let { PsiTreeUtil.getParentOfType(it, PsiClass::class.java) } fun UElement.isChildOf(probablyParent: UElement?, strict: Boolean = false): Boolean { tailrec fun isChildOf(current: UElement?, probablyParent: UElement): Boolean { return when (current) { null -> false probablyParent -> true else -> isChildOf(current.uastParent, probablyParent) } } if (probablyParent == null) return false return isChildOf(if (strict) this else uastParent, probablyParent) } /** * Resolves the receiver element if it implements [UResolvable]. * * @return the resolved element, or null if the element was not resolved, or if the receiver element is not an [UResolvable]. */ fun UElement.tryResolve(): PsiElement? = (this as? UResolvable)?.resolve() fun UElement.tryResolveNamed(): PsiNamedElement? = (this as? UResolvable)?.resolve() as? PsiNamedElement fun UElement.tryResolveUDeclaration(context: UastContext): UDeclaration? { return (this as? UResolvable)?.resolve()?.let { context.convertElementWithParent(it, null) as? UDeclaration } } fun UReferenceExpression?.getQualifiedName() = (this?.resolve() as? PsiClass)?.qualifiedName /** * Returns the String expression value, or null if the value can't be calculated or if the calculated value is not a String. */ fun UExpression.evaluateString(): String? = evaluate() as? String /** * Get a physical [File] for this file, or null if there is no such file on disk. */ fun UFile.getIoFile(): File? = psi.virtualFile?.let { VfsUtilCore.virtualToIoFile(it) } tailrec fun UElement.getUastContext(): UastContext { val psi = this.psi if (psi != null) { return ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found") } return (uastParent ?: error("PsiElement should exist at least for UFile")).getUastContext() } tailrec fun UElement.getLanguagePlugin(): UastLanguagePlugin { val psi = this.psi if (psi != null) { val uastContext = ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found") return uastContext.findPlugin(psi) ?: error("Language plugin was not found for $this (${this.javaClass.name})") } return (uastParent ?: error("PsiElement should exist at least for UFile")).getLanguagePlugin() } fun Collection<UElement>.toPsiElements() = mapNotNull { it.psi }
apache-2.0
46e9f76507d6f217a252fb8528ad2dab
36.945946
127
0.69943
4.353488
false
false
false
false
STUDIO-apps/GeoShare_Android
mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/profile/staticmap/ProfileStaticMapInteractorImpl.kt
1
1347
package uk.co.appsbystudio.geoshare.friends.profile.staticmap import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import uk.co.appsbystudio.geoshare.utils.firebase.DatabaseLocations import uk.co.appsbystudio.geoshare.utils.firebase.FirebaseHelper class ProfileStaticMapInteractorImpl: ProfileStaticMapInteractor { override fun getLocation(uid: String, listener: ProfileStaticMapInteractor.OnFirebaseListener) { val user = FirebaseAuth.getInstance().currentUser if (user != null) { val location = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val location = dataSnapshot.getValue(DatabaseLocations::class.java) if (location != null) listener.setImage(location) } override fun onCancelled(databaseError: DatabaseError) { listener.error(databaseError.message) } } FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.CURRENT_LOCATION}/${user.uid}/$uid").addListenerForSingleValueEvent(location) } } }
apache-2.0
5d3126bfe0c7fad9a1c5e82c40ff61a3
42.483871
154
0.715664
5.30315
false
false
false
false
vanniktech/Emoji
emoji-google-compat/src/commonMain/kotlin/com/vanniktech/emoji/googlecompat/category/SmileysAndPeopleCategoryChunk1.kt
1
50442
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić 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 * * 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.vanniktech.emoji.googlecompat.category import com.vanniktech.emoji.googlecompat.GoogleCompatEmoji internal object SmileysAndPeopleCategoryChunk1 { internal val EMOJIS: List<GoogleCompatEmoji> = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F640), 0, 1), listOf("scream_cat"), false), GoogleCompatEmoji(String(intArrayOf(0x1F63F), 0, 1), listOf("crying_cat_face"), false), GoogleCompatEmoji(String(intArrayOf(0x1F63E), 0, 1), listOf("pouting_cat"), false), GoogleCompatEmoji(String(intArrayOf(0x1F648), 0, 1), listOf("see_no_evil"), false), GoogleCompatEmoji(String(intArrayOf(0x1F649), 0, 1), listOf("hear_no_evil"), false), GoogleCompatEmoji(String(intArrayOf(0x1F64A), 0, 1), listOf("speak_no_evil"), false), GoogleCompatEmoji(String(intArrayOf(0x1F48B), 0, 1), listOf("kiss"), false), GoogleCompatEmoji(String(intArrayOf(0x1F48C), 0, 1), listOf("love_letter"), false), GoogleCompatEmoji(String(intArrayOf(0x1F498), 0, 1), listOf("cupid"), false), GoogleCompatEmoji(String(intArrayOf(0x1F49D), 0, 1), listOf("gift_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F496), 0, 1), listOf("sparkling_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F497), 0, 1), listOf("heartpulse"), false), GoogleCompatEmoji(String(intArrayOf(0x1F493), 0, 1), listOf("heartbeat"), false), GoogleCompatEmoji(String(intArrayOf(0x1F49E), 0, 1), listOf("revolving_hearts"), false), GoogleCompatEmoji(String(intArrayOf(0x1F495), 0, 1), listOf("two_hearts"), false), GoogleCompatEmoji(String(intArrayOf(0x1F49F), 0, 1), listOf("heart_decoration"), false), GoogleCompatEmoji(String(intArrayOf(0x2763, 0xFE0F), 0, 2), listOf("heavy_heart_exclamation_mark_ornament"), false), GoogleCompatEmoji(String(intArrayOf(0x1F494), 0, 1), listOf("broken_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x2764, 0xFE0F, 0x200D, 0x1F525), 0, 4), listOf("heart_on_fire"), false), GoogleCompatEmoji(String(intArrayOf(0x2764, 0xFE0F, 0x200D, 0x1FA79), 0, 4), listOf("mending_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x2764, 0xFE0F), 0, 2), listOf("heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F9E1), 0, 1), listOf("orange_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F49B), 0, 1), listOf("yellow_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F49A), 0, 1), listOf("green_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F499), 0, 1), listOf("blue_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F49C), 0, 1), listOf("purple_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F90E), 0, 1), listOf("brown_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F5A4), 0, 1), listOf("black_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F90D), 0, 1), listOf("white_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4AF), 0, 1), listOf("100"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4A2), 0, 1), listOf("anger"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4A5), 0, 1), listOf("boom", "collision"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4AB), 0, 1), listOf("dizzy"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4A6), 0, 1), listOf("sweat_drops"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4A8), 0, 1), listOf("dash"), false), GoogleCompatEmoji(String(intArrayOf(0x1F573, 0xFE0F), 0, 2), listOf("hole"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4A3), 0, 1), listOf("bomb"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4AC), 0, 1), listOf("speech_balloon"), false), GoogleCompatEmoji(String(intArrayOf(0x1F441, 0xFE0F, 0x200D, 0x1F5E8, 0xFE0F), 0, 5), listOf("eye-in-speech-bubble"), false), GoogleCompatEmoji(String(intArrayOf(0x1F5E8, 0xFE0F), 0, 2), listOf("left_speech_bubble"), false), GoogleCompatEmoji(String(intArrayOf(0x1F5EF, 0xFE0F), 0, 2), listOf("right_anger_bubble"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4AD), 0, 1), listOf("thought_balloon"), false), GoogleCompatEmoji(String(intArrayOf(0x1F4A4), 0, 1), listOf("zzz"), false), GoogleCompatEmoji( String(intArrayOf(0x1F44B), 0, 1), listOf("wave"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F44B, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44B, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44B, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44B, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44B, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F91A), 0, 1), listOf("raised_back_of_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F91A, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91A, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91A, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91A, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91A, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F590, 0xFE0F), 0, 2), listOf("raised_hand_with_fingers_splayed"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F590, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F590, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F590, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F590, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F590, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x270B), 0, 1), listOf("hand", "raised_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x270B, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270B, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270B, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270B, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270B, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F596), 0, 1), listOf("spock-hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F596, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F596, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F596, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F596, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F596, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1FAF1), 0, 1), listOf("rightwards_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1FAF2), 0, 1), listOf("leftwards_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1FAF2, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF2, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF2, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF2, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF2, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1FAF3), 0, 1), listOf("palm_down_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1FAF3, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF3, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF3, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF3, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF3, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1FAF4), 0, 1), listOf("palm_up_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1FAF4, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF4, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF4, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF4, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF4, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F44C), 0, 1), listOf("ok_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F44C, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44C, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44C, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44C, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44C, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F90C), 0, 1), listOf("pinched_fingers"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F90C, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F90C, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F90C, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F90C, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F90C, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F90F), 0, 1), listOf("pinching_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F90F, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F90F, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F90F, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F90F, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F90F, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x270C, 0xFE0F), 0, 2), listOf("v"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x270C, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270C, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270C, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270C, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270C, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F91E), 0, 1), listOf("crossed_fingers", "hand_with_index_and_middle_fingers_crossed"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F91E, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91E, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91E, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91E, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91E, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1FAF0), 0, 1), listOf("hand_with_index_finger_and_thumb_crossed"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1FAF0, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF0, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF0, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF0, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF0, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F91F), 0, 1), listOf("i_love_you_hand_sign"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F91F, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91F, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91F, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91F, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91F, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F918), 0, 1), listOf("the_horns", "sign_of_the_horns"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F918, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F918, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F918, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F918, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F918, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F919), 0, 1), listOf("call_me_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F919, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F919, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F919, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F919, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F919, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F448), 0, 1), listOf("point_left"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F448, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F448, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F448, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F448, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F448, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F449), 0, 1), listOf("point_right"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F449, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F449, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F449, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F449, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F449, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F446), 0, 1), listOf("point_up_2"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F446, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F446, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F446, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F446, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F446, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F595), 0, 1), listOf("middle_finger", "reversed_hand_with_middle_finger_extended"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F595, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F595, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F595, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F595, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F595, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F447), 0, 1), listOf("point_down"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F447, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F447, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F447, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F447, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F447, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x261D, 0xFE0F), 0, 2), listOf("point_up"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x261D, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x261D, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x261D, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x261D, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x261D, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1FAF5), 0, 1), listOf("index_pointing_at_the_viewer"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1FAF5, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF5, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF5, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF5, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF5, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F44D), 0, 1), listOf("+1", "thumbsup"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F44D, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44D, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44D, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44D, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44D, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F44E), 0, 1), listOf("-1", "thumbsdown"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F44E, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44E, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44E, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44E, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44E, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x270A), 0, 1), listOf("fist"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x270A, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270A, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270A, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270A, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270A, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F44A), 0, 1), listOf("facepunch", "punch"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F44A, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44A, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44A, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44A, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44A, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F91B), 0, 1), listOf("left-facing_fist"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F91B, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91B, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91B, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91B, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91B, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F91C), 0, 1), listOf("right-facing_fist"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F91C, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91C, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91C, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91C, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91C, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F44F), 0, 1), listOf("clap"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F44F, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44F, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44F, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44F, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F44F, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F64C), 0, 1), listOf("raised_hands"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F64C, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F64C, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F64C, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F64C, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F64C, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1FAF6), 0, 1), listOf("heart_hands"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1FAF6, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF6, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF6, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF6, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF6, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F450), 0, 1), listOf("open_hands"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F450, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F450, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F450, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F450, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F450, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F932), 0, 1), listOf("palms_up_together"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F932, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F932, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F932, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F932, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F932, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F91D), 0, 1), listOf("handshake"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F91D, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91D, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91D, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91D, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F91D, 0x1F3FF), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB, 0x200D, 0x1FAF2, 0x1F3FC), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB, 0x200D, 0x1FAF2, 0x1F3FD), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB, 0x200D, 0x1FAF2, 0x1F3FE), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FB, 0x200D, 0x1FAF2, 0x1F3FF), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC, 0x200D, 0x1FAF2, 0x1F3FB), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC, 0x200D, 0x1FAF2, 0x1F3FD), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC, 0x200D, 0x1FAF2, 0x1F3FE), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FC, 0x200D, 0x1FAF2, 0x1F3FF), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD, 0x200D, 0x1FAF2, 0x1F3FB), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD, 0x200D, 0x1FAF2, 0x1F3FC), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD, 0x200D, 0x1FAF2, 0x1F3FE), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FD, 0x200D, 0x1FAF2, 0x1F3FF), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE, 0x200D, 0x1FAF2, 0x1F3FB), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE, 0x200D, 0x1FAF2, 0x1F3FC), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE, 0x200D, 0x1FAF2, 0x1F3FD), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FE, 0x200D, 0x1FAF2, 0x1F3FF), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF, 0x200D, 0x1FAF2, 0x1F3FB), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF, 0x200D, 0x1FAF2, 0x1F3FC), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF, 0x200D, 0x1FAF2, 0x1F3FD), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1FAF1, 0x1F3FF, 0x200D, 0x1FAF2, 0x1F3FE), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F64F), 0, 1), listOf("pray"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F64F, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F64F, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F64F, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F64F, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F64F, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x270D, 0xFE0F), 0, 2), listOf("writing_hand"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x270D, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270D, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270D, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270D, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x270D, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F485), 0, 1), listOf("nail_care"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F485, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F485, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F485, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F485, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F485, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F933), 0, 1), listOf("selfie"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F933, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F933, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F933, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F933, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F933, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F4AA), 0, 1), listOf("muscle"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F4AA, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F4AA, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F4AA, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F4AA, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F4AA, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji(String(intArrayOf(0x1F9BE), 0, 1), listOf("mechanical_arm"), false), GoogleCompatEmoji(String(intArrayOf(0x1F9BF), 0, 1), listOf("mechanical_leg"), false), GoogleCompatEmoji( String(intArrayOf(0x1F9B5), 0, 1), listOf("leg"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9B5, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B5, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B5, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B5, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B5, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9B6), 0, 1), listOf("foot"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9B6, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B6, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B6, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B6, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B6, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F442), 0, 1), listOf("ear"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F442, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F442, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F442, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F442, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F442, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9BB), 0, 1), listOf("ear_with_hearing_aid"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9BB, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9BB, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9BB, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9BB, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9BB, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F443), 0, 1), listOf("nose"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F443, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F443, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F443, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F443, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F443, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji(String(intArrayOf(0x1F9E0), 0, 1), listOf("brain"), false), GoogleCompatEmoji(String(intArrayOf(0x1FAC0), 0, 1), listOf("anatomical_heart"), false), GoogleCompatEmoji(String(intArrayOf(0x1FAC1), 0, 1), listOf("lungs"), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B7), 0, 1), listOf("tooth"), false), GoogleCompatEmoji(String(intArrayOf(0x1F9B4), 0, 1), listOf("bone"), false), GoogleCompatEmoji(String(intArrayOf(0x1F440), 0, 1), listOf("eyes"), false), GoogleCompatEmoji(String(intArrayOf(0x1F441, 0xFE0F), 0, 2), listOf("eye"), false), GoogleCompatEmoji(String(intArrayOf(0x1F445), 0, 1), listOf("tongue"), false), GoogleCompatEmoji(String(intArrayOf(0x1F444), 0, 1), listOf("lips"), false), GoogleCompatEmoji(String(intArrayOf(0x1FAE6), 0, 1), listOf("biting_lip"), false), GoogleCompatEmoji( String(intArrayOf(0x1F476), 0, 1), listOf("baby"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F476, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F476, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F476, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F476, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F476, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D2), 0, 1), listOf("child"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D2, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D2, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D2, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D2, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D2, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F466), 0, 1), listOf("boy"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F466, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F466, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F466, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F466, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F466, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F467), 0, 1), listOf("girl"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F467, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F467, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F467, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F467, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F467, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D1), 0, 1), listOf("adult"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F471), 0, 1), listOf("person_with_blond_hair"), true, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F471, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F471, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F471, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F471, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F471, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F468), 0, 1), listOf("man"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D4), 0, 1), listOf("bearded_person"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_with_beard"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_with_beard"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9B0), 0, 3), listOf("red_haired_man"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9B1), 0, 3), listOf("curly_haired_man"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9B3), 0, 3), listOf("white_haired_man"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9B3), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F468, 0x200D, 0x1F9B2), 0, 3), listOf("bald_man"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9B2), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F469), 0, 1), listOf("woman"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FB), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FC), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FD), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FE), 0, 2), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FF), 0, 2), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9B0), 0, 3), listOf("red_haired_woman"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F9D1, 0x200D, 0x1F9B0), 0, 3), listOf("red_haired_person"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9B0), 0, 4), emptyList<String>(), false), ), ), GoogleCompatEmoji( String(intArrayOf(0x1F469, 0x200D, 0x1F9B1), 0, 3), listOf("curly_haired_woman"), false, variants = listOf( GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), GoogleCompatEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9B1), 0, 4), emptyList<String>(), false), ), ), ) }
apache-2.0
754acf7c5578790944b0c10caeb2b544
66.343124
129
0.679718
3.010984
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/map/annotation/MapAnnotation.kt
1
3496
package mil.nga.giat.mage.map.annotation import android.content.Context import android.graphics.Bitmap import android.net.Uri import com.bumptech.glide.load.Transformation import mil.nga.giat.mage.data.feed.ItemWithFeed import mil.nga.giat.mage.network.Server import mil.nga.giat.mage.sdk.datastore.location.Location import mil.nga.giat.mage.sdk.datastore.observation.Observation import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeature import mil.nga.giat.mage.sdk.datastore.user.User import mil.nga.sf.Geometry import java.io.File data class MapAnnotation<T>( val id: T, val layer: String, val geometry: Geometry, val timestamp: Long? = null, val accuracy: Float? = null, val style: AnnotationStyle? = null, val allowEmptyIcon: Boolean = false, val iconTransformations: List<Transformation<Bitmap>> = mutableListOf(), ) { companion object { fun fromObservationProperties( id: Long, geometry: Geometry, timestamp: Long, accuracy: Float?, eventId: String, formId: Long?, primary: String?, secondary: String?, context: Context ): MapAnnotation<Long> { return MapAnnotation( id = id, layer = "observation", geometry = geometry, timestamp = timestamp, accuracy = accuracy, style = IconStyle.fromObservationProperties(eventId, formId, primary, secondary, context) ) } fun fromObservation(observation: Observation, context: Context): MapAnnotation<Long> { return MapAnnotation( id = observation.id, layer = "observation", geometry = observation.geometry, timestamp = observation.timestamp.time, accuracy = observation.accuracy, style = AnnotationStyle.fromObservation(observation, context) ) } fun fromUser(user: User, location: Location): MapAnnotation<Long> { val iconPath = if (user.iconPath != null) { File(user.iconPath) } else null val iconUri = iconPath?.let { Uri.fromFile(it) } val accuracy = location.propertiesMap["accuracy"]?.value?.toString()?.toFloatOrNull() return MapAnnotation( id = location.id, layer = "location", geometry = location.geometry, timestamp = location.timestamp.time, accuracy = accuracy, style = IconStyle(iconUri), allowEmptyIcon = true ) } fun fromFeedItem(itemWithFeed: ItemWithFeed, context: Context): MapAnnotation<String>? { val feed = itemWithFeed.feed val item = itemWithFeed.item val geometry = item.geometry ?: return null val iconUri = feed.mapStyle?.iconStyle?.id?.let { Uri.parse("${Server(context).baseUrl}/api/icons/${it}/content") } return MapAnnotation( id = item.id, layer = feed.id, geometry = geometry, timestamp = item.timestamp, style = IconStyle(iconUri) ) } fun fromStaticFeature(feature: StaticFeature, context: Context): MapAnnotation<Long> { return MapAnnotation( id = feature.id, layer = feature.layer.id.toString(), geometry = feature.geometry, style = AnnotationStyle.fromStaticFeature(feature, context) ) } } }
apache-2.0
e38f131a0a7b8f79a868bf4e3e09cfba
32.625
101
0.618421
4.587927
false
false
false
false
android/app-bundle-samples
DynamicFeatures/app/src/main/java/com/google/android/samples/dynamicfeatures/MainActivity.kt
1
16566
/* * Copyright 2018 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.google.android.samples.dynamicfeatures import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.View import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.constraintlayout.widget.Group import com.google.android.play.core.splitcompat.SplitCompat import com.google.android.play.core.splitinstall.SplitInstallManager import com.google.android.play.core.splitinstall.SplitInstallManagerFactory import com.google.android.play.core.splitinstall.SplitInstallRequest import com.google.android.play.core.splitinstall.SplitInstallSessionState import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus import java.util.Locale class MainActivity : BaseSplitActivity() { /** Listener used to handle changes in state for install requests. */ private val listener = SplitInstallStateUpdatedListener { state -> val multiInstall = state.moduleNames().size > 1 val langsInstall = state.languages().isNotEmpty() val names = if (langsInstall) { // We always request the installation of a single language in this sample state.languages().first() } else state.moduleNames().joinToString(" - ") when (state.status()) { SplitInstallSessionStatus.DOWNLOADING -> { // In order to see this, the application has to be uploaded to the Play Store. displayLoadingState(state, getString(R.string.downloading, names)) } SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION -> { /* This may occur when attempting to download a sufficiently large module. In order to see this, the application has to be uploaded to the Play Store. Then features can be requested until the confirmation path is triggered. */ manager.startConfirmationDialogForResult(state, this, CONFIRMATION_REQUEST_CODE) } SplitInstallSessionStatus.INSTALLED -> { if (langsInstall) { onSuccessfulLanguageLoad(names) } else { onSuccessfulLoad(names, launch = !multiInstall) } } SplitInstallSessionStatus.INSTALLING -> displayLoadingState( state, getString(R.string.installing, names) ) SplitInstallSessionStatus.FAILED -> { toastAndLog(getString(R.string.error_for_module, state.errorCode(), state.moduleNames())) } } } /** This is needed to handle the result of the manager.startConfirmationDialogForResult request that can be made from SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION in the listener above. */ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == CONFIRMATION_REQUEST_CODE) { // Handle the user's decision. For example, if the user selects "Cancel", // you may want to disable certain functionality that depends on the module. if (resultCode == Activity.RESULT_CANCELED) { toastAndLog(getString(R.string.user_cancelled)) } } else { super.onActivityResult(requestCode, resultCode, data) } } private val moduleKotlin by lazy { getString(R.string.module_feature_kotlin) } private val moduleJava by lazy { getString(R.string.module_feature_java) } private val moduleNative by lazy { getString(R.string.module_native) } private val moduleMaxSdk by lazy { getString(R.string.module_feature_maxsdk) } private val moduleAssets by lazy { getString(R.string.module_assets) } private val moduleInitial by lazy { getString(R.string.module_initial) } private val instantModule by lazy { getString(R.string.module_instant_feature_split_install) } private val instantModuleUrl by lazy { getString(R.string.instant_feature_url) } // Modules to install through installAll functions. private val installableModules by lazy { listOf(moduleKotlin, moduleJava, moduleNative, moduleAssets) } private val clickListener by lazy { View.OnClickListener { when (it.id) { R.id.btn_load_kotlin -> loadAndLaunchModule(moduleKotlin) R.id.btn_load_java -> loadAndLaunchModule(moduleJava) R.id.btn_load_assets -> loadAndLaunchModule(moduleAssets) R.id.btn_start_maxsdk -> { /* Check if the module is available in the first place. In a real world app functionality might be different for a maxSdk conditional module. Here we just show a toast to highlight that the app is running above the set maxSdk. */ if (!manager.installedModules.contains(moduleMaxSdk)) { Toast.makeText( this@MainActivity, "Not installed by condition, loading before launch", Toast.LENGTH_LONG) .show() } loadAndLaunchModule(moduleMaxSdk) } R.id.btn_load_native -> loadAndLaunchModule(moduleNative) R.id.btn_install_all_now -> installAllFeaturesNow() R.id.btn_install_all_deferred -> installAllFeaturesDeferred() R.id.btn_request_uninstall -> requestUninstall() R.id.btn_launch_initial_install -> loadAndLaunchModule(moduleInitial) R.id.btn_instant_dynamic_feature_split_install -> loadAndLaunchModule(instantModule) R.id.btn_instant_dynamic_feature_url_load -> openUrl(instantModuleUrl) R.id.lang_en -> loadAndSwitchLanguage(LANG_EN) R.id.lang_pl -> loadAndSwitchLanguage(LANG_PL) } } } private lateinit var manager: SplitInstallManager private lateinit var progress: Group private lateinit var buttons: Group private lateinit var progressBar: ProgressBar private lateinit var progressText: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTitle(R.string.app_name) setContentView(R.layout.activity_main) manager = SplitInstallManagerFactory.create(this) initializeViews() } override fun onResume() { // Listener can be registered even without directly triggering a download. manager.registerListener(listener) super.onResume() } override fun onPause() { // Make sure to dispose of the listener once it's no longer needed. manager.unregisterListener(listener) super.onPause() } /** * Load a feature by module name. * @param name The name of the feature module to load. */ private fun loadAndLaunchModule(name: String) { updateProgressMessage(getString(R.string.loading_module, name)) // Skip loading if the module already is installed. Perform success action directly. if (manager.installedModules.contains(name)) { updateProgressMessage(getString(R.string.already_installed)) onSuccessfulLoad(name, launch = true) return } // Create request to install a feature module by name. val request = SplitInstallRequest.newBuilder() .addModule(name) .build() // Load and install the requested feature module. manager.startInstall(request) updateProgressMessage(getString(R.string.starting_install_for, name)) } /** * Load language splits by language name. * @param lang The language code to load (without the region part, e.g. "en", "fr" or "pl"). */ private fun loadAndSwitchLanguage(lang: String) { updateProgressMessage(getString(R.string.loading_language, lang)) // Skip loading if the language is already installed. Perform success action directly. if (manager.installedLanguages.contains(lang)) { updateProgressMessage(getString(R.string.already_installed)) onSuccessfulLanguageLoad(lang) return } // Create request to install a language by name. val request = SplitInstallRequest.newBuilder() .addLanguage(Locale.forLanguageTag(lang)) .build() // Load and install the requested language. manager.startInstall(request) updateProgressMessage(getString(R.string.starting_install_for, lang)) } private fun openUrl(url: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) .setPackage(BuildConfig.APPLICATION_ID) .addCategory(Intent.CATEGORY_BROWSABLE) startActivity(intent) } /** Display assets loaded from the assets feature module. */ private fun displayAssets() { // Get the asset manager with a refreshed context, to access content of newly installed apk. val assetManager = createPackageContext(packageName, 0).also { SplitCompat.install(it) }.assets // Now treat it like any other asset file. val assetsStream = assetManager.open("assets.txt") val assetContent = assetsStream.bufferedReader() .use { it.readText() } AlertDialog.Builder(this) .setTitle(getString(R.string.asset_content)) .setMessage(assetContent) .show() } /** Install all features but do not launch any of them. */ private fun installAllFeaturesNow() { // Request all known modules to be downloaded in a single session. val requestBuilder = SplitInstallRequest.newBuilder() installableModules.forEach { name -> if (!manager.installedModules.contains(name)) { requestBuilder.addModule(name) } } val request = requestBuilder.build() manager.startInstall(request).addOnSuccessListener { toastAndLog("Loading ${request.moduleNames}") }.addOnFailureListener { toastAndLog("Failed loading ${request.moduleNames}") } } /** Install all features deferred. */ private fun installAllFeaturesDeferred() { manager.deferredInstall(installableModules).addOnSuccessListener { toastAndLog("Deferred installation of $installableModules") } } /** Request uninstall of all features. */ private fun requestUninstall() { toastAndLog("Requesting uninstall of all modules." + "This will happen at some point in the future.") val installedModules = manager.installedModules.toList() manager.deferredUninstall(installedModules).addOnSuccessListener { toastAndLog("Uninstalling $installedModules") }.addOnFailureListener { toastAndLog("Failed installation of $installedModules") } } /** * Define what to do once a feature module is loaded successfully. * @param moduleName The name of the successfully loaded module. * @param launch `true` if the feature module should be launched, else `false`. */ private fun onSuccessfulLoad(moduleName: String, launch: Boolean) { if (launch) { when (moduleName) { moduleKotlin -> launchActivity(KOTLIN_SAMPLE_CLASSNAME) moduleJava -> launchActivity(JAVA_SAMPLE_CLASSNAME) moduleInitial -> launchActivity(INITIAL_INSTALL_CLASSNAME) moduleMaxSdk -> launchActivity(MAX_SDK_CLASSNAME) moduleNative -> launchActivity(NATIVE_SAMPLE_CLASSNAME) moduleAssets -> displayAssets() instantModule -> launchActivity(INSTANT_SAMPLE_CLASSNAME) } } displayButtons() } private fun onSuccessfulLanguageLoad(lang: String) { LanguageHelper.language = lang recreate() } /** Launch an activity by its class name. */ private fun launchActivity(className: String) { val intent = Intent().setClassName(BuildConfig.APPLICATION_ID, className) startActivity(intent) } /** Display a loading state to the user. */ private fun displayLoadingState(state: SplitInstallSessionState, message: String) { displayProgress() progressBar.max = state.totalBytesToDownload().toInt() progressBar.progress = state.bytesDownloaded().toInt() updateProgressMessage(message) } /** Set up all view variables. */ private fun initializeViews() { buttons = findViewById(R.id.buttons) progress = findViewById(R.id.progress) progressBar = findViewById(R.id.progress_bar) progressText = findViewById(R.id.progress_text) setupClickListener() } /** Set all click listeners required for the buttons on the UI. */ private fun setupClickListener() { setClickListener(R.id.btn_load_kotlin, clickListener) setClickListener(R.id.btn_load_java, clickListener) setClickListener(R.id.btn_load_assets, clickListener) setClickListener(R.id.btn_load_native, clickListener) setClickListener(R.id.btn_install_all_now, clickListener) setClickListener(R.id.btn_install_all_deferred, clickListener) setClickListener(R.id.btn_request_uninstall, clickListener) setClickListener(R.id.btn_launch_initial_install, clickListener) setClickListener(R.id.btn_instant_dynamic_feature_split_install, clickListener) setClickListener(R.id.btn_instant_dynamic_feature_url_load, clickListener) setClickListener(R.id.lang_en, clickListener) setClickListener(R.id.lang_pl, clickListener) } private fun setClickListener(id: Int, listener: View.OnClickListener) { findViewById<View>(id).setOnClickListener(listener) } private fun updateProgressMessage(message: String) { if (progress.visibility != View.VISIBLE) displayProgress() progressText.text = message } /** Display progress bar and text. */ private fun displayProgress() { progress.visibility = View.VISIBLE buttons.visibility = View.GONE } /** Display buttons to accept user input. */ private fun displayButtons() { progress.visibility = View.GONE buttons.visibility = View.VISIBLE } } fun MainActivity.toastAndLog(text: String) { Toast.makeText(this, text, Toast.LENGTH_LONG).show() Log.d(TAG, text) } private const val PACKAGE_NAME = "com.google.android.samples.dynamicfeatures" private const val PACKAGE_NAME_ONDEMAND = "$PACKAGE_NAME.ondemand" private const val INSTANT_PACKAGE_NAME = "com.google.android.samples.instantdynamicfeatures" private const val KOTLIN_SAMPLE_CLASSNAME = "$PACKAGE_NAME_ONDEMAND.KotlinSampleActivity" private const val JAVA_SAMPLE_CLASSNAME = "$PACKAGE_NAME_ONDEMAND.JavaSampleActivity" private const val NATIVE_SAMPLE_CLASSNAME = "$PACKAGE_NAME_ONDEMAND.NativeSampleActivity" private const val INITIAL_INSTALL_CLASSNAME = "$PACKAGE_NAME.InitialInstallActivity" private const val MAX_SDK_CLASSNAME = "$PACKAGE_NAME.MaxSdkSampleActivity" private const val INSTANT_SAMPLE_CLASSNAME = "$INSTANT_PACKAGE_NAME.SplitInstallInstantActivity" private const val CONFIRMATION_REQUEST_CODE = 1 private const val TAG = "DynamicFeatures"
apache-2.0
3ce23e71d8e8a1d30e51da39a6d9a456
41.260204
100
0.659544
4.800348
false
false
false
false
koesie10/AdventOfCode-Solutions-Kotlin
2015/src/main/kotlin/com/koenv/adventofcode/Day18.kt
1
7998
package com.koenv.adventofcode import javafx.animation.AnimationTimer import javafx.application.Application import javafx.event.EventHandler import javafx.geometry.VPos import javafx.scene.Scene import javafx.scene.canvas.Canvas import javafx.scene.canvas.GraphicsContext import javafx.scene.input.KeyEvent import javafx.scene.input.MouseEvent import javafx.scene.layout.StackPane import javafx.scene.paint.Color import javafx.scene.text.Font import javafx.stage.Stage import java.io.FileReader import java.util.* class Day18(val width: Int, val height: Int) { private val grid: Array<Array<Int>> val numberOfLightsInOnState: Int get() = grid.sumBy { it.sum() } val numberOfLightsInOffState: Int get() = width * height - numberOfLightsInOnState init { this.grid = Array(width, { Array(height, { STATE_OFF }) }) // Initialize an array of int[width][height] with all states set to 0 } fun setState(input: String) { input.lines().forEachIndexed { y, row -> row.forEachIndexed { x, state -> grid[x][y] = if (state == '#') STATE_ON else STATE_OFF } } } fun turnCornersOn() { grid[0][0] = STATE_ON grid[width - 1][0] = STATE_ON grid[0][height - 1] = STATE_ON grid[width - 1][height - 1] = STATE_ON } fun tick() { val oldGrid = grid.map { it.map { it } } for (x in 0..grid.size - 1) { for (y in 0..grid[x].size - 1) { val neighboursStates = getNumberOfNeighboursInOnState(oldGrid, x, y) if (oldGrid[x][y] == STATE_ON && neighboursStates != 2 && neighboursStates != 3) { grid[x][y] = STATE_OFF } else if (oldGrid[x][y] == STATE_OFF && neighboursStates == 3) { grid[x][y] = STATE_ON } } } } fun toggle(x: Int, y: Int) { grid[x][y] = if (grid[x][y] == STATE_ON) STATE_OFF else STATE_ON } private fun getNumberOfNeighboursInOnState(oldGrid: List<List<Int>>, x: Int, y: Int): Int { val neighbours = arrayOf( /* * +--------+----------+--------+ * | -1, -1 | 0, -1 | 1, -1 | * +--------+----------+--------+ * | -1, 0 | CURRENT! | 1, 0 | * +--------+----------+--------+ * | -1, 1 | 0, 1 | 1, 1 | * +--------+----------+--------+ */ oldGrid.getOrNull(x - 1)?.getOrNull(y - 1), oldGrid.getOrNull(x)?.getOrNull(y - 1), oldGrid.getOrNull(x + 1)?.getOrNull(y - 1), oldGrid.getOrNull(x - 1)?.getOrNull(y), oldGrid.getOrNull(x + 1)?.getOrNull(y), oldGrid.getOrNull(x - 1)?.getOrNull(y + 1), oldGrid.getOrNull(x)?.getOrNull(y + 1), oldGrid.getOrNull(x + 1)?.getOrNull(y + 1) ) return neighbours.filter { it == STATE_ON }.size } companion object { const val STATE_OFF = 0 const val STATE_ON = 1 @JvmStatic fun main(args: Array<String>) { Application.launch(ViewerApplication::class.java) } } class ViewerApplication : Application() { private val control = Day18(100, 100) private var currentTime: Long = 0L private var currentTick: Long = 0L private var speed: Long = 1L private var running = false override fun start(primaryStage: Stage) { primaryStage.title = "Advent of Code - Day 18" primaryStage.isResizable = false val root = StackPane() val canvas = Canvas(800.0, 900.0) val context = canvas.graphicsContext2D canvas.isFocusTraversable = true canvas.requestFocus() context.textBaseline = VPos.TOP context.font = Font.font(20.0) root.children.add(canvas) primaryStage.scene = Scene(root) primaryStage.show() initGrid() drawGrid(context, System.nanoTime()) val loop = object : AnimationTimer() { override fun handle(now: Long) { if (running && ++currentTime % speed == 0L) { control.tick() currentTick++ } drawGrid(context, now) } } val mouseHandler = EventHandler<MouseEvent> { val y = (it.sceneX / canvas.width * control.width).toInt() val x = (it.sceneY / canvas.height * control.height).toInt() if (x < 0 || x >= control.width || y < 0 || y >= control.height) { return@EventHandler } control.toggle(x, y) } canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseHandler) canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, mouseHandler) canvas.addEventHandler(KeyEvent.KEY_TYPED, { when (it.character) { "c" -> { control.grid.forEachIndexed { y, row -> row.forEachIndexed { x, cell -> control.grid[y][x] = if (cell == STATE_ON) STATE_OFF else STATE_ON } } } "r" -> { val random = Random() control.grid.forEachIndexed { y, row -> row.forEachIndexed { x, cell -> control.grid[y][x] = if (random.nextBoolean()) STATE_OFF else STATE_ON } } currentTick = 0 } "p" -> { running = !running } "q" -> { loop.stop() primaryStage.close() } "=", "+", "." -> { speed-- if (speed <= 0) { speed = 1 } } "-", "," -> { speed++ } } }) loop.start() } fun initGrid() { control.setState(FileReader("2015/src/test/resources/day18.txt").buffered().readText()) } private var prev: Long = 0L private var frameCount: Double = 0.0 private var fps: Double = 0.0 fun drawGrid(context: GraphicsContext, now: Long) { // a second if (now - prev > 1000000000) { fps = frameCount prev = now frameCount = 0.0 } else { frameCount++ } val gridSizeX = context.canvas.width / control.width val gridSizeY = context.canvas.height / control.height context.fill = Color.BLACK context.fillRect(0.0, 0.0, context.canvas.width, context.canvas.height) context.fill = Color.WHITE control.grid.forEachIndexed { x, row -> row.forEachIndexed { y, cell -> if (cell == STATE_ON) { context.fillRect(x * gridSizeX, y * gridSizeY + 100.0, gridSizeX, gridSizeY) } } } val text = "FPS: $fps, Tick: $currentTick, Speed: ${1.0f / speed}" context.fill = Color.WHITE context.fillText(text, 0.0, 0.0) if (!running) { context.fill = Color.RED context.fillText("PAUSED", 0.0, 30.0) } } } }
mit
655507d7dc934fd0e357751137ac2933
31.917695
136
0.461115
4.445803
false
false
false
false
ysl3000/PathfindergoalAPI
Pathfinder_1_16/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_16_R2/entity/CraftInsentient.kt
1
5805
package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_16_R2.entity import com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_16_R2.pathfinding.CraftNavigation import com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_16_R2.pathfinding.CraftPathfinderGoalWrapper import com.github.ysl3000.bukkit.pathfinding.entity.Insentient import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderGoal import net.minecraft.server.v1_16_R2.EntityInsentient import net.minecraft.server.v1_16_R2.PathfinderGoalSelector import org.bukkit.Location import org.bukkit.attribute.Attributable import org.bukkit.attribute.Attribute import org.bukkit.craftbukkit.v1_16_R2.entity.* import org.bukkit.entity.* import org.bukkit.util.Vector import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.util.* class CraftInsentient private constructor(private val handle: EntityInsentient) : Insentient { private val nmsGoals = HashMap<PathfinderGoal, net.minecraft.server.v1_16_R2.PathfinderGoal>() private val nmsTargetGoals = HashMap<PathfinderGoal, net.minecraft.server.v1_16_R2.PathfinderGoal>() private val navigation: com.github.ysl3000.bukkit.pathfinding.pathfinding.Navigation constructor(flying: Flying) : this((flying as CraftFlying).handle) init { this.navigation = CraftNavigation(handle.navigation, handle, (handle.bukkitEntity as Attributable).getAttribute(Attribute.GENERIC_MOVEMENT_SPEED)?.value ?: 0.7) } constructor(enderDragon: EnderDragon) : this((enderDragon as CraftEnderDragon).handle) constructor(creature: Creature) : this((creature as CraftCreature).handle) constructor(mob: Mob) : this((mob as CraftMob).handle) constructor(ambient: Ambient) : this((ambient as CraftAmbient).handle) constructor(slime: Slime) : this((slime as CraftSlime).handle) override fun addPathfinderGoal(priority: Int, pathfinderGoal: PathfinderGoal) { val goalWrapper = CraftPathfinderGoalWrapper(pathfinderGoal) this.nmsGoals[pathfinderGoal] = goalWrapper handle.goalSelector.a(priority, goalWrapper) } override fun removePathfinderGoal( pathfinderGoal: PathfinderGoal) { if (nmsGoals.containsKey(pathfinderGoal)) { val nmsGoal = nmsGoals.remove(pathfinderGoal) handle.goalSelector.a(nmsGoal) } } override fun hasPathfinderGoal( pathfinderGoal: PathfinderGoal): Boolean = nmsGoals.containsKey(pathfinderGoal) override fun clearPathfinderGoals() { handle.goalSelector = PathfinderGoalSelector(handle.getWorld().methodProfilerSupplier) nmsGoals.clear() } override fun addTargetPathfinderGoal(priority: Int, pathfinderGoal: PathfinderGoal) { val goalWrapper = CraftPathfinderGoalWrapper(pathfinderGoal) this.nmsTargetGoals[pathfinderGoal] = goalWrapper handle.targetSelector.a(priority, goalWrapper) } override fun removeTargetPathfinderGoal( pathfinderGoal: PathfinderGoal) { if (nmsTargetGoals.containsKey(pathfinderGoal)) { val nmsGoal = nmsTargetGoals.remove(pathfinderGoal) handle.goalSelector.a(nmsGoal) } } override fun hasTargetPathfinderGoal( pathfinderGoal: PathfinderGoal): Boolean = nmsTargetGoals.containsKey(pathfinderGoal) override fun clearTargetPathfinderGoals() { handle.targetSelector = PathfinderGoalSelector(handle.getWorld().methodProfilerSupplier) nmsTargetGoals.clear() } override fun jump() { handle.controllerJump.jump() } override fun lookAt(location: Location) = handle.controllerLook .a(location.x, location.y, location.z, location.yaw, location.pitch) override fun lookAt(entity: Entity) = lookAt(entity.location) override fun getLookingAt(): Location = Location(handle.bukkitEntity.world, handle.controllerLook.d(), handle.controllerLook.e(), handle.controllerLook.f()) override fun setMovementDirection(direction: Vector, speed: Double) = handle.controllerMove.a(direction.x, direction.blockY.toDouble(), direction.z, speed) override fun setStrafeDirection(forward: Float, sideward: Float) = handle.controllerMove.a(forward, sideward) override fun resetGoalsToDefault() { if (reset == null) { return } try { reset!!.invoke(handle) } catch (e: IllegalAccessException) { e.printStackTrace() } catch (e: InvocationTargetException) { e.printStackTrace() } } override fun getNavigation(): com.github.ysl3000.bukkit.pathfinding.pathfinding.Navigation = navigation override fun getHeadHeight(): Float = handle.headHeight override fun hasPositionChanged(): Boolean = handle.positionChanged override fun onEntityKill(livingEntity: LivingEntity) { val nms = (livingEntity as CraftLivingEntity).handle handle.a(nms.world.server.server.getWorldServer(nms.world.dimensionKey), nms) } override fun getBukkitEntity(): Entity = handle.bukkitEntity override fun setRotation(yaw: Float, pitch: Float) { this.handle.yaw = yaw this.handle.pitch = pitch } override fun updateRenderAngles() = handle.controllerMove.a() companion object { private var reset: Method? = null init { try { reset = EntityInsentient::class.java.getDeclaredMethod("initPathfinder") reset!!.isAccessible = true } catch (e: NoSuchMethodException) { e.printStackTrace() } } } }
mit
6b4783a5fc83fecf76515af62c2c0005
35.2875
160
0.702326
4.560094
false
false
false
false
kharchenkovitaliypt/AndroidMvp
mvp/src/main/java/com/idapgroup/android/mvp/impl/LceViewCreator.kt
1
1930
package com.idapgroup.android.mvp.impl import android.support.annotation.LayoutRes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.idapgroup.android.mvp.R typealias ViewCreator = (inflater: LayoutInflater, container: ViewGroup) -> View interface LceViewCreator { fun onCreateLoadView(inflater: LayoutInflater, container: ViewGroup) : View fun onCreateErrorView(inflater: LayoutInflater, container: ViewGroup) : View fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup): View } open class SimpleLceViewCreator( val createContentView: ViewCreator, val createLoadView: ViewCreator = Layout.CREATE_LOAD_VIEW, val createErrorView: ViewCreator = Layout.CREATE_ERROR_VIEW ): LceViewCreator { object Layout { val LOAD = R.layout.lce_base_load val ERROR = R.layout.lce_base_error val CREATE_LOAD_VIEW = toViewCreator(Layout.LOAD) val CREATE_ERROR_VIEW = toViewCreator(Layout.ERROR) } constructor(@LayoutRes contentRes: Int, @LayoutRes loadRes: Int = Layout.LOAD, @LayoutRes errorRes: Int = Layout.ERROR ): this( toViewCreator(contentRes), toViewCreator(loadRes), toViewCreator(errorRes) ) override fun onCreateLoadView(inflater: LayoutInflater, container: ViewGroup) : View { return createLoadView(inflater, container) } override fun onCreateErrorView(inflater: LayoutInflater, container: ViewGroup) : View { return createErrorView(inflater, container) } override fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup): View { return createContentView(inflater, container) } } fun toViewCreator(@LayoutRes layoutRes: Int): ViewCreator { return { inflater, container -> inflater.inflate(layoutRes, container, false) } }
apache-2.0
7fde92af4fea54d034bdf548e6d02c65
32.859649
92
0.714508
4.606205
false
false
false
false
proxer/ProxerLibJava
library/src/main/kotlin/me/proxer/library/internal/adapter/NotificationAdapter.kt
1
1790
package me.proxer.library.internal.adapter import com.squareup.moshi.FromJson import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.squareup.moshi.ToJson import me.proxer.library.entity.notifications.Notification import me.proxer.library.enums.NotificationType import me.proxer.library.util.ProxerUrls import java.util.Date /** * @author Ruben Gees */ internal class NotificationAdapter { @FromJson fun fromJson(json: IntermediateNotification): Notification { val properContentLink = ProxerUrls.webBase.newBuilder() .addEncodedPathSegments( json.contentLink .trimStart('/') .substringBeforeLast("#") ) .build() return Notification( json.id, json.type, json.contentId, properContentLink, json.text, json.date, json.additionalDescription ) } @ToJson fun toJson(value: Notification): IntermediateNotification { return IntermediateNotification( value.id, value.type, value.contentId, value.contentLink.toString(), value.text, value.date, value.additionalDescription ) } @JsonClass(generateAdapter = true) internal data class IntermediateNotification( @Json(name = "id") val id: String, @Json(name = "type") val type: NotificationType, @Json(name = "tid") val contentId: String, @Json(name = "link") val contentLink: String, @Json(name = "linktext") val text: String, @Json(name = "time") val date: Date, @Json(name = "description") val additionalDescription: String ) }
mit
cd4b84fdcf57b3c37977fe705d4b1d14
28.344262
69
0.612291
4.685864
false
false
false
false
ScienceYuan/WidgetNote
app/src/test/java/com/rousci/androidapp/widgetnote/viewPresenter/setting/Presenter.kt
1
2610
package com.rousci.androidapp.widgetnote.viewPresenter.setting import android.appwidget.AppWidgetManager import android.content.Context import android.content.SharedPreferences import android.text.Editable import android.view.MenuItem import android.widget.EditText import com.rousci.androidapp.widgetnote.viewPresenter.singleDataPreference import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.* import org.robolectric.RobolectricTestRunner /** * Created by rousci on 17-11-7. */ @RunWith(RobolectricTestRunner::class) class Presenter{ val setting = mock(Setting::class.java) val finishItem = mock(MenuItem::class.java) val frequencyEditor = mock(EditText::class.java) val frequencyText = mock(Editable::class.java) val fontEditor = mock(EditText::class.java) val fontText = mock(Editable::class.java) val sharePreference = mock(SharedPreferences::class.java) val editor = mock(SharedPreferences.Editor::class.java) val wigdetManager = mock(AppWidgetManager::class.java) val testFontSize = 24 val testFrequence = 2 @Before fun before(){ `when`(finishItem.itemId).thenReturn(android.R.id.home) `when`(setting.frequencyEditor).thenReturn(frequencyEditor) `when`(frequencyEditor.text).thenReturn(frequencyText) `when`(frequencyText.toString()).thenReturn(testFrequence.toString()) `when`(setting.fontSizeEditor).thenReturn(fontEditor) `when`(fontEditor.text).thenReturn(fontText) `when`(fontText.toString()).thenReturn(testFontSize.toString()) `when`(setting.getSharedPreferences(singleDataPreference, Context.MODE_PRIVATE)). thenReturn(sharePreference) `when`(sharePreference.edit()).thenReturn(editor) } @After fun after(){ } @Test fun itemSelect(){ onOptionsItemSelectedPR(finishItem, setting) verify(finishItem).itemId verify(setting).finish() } @Test fun updateConfigNormal(){ updateConfig(setting) verify(setting).frequencyEditor verify(setting).fontSizeEditor verify(frequencyEditor).text verify(fontEditor).text verify(setting).getSharedPreferences(singleDataPreference, Context.MODE_PRIVATE) verify(editor).apply() } @Test fun updateRemoteViewNormal(){ updateRemoteView(wigdetManager, setting) verify(setting).fontSizeEditor verify(setting).getSharedPreferences(singleDataPreference, Context.MODE_PRIVATE) } }
mit
a965e318ababd9169e2ac79611a17935
28
89
0.720307
4.357262
false
true
false
false
gravidence/gravifon
gravifon/src/main/kotlin/org/gravidence/gravifon/ui/window/ApplicationWindow.kt
1
6027
package org.gravidence.gravifon.ui.window import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.input.key.* import androidx.compose.ui.window.ApplicationScope import androidx.compose.ui.window.MenuBar import androidx.compose.ui.window.Window import androidx.compose.ui.window.WindowState import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.gravidence.gravifon.GravifonContext import org.gravidence.gravifon.GravifonStarter import org.gravidence.gravifon.event.EventBus import org.gravidence.gravifon.event.application.WindowStateChangedEvent import org.gravidence.gravifon.event.playback.PausePlaybackEvent import org.gravidence.gravifon.event.playback.RepositionPlaybackPointRelativeEvent import org.gravidence.gravifon.event.playback.StopPlaybackAfterEvent import org.gravidence.gravifon.playback.PlaybackStatus import org.gravidence.gravifon.playlist.manage.StopAfter import org.gravidence.gravifon.ui.AppBody import org.gravidence.gravifon.ui.dialog.ApplicationSettingsDialog import org.gravidence.gravifon.ui.dialog.PluginSettingsDialog import org.gravidence.gravifon.ui.dialog.TrackMetadataDialog import kotlin.time.Duration.Companion.seconds @OptIn(ExperimentalComposeUiApi::class) @Composable fun ApplicationScope.ApplicationWindow(windowState: WindowState) { Window( title = "Gravifon", state = windowState, onCloseRequest = { GravifonStarter.orchestrator.shutdown() GravifonContext.scopeDefault.cancel() GravifonContext.scopeIO.cancel() exitApplication() }, onPreviewKeyEvent = { // TODO below doesn't work, see https://github.com/JetBrains/compose-jb/issues/1840 if (it.key == Key.MediaPlayPause && it.type == KeyEventType.KeyUp) { EventBus.publish(PausePlaybackEvent()) return@Window true } return@Window false } ) { LaunchedEffect(windowState) { snapshotFlow { windowState.size } .onEach { EventBus.publish(WindowStateChangedEvent(size = it)) } .launchIn(this) snapshotFlow { windowState.position } .filter { it.isSpecified } .onEach { EventBus.publish(WindowStateChangedEvent(position = it)) } .launchIn(this) snapshotFlow { windowState.placement } .onEach { EventBus.publish(WindowStateChangedEvent(placement = it)) } .launchIn(this) } MenuBar { Menu(text = "File") { } Menu(text = "Playback") { Item( text = "Play/Pause", icon = rememberVectorPainter(Icons.Filled.PlayArrow), shortcut = KeyShortcut(key = Key.Spacebar, ctrl = true), onClick = { EventBus.publish(PausePlaybackEvent()) } ) Separator() Item( text = "Jump forward", icon = rememberVectorPainter(Icons.Filled.FastForward), shortcut = KeyShortcut(key = Key.DirectionRight), onClick = { EventBus.publish(RepositionPlaybackPointRelativeEvent(10.seconds)) } ) Item( text = "Jump backward", icon = rememberVectorPainter(Icons.Filled.FastRewind), shortcut = KeyShortcut(key = Key.DirectionLeft), onClick = { EventBus.publish(RepositionPlaybackPointRelativeEvent((-10).seconds)) } ) Separator() Item( text = "Stop after current", icon = if (GravifonContext.stopAfterState.value.activated) rememberVectorPainter(Icons.Filled.Check) else null, shortcut = KeyShortcut(key = Key.Spacebar, shift = true), onClick = { if (GravifonContext.stopAfterState.value.activated) { GravifonContext.stopAfterState.value = StopAfter() } else { val n = when (GravifonContext.playbackStatusState.value) { PlaybackStatus.STOPPED -> 1 else -> 0 } EventBus.publish(StopPlaybackAfterEvent(n)) } } ) } Menu(text = "Settings") { Item( text = "Application...", icon = rememberVectorPainter(Icons.Filled.Settings), onClick = { GravifonContext.applicationSettingsDialogVisible.value = true } ) Item( text = "Plugin...", icon = rememberVectorPainter(Icons.Filled.Extension), onClick = { GravifonContext.pluginSettingsDialogVisible.value = true } ) } Menu(text = "View") { GravifonStarter.views .filter { it.viewEnabled } .forEach { Item( text = it.viewDisplayName, onClick = { it.activateView() } ) } } Menu(text = "About") { } } AppBody() ApplicationSettingsDialog() PluginSettingsDialog() TrackMetadataDialog() } }
mit
7e08db3e5ca787923f163c67ae5cf455
39.72973
131
0.585532
5.324205
false
false
false
false
SUPERCILEX/Robot-Scouter
feature/trash/src/main/java/com/supercilex/robotscouter/feature/trash/TrashListAdapter.kt
1
1233
package com.supercilex.robotscouter.feature.trash import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.selection.SelectionTracker import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.supercilex.robotscouter.core.LateinitVal internal class TrashListAdapter : ListAdapter<Trash, TrashViewHolder>(differ) { var selectionTracker: SelectionTracker<String> by LateinitVal() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = TrashViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.trash_item, parent, false) ) override fun onBindViewHolder(holder: TrashViewHolder, position: Int) { val trash = getItem(position) holder.bind(trash, selectionTracker.isSelected(trash.id)) } public override fun getItem(position: Int): Trash = super.getItem(position) private companion object { val differ = object : DiffUtil.ItemCallback<Trash>() { override fun areItemsTheSame(oldItem: Trash, newItem: Trash) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Trash, newItem: Trash) = oldItem == newItem } } }
gpl-3.0
ca6357afc4e0872b7d5ba70274424fb2
38.774194
99
0.748581
4.760618
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/browser/webview/CustomViewSwitcher.kt
2
5682
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.browser.webview import android.app.Activity import android.content.Context import android.media.MediaPlayer import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.webkit.WebChromeClient import android.webkit.WebView import android.widget.FrameLayout import android.widget.VideoView import androidx.core.content.ContextCompat import jp.toastkid.yobidashi.R import timber.log.Timber /** * [WebView]'s custom view switcher. * * @param contextSupplier Use for making parent view. * @param currentWebViewSupplier Use for getting current [WebView] * @author toastkidjp */ class CustomViewSwitcher( private val contextSupplier: () -> Context, private val currentWebViewSupplier: () -> View? ) { /** * Custom view container. */ private var customViewContainer: FrameLayout? = null /** * Holding for controlling video content. */ private var videoView: VideoView? = null /** * Holding for recover previous orientation. */ private var originalOrientation: Int = 0 /** * Holding for disposing. */ private var customViewCallback: WebChromeClient.CustomViewCallback? = null /** * Holding for disposing custom view. */ private var customView: View? = null /** * Delegation from WebChromeClient. * * @param view Custom view from [WebView]. * @param callback from [WebView] */ fun onShowCustomView(view: View?, callback: WebChromeClient.CustomViewCallback?) { if (customView != null) { callback?.onCustomViewHidden() return } val activity = contextSupplier() as? Activity ?: return activity.window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) originalOrientation = activity.requestedOrientation activity.requestedOrientation = activity.requestedOrientation customViewContainer = FrameLayout(activity) customViewContainer?.setBackgroundColor(ContextCompat.getColor(activity, R.color.filter_white_aa)) view?.keepScreenOn = true val listener = VideoCompletionListener() if (view is FrameLayout) { val child = view.focusedChild if (child is VideoView) { videoView = child videoView?.setOnErrorListener(listener) videoView?.setOnCompletionListener(listener) } } else if (view is VideoView) { videoView = view videoView?.setOnErrorListener(listener) videoView?.setOnCompletionListener(listener) } customViewCallback = callback customView = view val decorView = activity.window.decorView as? FrameLayout decorView?.addView(customViewContainer, customViewParams) customViewContainer?.addView(customView, customViewParams) decorView?.requestLayout() currentWebViewSupplier()?.visibility = View.INVISIBLE } /** * Delegation from WebChromeClient. */ fun onHideCustomView() { val activity = contextSupplier() as? Activity ?: return activity.window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) customView?.keepScreenOn = false if (customViewCallback != null) { try { customViewCallback?.onCustomViewHidden() } catch (e: Exception) { Timber.w("Error hiding custom view", e) } customViewCallback = null } currentWebViewSupplier()?.visibility = View.VISIBLE if (customViewContainer != null) { val parent = customViewContainer?.parent as? ViewGroup parent?.removeView(customViewContainer) customViewContainer?.removeAllViews() } customViewContainer = null customView = null videoView?.stopPlayback() videoView?.setOnErrorListener(null) videoView?.setOnCompletionListener(null) videoView = null try { customViewCallback?.onCustomViewHidden() } catch (e: Exception) { Timber.w(e) } customViewCallback = null activity.requestedOrientation = originalOrientation } /** * Video completion listener. */ private inner class VideoCompletionListener : MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener { /** * Only return false. * * @param mp [MediaPlayer] * @param what [Int] * @param extra [Int] * @return false */ override fun onError(mp: MediaPlayer, what: Int, extra: Int): Boolean = false /** * Only call onHideCustomView. * * @param mp [MediaPlayer] */ override fun onCompletion(mp: MediaPlayer) = onHideCustomView() } companion object { /** * For centering video view. */ private val customViewParams = FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER ) } }
epl-1.0
f3d5af93a4b2fdc5f6352f7290f7c624
28.293814
106
0.638684
5.265987
false
false
false
false
Jire/Strukt
src/main/kotlin/org/jire/strukt/internal/AbstractStrukts.kt
1
1201
/* * Copyright 2020 Thomas Nappo (Jire) * * 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 org.jire.strukt.internal import it.unimi.dsi.fastutil.objects.ObjectArrayList import org.jire.strukt.Field import org.jire.strukt.Strukts import kotlin.reflect.KClass abstract class AbstractStrukts(override val type: KClass<*>) : Strukts { override var size = 0L override var nextIndex = 0L override val fields = ObjectArrayList<Field>() override fun addField(field: Field) { size += field.size nextIndex++ fields.add(field) } override fun toString(address: Long) = fields.joinToString(", ") { "${it.name}(${it.getBoxed(address)})" } }
apache-2.0
2b36197bc92df4754bd1b2c76498c2fb
29.820513
107
0.716903
3.837061
false
false
false
false
tipsy/javalin
javalin-graphql/src/main/java/io/javalin/plugin/graphql/graphql/GraphQLRun.kt
1
2260
package io.javalin.plugin.graphql.graphql import graphql.ExceptionWhileDataFetching import graphql.ExecutionInput import graphql.ExecutionResult import graphql.GraphQL import org.eclipse.jetty.server.handler.ContextHandler import org.reactivestreams.Publisher import org.reactivestreams.Subscriber import java.util.concurrent.CompletableFuture class GraphQLRun(private val graphql: GraphQL) { private var context: Any? = null private var query: String = "" private var operationName: String? = null private var variables: Map<String, Any> = emptyMap() fun withQuery(query: String): GraphQLRun = apply { this.query = query } fun withVariables(variables: Map<String, Any>): GraphQLRun = apply { this.variables = variables } fun withOperationName(operationName: String?) = apply { this.operationName = operationName } fun withContext(context: Any?): GraphQLRun = apply { this.context = context } fun execute(): CompletableFuture<MutableMap<String, Any>> { val action = generateAction(); return graphql.executeAsync(action) .thenApplyAsync { this.getResult(it) } } private fun generateAction(): ExecutionInput { return ExecutionInput.newExecutionInput() .variables(variables) .query(query) .operationName(operationName) .context(context) .build() } private fun getResult(executionResult: ExecutionResult): MutableMap<String, Any> { val result = mutableMapOf<String, Any>() if (executionResult.errors.isNotEmpty()) { result["errors"] = executionResult.errors.distinctBy { if (it is ExceptionWhileDataFetching) { it.exception } else { it } } } try { result["data"] = executionResult.getData<Any>() } catch (e: Exception) {} return result } fun subscribe(subscriber: Subscriber<ExecutionResult>): Unit { val action = generateAction() return graphql .execute(action) .getData<Publisher<ExecutionResult>>() .subscribe(subscriber) } }
apache-2.0
7e5bc7782c26bd60b5ce165670ec868e
31.285714
101
0.634513
5.067265
false
false
false
false
Aidanvii7/Toolbox
delegates-observable-rxjava/src/main/java/com/aidanvii/toolbox/delegates/observable/rxjava/SubscribeDecorator.kt
1
2524
package com.aidanvii.toolbox.delegates.observable.rxjava import com.aidanvii.toolbox.Action import com.aidanvii.toolbox.Consumer import com.aidanvii.toolbox.actionStub import com.aidanvii.toolbox.consumerStub import com.aidanvii.toolbox.delegates.observable.AfterChange import com.aidanvii.toolbox.delegates.observable.ObservableProperty import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.exceptions.OnErrorNotImplementedException import io.reactivex.plugins.RxJavaPlugins import kotlin.reflect.KProperty private val onErrorStub: Consumer<Throwable> = { RxJavaPlugins.onError(OnErrorNotImplementedException(it)) } fun <ST> ObservableProperty.Source<ST>.subscribeTo( observable: Observable<ST>, compositeDisposable: CompositeDisposable, onError: Consumer<Throwable> = onErrorStub, onComplete: Action = actionStub ) = SubscribeDecorator(this, observable, { compositeDisposable.add(it) }, onError, onComplete) /** * Returns an [ObservableProperty] that subscribes to a given [Observable], and updates the [ObservableProperty.Source] * when the given [Observable] emits a new value. * @param ST the base type of the source observable ([ObservableProperty.Source]). */ fun <ST> ObservableProperty.Source<ST>.subscribeTo( observable: Observable<ST>, outDisposable: Consumer<Disposable> = consumerStub, onError: Consumer<Throwable> = onErrorStub, onComplete: Action = actionStub ) = SubscribeDecorator(this, observable, outDisposable, onError, onComplete) class SubscribeDecorator<ST>( private val decorated: ObservableProperty.Source<ST>, observable: Observable<ST>, consumeDisposable: Consumer<Disposable> = consumerStub, onError: Consumer<Throwable> = onErrorStub, onComplete: Action ) : ObservableProperty<ST, ST> by decorated { init { decorated.onProvideDelegateObservers += { property, oldValue, newValue -> consumeDisposable(observable.subscribe({ decorated.setValue(null, property, newValue) }, onError, onComplete)) } decorated.afterChangeObservers += { property, oldValue, newValue -> afterChangeObservers.forEach { it(property, oldValue, newValue) } } } override val afterChangeObservers = mutableSetOf<AfterChange<ST>>() operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): SubscribeDecorator<ST> { onProvideDelegate(thisRef, property) return this } }
apache-2.0
0c527608ae79b4bd2f5f64082f0426f8
40.393443
122
0.76664
4.771267
false
false
false
false
bpark/companion-classification-micro
src/test/kotlin/com/github/bpark/companion/LearnerTest.kt
1
5911
/* * Copyright 2017 bpark * * 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.github.bpark.companion import com.github.bpark.companion.analyzers.RawFeatureAnalyzer import com.github.bpark.companion.analyzers.TenseFeatureTransformer import com.github.bpark.companion.classifier.TextClassifier import com.github.bpark.companion.input.AnalyzedWord import com.github.bpark.companion.input.NlpSentence import com.github.bpark.companion.input.Sentence import com.github.bpark.companion.input.WordnetSentence import com.github.bpark.companion.learn.SentenceTypeLearner import com.github.bpark.companion.learn.TextClassifierLearner import org.hamcrest.Matchers.lessThan import org.junit.Assert.assertThat import org.junit.Test import weka.core.SerializationHelper /** * Test for different learner implementations. * * Each test reads an .arff file and produces a trained model. This model is used for classification and can be used * for the different classification implementations. */ class LearnerTest { /** * Test for the sentence type (imperative, declarative, people questions, etc.) */ @Test @Throws(Exception::class) fun testLearner() { val learner = SentenceTypeLearner() val instances = learner.loadDataset("src/test/resources/sentences.arff") val classifier = learner.learn(instances) learner.evaluate(classifier, instances) SerializationHelper.write("target/classes/sentences.model", classifier) } /** * Test for topic type, ex, if a phrase is a greeting or farewell. */ @Test @Throws(Exception::class) fun testLearn() { val learner = TextClassifierLearner() val instances = learner.loadDataset("src/test/resources/topics.arff") val classifier = learner.learn(instances) learner.evaluate(classifier, instances) SerializationHelper.write("target/classes/topics.model", classifier) val textClassifier = TextClassifier("/topics.model", listOf("greeting", "farewell", "weather", "other")) val featureAnalyzer = RawFeatureAnalyzer assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("It's rainy")))["weather"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("It's sunny")))["weather"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("It's cold")))["weather"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("The summer is hot")))["weather"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("The winter is cold")))["weather"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("It's hot outside")))["weather"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("The weather is bad")))["weather"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("The sun is shining")))["weather"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("How are you doing?")))["greeting"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("Hello John")))["greeting"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("Hi John")))["greeting"])) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("Bye Mary")))["farewell"])) } /** * Test for tense detection. */ @Test @Throws(Exception::class) fun testTenseLearn() { val learner = TextClassifierLearner() val instances = learner.loadDataset("src/test/resources/tenses.arff") val classifier = learner.learn(instances) learner.evaluate(classifier, instances) SerializationHelper.write("target/classes/tenses.model", classifier) val featureAnalyzer = TenseFeatureTransformer val textClassifier = TextClassifier("/tenses.model", listOf("simplePresent", "presentProgressive", "simplePast", "pastProgressive", "simplePresentPerfect", "presentPerfectProgressive", "simplePastPerfect", "pastPerfectProgressive", "willFuture", "goingToFuture", "simpleFuturePerfect", "futurePerfectProgressive", "conditionalSimple", "conditionalProgressive", "conditionalPerfect", "conditionalPerfectProgressive", "nothing")) val simplePresent = Sentence(NlpSentence("I work", listOf("I", "work"), listOf("PRP", "VBP")), WordnetSentence(listOf(null, AnalyzedWord("work")))) assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(simplePresent))["simplePresent"])) //assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("MD(will,0) VB")))["willFuture"])) //assertThat<Double>(0.9, lessThan<Double>(textClassifier.classify(featureAnalyzer.transform(raw("")))["nothing"])) } private fun raw(raw: String) = Sentence(NlpSentence(raw, emptyList(), emptyList()), WordnetSentence(emptyList())) }
apache-2.0
7e4ccf24c9ae1597a7cf91bb0dbd679b
49.101695
155
0.725427
4.213115
false
true
false
false
Mauin/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/UselessPostfixExpressionSpec.kt
1
2301
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class UselessPostfixExpressionSpec : SubjectSpek<UselessPostfixExpression>({ subject { UselessPostfixExpression() } describe("check several types of postfix increments") { it("overrides the incremented integer") { val code = """ fun x() { var i = 0 i = i-- // invalid i = 1 + i++ // invalid i = i++ + 1 // invalid }""" assertThat(subject.lint(code)).hasSize(3) } it("does not override the incremented integer") { val code = """ fun f() { var j = 0 j = i++ }""" assertThat(subject.lint(code)).hasSize(0) } it("returns no incremented value") { val code = """ fun x() { var i = 0 if (i == 0) return 1 + j++ return i++ }""" assertThat(subject.lint(code)).hasSize(2) } it("should not report field increments") { val code = """ class Test { private var runningId: Long = 0 fun increment() { runningId++ } fun getId(): Long { return runningId++ } } class Foo(var i: Int = 0) { fun getIdAndIncrement(): Int { return i++ } } """ assertThat(subject.lint(code)).isEmpty() } it("should detect properties shadowing fields that are incremented") { val code = """ class Test { private var runningId: Long = 0 fun getId(): Long { val runningId: Long = 0 return runningId++ } } class Foo(var i: Int = 0) { fun foo(): Int { var i = 0 return i++ } } """ assertThat(subject.lint(code)).hasSize(2) } } describe("Only ++ and -- postfix operators should be considered") { it("should not report !! in a return statement") { val code = """ fun getInstance(): SwiftBrowserIdleTaskHelper { return sInstance!! } fun testProperty(): Int { return shouldNotBeNull!!.field } """ assertThat(subject.lint(code)).isEmpty() } it("should not report !! in a standalone expression") { assertThat(subject.lint("sInstance!!")).isEmpty() } } })
apache-2.0
92bca4186404ce87b64f81a4210b1691
20.305556
76
0.596262
3.419019
false
false
false
false
webarata3/KExcelAPI
src/main/kotlin/link/webarata3/kexcelapi/KExcel.kt
2
4693
/* The MIT License (MIT) Copyright (c) 2017 Shinichi ARATA. 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 link.webarata3.kexcelapi import org.apache.poi.ss.usermodel.* import java.io.FileInputStream import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.util.* import java.util.regex.Pattern class KExcel { companion object { @JvmStatic fun open(fileName: String): Workbook { return WorkbookFactory.create(FileInputStream(Paths.get(fileName).toFile())) } @JvmStatic fun write(workbook: Workbook, fileName: String) { val outputPath = Paths.get(fileName) try { Files.newOutputStream(outputPath).use { workbook.write(it) } } catch (e: IOException) { throw e } } @JvmStatic fun cellIndexToCellLabel(x: Int, y: Int): String { require(x >= 0, { "xは0以上でなければなりません" }) require(y >= 0, { "yは0以上でなければなりません" }) val cellName = dec26(x, 0) return cellName + (y + 1) } @JvmStatic private fun dec26(num: Int, first: Int): String { return if (num > 25) { dec26(num / 26, 1) } else { "" } + ('A' + (num - first) % 26) } } } operator fun Workbook.get(n: Int): Sheet { return this.getSheetAt(n) } operator fun Workbook.get(name: String): Sheet { return this.getSheet(name) } operator fun Sheet.get(n: Int): Row { return getRow(n) ?: createRow(n) } operator fun Row.get(n: Int): Cell { return getCell(n) ?: createCell(n, CellType.BLANK) } operator fun Sheet.get(x: Int, y: Int): Cell { val row = this[y] return row[x] } private val RADIX = 26 // https://github.com/nobeans/gexcelapi/blob/master/src/main/groovy/org/jggug/kobo/gexcelapi/GExcel.groovy operator fun Sheet.get(cellLabel: String): Cell { val p1 = Pattern.compile("([a-zA-Z]+)([0-9]+)") val matcher = p1.matcher(cellLabel) matcher.find() var num = 0 matcher.group(1).toUpperCase().reversed().forEachIndexed { i, c -> val delta = c.toInt() - 'A'.toInt() + 1 num += delta * Math.pow(RADIX.toDouble(), i.toDouble()).toInt() } num -= 1 return this[num, matcher.group(2).toInt() - 1] } fun Cell.toStr(): String = CellProxy(this).toStr() fun Cell.toInt(): Int = CellProxy(this).toInt() fun Cell.toDouble(): Double = CellProxy(this).toDouble() fun Cell.toBoolean(): Boolean = CellProxy(this).toBoolean() fun Cell.toDate(): Date = CellProxy(this).toDate() operator fun Sheet.set(cellLabel: String, value: Any) { this[cellLabel].setValue(value) } operator fun Sheet.set(x: Int, y: Int, value: Any) { this[x, y].setValue(value) } private fun Cell.setValue(value: Any) { when (value) { is String -> setCellValue(value) is Int -> setCellValue(value.toDouble()) is Double -> setCellValue(value) is Boolean -> setCellValue(value) is Date -> { // 日付セルはフォーマットしてあげないと日付型にならない setCellValue(value) val wb = sheet.workbook val createHelper = wb.creationHelper val cellStyle = wb.createCellStyle() val style = createHelper.createDataFormat().getFormat("yyyy/m/d") cellStyle.dataFormat = style setCellStyle(cellStyle) } else -> throw IllegalArgumentException("String、Int、Double、Boolean、Dateのみ対応しています") } }
mit
5ecd62487fa1b77c089c16b6ffb01293
30.040816
106
0.642998
3.749384
false
false
false
false
light-and-salt/kotloid
src/main/kotlin/kr/or/lightsalt/kotloid/text.kt
1
1053
package kr.or.lightsalt.kotloid import android.os.Build import kr.or.lightsalt.longDatePattern import kr.or.lightsalt.monthAndDayPattern import org.joda.time.LocalDate import java.text.DateFormat import java.text.SimpleDateFormat import java.util.* val bestDateFormat: DateFormat by lazy { val locale = Locale.getDefault() SimpleDateFormat(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) android.text.format.DateFormat.getBestDateTimePattern(locale, "yMdE") else longDatePattern, locale) } val bestMonthDayFormat: DateFormat by lazy { val locale = Locale.getDefault() SimpleDateFormat(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) android.text.format.DateFormat.getBestDateTimePattern(locale, "MdE") else monthAndDayPattern, locale) } val Date.bestDate: String get() = (if (LocalDate(time).year == LocalDate().year) bestMonthDayFormat else bestDateFormat) .format(this) val LocalDate.bestDate: String get() = (if (year == LocalDate().year) bestMonthDayFormat else bestDateFormat).format(toDate())
apache-2.0
e5fcabf886dafd56ab6b9ec22658878e
34.1
96
0.788224
3.51
false
false
false
false
andela-kogunde/CheckSmarter
app/src/main/kotlin/com/andela/checksmarter/views/CheckSmarterTaskView.kt
1
3876
package com.andela.checksmarter.views import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.helper.ItemTouchHelper import android.util.AttributeSet import android.util.Log import android.widget.LinearLayout import android.widget.Toast import com.andela.checksmarter.adapters.CheckSmarterTaskAdapter import com.andela.checksmarter.model.* import com.andela.checksmarter.utilities.* import com.andela.checksmarter.utilities.databaseCollection.DBCollection import io.realm.Realm import io.realm.RealmList import kotlinx.android.synthetic.main.fragment_detail.view.* import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.functions.Func1 import rx.schedulers.Schedulers import rx.subjects.PublishSubject import rx.subscriptions.CompositeSubscription import java.util.* import kotlin.properties.Delegates /** * Created by CodeKenn on 20/04/16. */ class CheckSmarterTaskView(context: Context?, attrs: AttributeSet?) : LinearLayout(context, attrs), CheckSmarterTaskAdapter.CheckSmarterTaskClickListener { val CHECK_SMARTER = "checksmarter" val checkSmarterTaskAdapter = CheckSmarterTaskAdapter(this) val subscriptions = CompositeSubscription() var currentCheckSmarter: CheckSmarterJava? = null var publishSubject: PublishSubject<CheckSmarterTaskJava> by Delegates.notNull() val dbCollection = DBCollection() private fun initializeComponents() { checkSmarterTaskView.layoutManager = CheckSmarterLinearLayoutManager(context) checkSmarterTaskView.adapter = checkSmarterTaskAdapter } override fun onFinishInflate() { super.onFinishInflate() initializeComponents() setCheckSmarter() } override fun onAttachedToWindow() { super.onAttachedToWindow() publishSubject = PublishSubject.create() val result = publishSubject .flatMap(checkSmarterTaskSearch) .observeOn(AndroidSchedulers.mainThread()) .share() subscriptions.add(result .subscribe(checkSmarterTaskAdapter)) post { publishSubject.onNext(CheckSmarterTaskJava(0)) } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() subscriptions.unsubscribe() updateChanges() } override fun onCheckSmarterTaskClick(checkSmarterTask: CheckSmarterTaskJava) { Log.d("TASK", checkSmarterTask.id.toString()) } override fun onCheckSmarterTaskLongClick(checkSmarterTask: CheckSmarterTaskJava) { currentCheckSmarter?.tasks?.remove(checkSmarterTask) checkSmarterTaskAdapter.notifyDataSetChanged() } private fun setCheckSmarter() { var checkSmarter: CheckSmarterDup? = Intents().getExtra(context, CHECK_SMARTER) if (checkSmarter != null) { this.currentCheckSmarter = Exchange().getRealmCheckSmarter(checkSmarter) } else { this.currentCheckSmarter = CheckSmarterJava() this.currentCheckSmarter?.id = dbCollection.getNextInt(CheckSmarterJava::class.java) } } private val checkSmarterTaskSearch = Func1<CheckSmarterTaskJava, Observable<RealmList<CheckSmarterTaskJava>>> { checkSmarterTask -> Observable.just(currentCheckSmarter?.tasks!!).subscribeOn(Schedulers.io()) } fun postCheckSmarterTask(title: String) { dbCollection.updateObject { var checkSmarterTask = CheckSmarterTaskJava() checkSmarterTask.id = dbCollection.getNextInt(CheckSmarterTaskJava::class.java) checkSmarterTask.title = title currentCheckSmarter?.tasks?.add(checkSmarterTask) } checkSmarterTaskAdapter.notifyItemInserted(0) } private fun updateChanges() { dbCollection.createOrUpdate(this.currentCheckSmarter!!) } }
mit
cca45df74b3c04764b919c4ec86bc329
34.568807
155
0.737616
5.040312
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/PlacesFile.kt
1
2369
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.tools.places import uk.co.nickthecoder.paratask.util.Resource import uk.co.nickthecoder.paratask.util.child import uk.co.nickthecoder.paratask.util.homeDirectory import java.io.File import java.net.URL class PlacesFile(val file: File) { val places = if (file.exists()) { file.readLines().map { parseLine(it) }.toMutableList() } else { mutableListOf<PlaceInFile>() } fun remove(place: Place) { val foundPlace: Place? = places.filter { it.label == place.label && it.resource == place.resource }.firstOrNull() foundPlace?.let { places.remove(it) } } fun save() { file.writeText(places.joinToString(separator = "\n", postfix = "\n")) } private fun parseLine(line: String): PlaceInFile { val space = line.indexOf(' ') val urlString = if (space >= 0) line.substring(0, space) else line var label: String if (space >= 0) { label = line.substring(space).trim() } else { try { val url = URL(urlString) val filePart = File(url.file) label = filePart.name } catch (e: Exception) { label = "" } } val url = URL(urlString) if (urlString.startsWith("file:")) { val file = File(url.toURI()) return PlaceInFile(this, Resource(file), label) } else { return PlaceInFile(this, Resource(urlString), label) } } fun taskNew(): NewPlaceTask = NewPlaceTask(this) companion object { val defaultFile = homeDirectory.child(".config", "gtk-3.0", "bookmarks") } }
gpl-3.0
71eb3ca31eb50e4e17fe540415b08f39
30.586667
121
0.637822
4.141608
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/ui/ProjectIndicatorServiceIT.kt
1
4317
package net.nemerosa.ontrack.extension.indicators.ui import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.extension.indicators.AbstractIndicatorsTestSupport import net.nemerosa.ontrack.json.asJson import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import java.time.Duration import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class ProjectIndicatorServiceIT : AbstractIndicatorsTestSupport() { @Autowired private lateinit var projectIndicatorService: ProjectIndicatorService @Test fun `Life cycle of project indicators`() { val category = category() val type = category.booleanType() project project@{ asAdmin { // No indicator yet projectIndicatorService.getProjectCategoryIndicators(id, false).apply { assertTrue(isEmpty(), "No indicator yet") } // Sets an indicator projectIndicatorService.updateIndicator(id, type.id, mapOf( "value" to "false" ).asJson()) assertIndicatorValueIs(type, false) // Updates the indicator again projectIndicatorService.updateIndicator(id, type.id, mapOf( "value" to "true" ).asJson()) assertIndicatorValueIs(type, true) // Gets the list of indicators projectIndicatorService.getProjectCategoryIndicators(id, false).apply { assertEquals(1, size) first().apply { assertEquals(category, this.category) assertEquals(this@project, this.project) assertEquals(1, this.indicators.size) this.indicators.first().apply { assertEquals( mapOf("value" to "true").asJson(), this.value ) } } } // Deletes the indicator projectIndicatorService.deleteIndicator(id, type.id) projectIndicatorService.getProjectCategoryIndicators(id, false).apply { assertTrue(isEmpty(), "No indicator yet") } } } } @Test fun `Previous indicator`() { // Trend times val duration = Duration.ofDays(7) val lastTime = Time.now() - Duration.ofDays(1) val pastTime = lastTime - duration // Category & type val category = category() val type = category.booleanType() project { // Sets indicators indicator(type, false, pastTime) indicator(type, true, lastTime) // Gets a previous indicator asAdmin { val indicator = projectIndicatorService.getProjectCategoryIndicators(id, false).first().indicators.first() assertEquals(mapOf("value" to "true").asJson(), indicator.value) val previousIndicator = projectIndicatorService.getPreviousIndicator(indicator) assertEquals(this, previousIndicator.project) assertEquals(mapOf("value" to "false").asJson(), previousIndicator.value) } } } @Test fun `Update form for a project indicator always adds the comment memo field`() { val category = category() val type = category.booleanType() project { indicator(type, value = true, comment = "Some comment") asAdmin { val form = projectIndicatorService.getUpdateFormForIndicator(id, type.id) // Checks the value field assertNotNull(form.getField("value")) { f -> assertEquals("selection", f.type) assertEquals("true", f.value) } // Checks the comment field assertNotNull(form.getField("comment")) { f -> assertEquals("memo", f.type) assertEquals("Some comment", f.value) } } } } }
mit
89bb58f332ea31c6af7a504421e3de2a
38.981481
122
0.55432
5.63577
false
true
false
false
RedstonerServer/Parcels
dicore3/command/src/main/kotlin/io/dico/dicore/command/registration/reflect/KotlinReflectiveRegistration.kt
1
2497
package io.dico.dicore.command.registration.reflect import io.dico.dicore.command.* import kotlinx.coroutines.CoroutineStart.UNDISPATCHED import kotlinx.coroutines.Deferred import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import java.lang.reflect.Method import java.util.concurrent.CancellationException import kotlin.coroutines.CoroutineContext import kotlin.coroutines.intrinsics.intercepted import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn import kotlin.reflect.jvm.kotlinFunction fun isSuspendFunction(method: Method): Boolean { val func = method.kotlinFunction ?: return false return func.isSuspend } @Throws(CommandException::class) fun callCommandAsCoroutine( executionContext: ExecutionContext, coroutineContext: CoroutineContext, continuationIndex: Int, method: Method, instance: Any?, args: Array<Any?> ): String? { // UNDISPATCHED causes the handler to run until the first suspension point on the current thread, // meaning command handlers that don't have suspension points will run completely synchronously. // Tasks that take time to compute should suspend the coroutine and resume on another thread. val job = GlobalScope.async(context = coroutineContext, start = UNDISPATCHED) { suspendCoroutineUninterceptedOrReturn<Any?> { cont -> args[continuationIndex] = cont.intercepted() method.invoke(instance, *args) } } if (job.isCompleted) { return job.getResult() } job.invokeOnCompletion { val chatHandler = executionContext.address.chatHandler try { val result = job.getResult() chatHandler.sendMessage(executionContext.sender, EMessageType.RESULT, result) } catch (ex: Throwable) { chatHandler.handleException(executionContext.sender, executionContext, ex) } } return null } @Throws(CommandException::class) private fun Deferred<Any?>.getResult(): String? { getCompletionExceptionOrNull()?.let { ex -> if (ex is CancellationException) { System.err.println("An asynchronously dispatched command was cancelled unexpectedly") ex.printStackTrace() throw CommandException("The command was cancelled unexpectedly (see console)") } if (ex is Exception) return ReflectiveCommand.getResult(null, ex) throw ex } return ReflectiveCommand.getResult(getCompleted(), null) }
gpl-2.0
eb82cc17c4cc582ce2d0ea5e65f21e6a
35.188406
101
0.727273
5.044444
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/ui/main/MainPresenter.kt
1
2173
package treehou.se.habit.ui.main import android.os.Bundle import android.support.v4.text.TextUtilsCompat import android.text.TextUtils import javax.inject.Inject import io.realm.Realm import se.treehou.ng.ohcommunicator.connector.models.OHSitemap import treehou.se.habit.core.db.model.ServerDB import treehou.se.habit.util.Settings open class MainPresenter @Inject constructor(private val mainView: MainContract.View, private val realm: Realm, private val settings: Settings) : MainContract.Presenter { override fun load(launchData: Bundle?, savedData: Bundle?) { setupFragments(savedData) } override fun subscribe() {} override fun unsubscribe() {} override fun unload() { } /** * Setup the saved instance state. * @param savedInstanceState saved instance state */ private fun setupFragments(savedInstanceState: Bundle?) { if (!mainView.hasOpenPage()) { // Load server setup server fragment if no server found val serverDBs = realm.where(ServerDB::class.java).findAll() if (serverDBs.size <= 0) { mainView.openServers() } else { // Load default sitemap if any val defaultSitemap = settings.defaultSitemap val autoloadLast = settings.autoloadSitemapRx.blockingFirst() if (savedInstanceState == null && !TextUtils.isEmpty(defaultSitemap) && autoloadLast) { mainView.openSitemaps(defaultSitemap) } else { mainView.openSitemaps() } } } } override fun save(savedData: Bundle?) {} override fun showSitemaps() { mainView.openSitemaps() } override fun showSitemap(ohSitemap: OHSitemap) { mainView.openSitemap(ohSitemap) } override fun showControllers() { mainView.openControllers() } override fun showServers() { mainView.openServers() } override fun showSettings() { mainView.openSettings() } companion object { private val TAG = MainPresenter::class.java.simpleName } }
epl-1.0
a006b79e6a60c7dfec6c466a95f836af
25.82716
137
0.638748
4.693305
false
false
false
false
genobis/tornadofx
src/test/kotlin/tornadofx/tests/PropertiesTest.kt
3
84498
package tornadofx.tests import javafx.beans.binding.DoubleBinding import javafx.beans.binding.FloatBinding import javafx.beans.binding.IntegerBinding import javafx.beans.binding.LongBinding import javafx.beans.property.* import javafx.collections.FXCollections import org.junit.Assert import org.junit.Assert.assertTrue import org.junit.Test import tornadofx.* import kotlin.test.assertEquals class PropertiesTest { @Test fun primitiveOnChange() { val d = SimpleDoubleProperty() // Ensure getting the value does not throw an NPE d.onChange { assert((it + 7) is Double) } d.value = 100.0 d.value = Double.POSITIVE_INFINITY d.value = Double.NaN d.value = null } @Test fun property_delegation() { // given: val fixture = object { val nameProperty = SimpleStringProperty("Alice") var name by nameProperty val ageProperty = SimpleDoubleProperty(1.0) var age by ageProperty val dirtyProperty = SimpleBooleanProperty(false) var dirty by dirtyProperty } // expect: assertEquals("Alice", fixture.name) assertEquals("Alice", fixture.nameProperty.value) assertEquals(1.0, fixture.age) assertEquals(1.0, fixture.ageProperty.value) assertEquals(false, fixture.dirty) assertEquals(false, fixture.dirtyProperty.value) // when: fixture.name = "Bob" fixture.age = 100.0 fixture.dirty = true // expect: assertEquals("Bob", fixture.name) assertEquals("Bob", fixture.nameProperty.value) assertEquals(100.0, fixture.age) assertEquals(100.0, fixture.ageProperty.value) assertEquals(true, fixture.dirty) assertEquals(true, fixture.dirtyProperty.value) } @Test fun property_get_should_read_value() { // given: val fixture = object { val string by property<String>() val integer: Int? by property() val stringDefault by property("foo") val integerDefault by property(42) } // expect: assertEquals(null, fixture.string) assertEquals(null, fixture.integer) assertEquals("foo", fixture.stringDefault) assertEquals(42, fixture.integerDefault) } @Test fun property_set_should_write_value() { // given: val fixture = object { var string by property<String>() var integer: Int? by property() var stringDefault by property("foo") var integerDefault by property(42) } // when: fixture.string = "foo" fixture.integer = 42 // then: assertEquals("foo", fixture.string) assertEquals("foo", fixture.stringDefault) assertEquals(42, fixture.integer) assertEquals(42, fixture.integerDefault) } class TestClass { var myProperty: String by singleAssign() } @Test fun failNoAssignment() { val instance = TestClass() var failed = false try { instance.myProperty } catch (e: Exception) { failed = true } assertTrue(failed) } @Test fun succeedAssignment() { val instance = TestClass() instance.myProperty = "foo" instance.myProperty } @Test fun failDoubleAssignment() { val instance = TestClass() var failed = false instance.myProperty = "foo" try { instance.myProperty = "bar" } catch (e: Exception) { failed = true } assertTrue(failed) } @Test fun pojoWritableObservable() { val person = JavaPerson() person.id = 1 person.name = "John" val idObservable = person.observable(JavaPerson::getId, JavaPerson::setId) val nameObservable = person.observable<String>("name") idObservable.value = 44 nameObservable.value = "Doe" Assert.assertEquals(44, person.id) Assert.assertEquals("Doe", person.name) person.id = 5 Assert.assertEquals(5, idObservable.value) } @Test fun pojoWritableObservableGetterOnly() { val person = JavaPerson() person.id = 1 person.name = "John" val idObservable = person.observable(JavaPerson::getId) val nameObservable = person.observable<String>("name") val idBinding = idObservable.integerBinding { idObservable.value } idObservable.value = 44 nameObservable.value = "Doe" Assert.assertEquals(44, idBinding.value) Assert.assertEquals(44, person.id) Assert.assertEquals("Doe", person.name) person.id = 5 // property change events on the pojo are propogated Assert.assertEquals(5, idBinding.value) Assert.assertEquals(5, idObservable.value) } @Test fun property_on_change() { var called = false val property = SimpleStringProperty("Hello World") property.onChange { called = true } property.value = "Changed" assertTrue(called) } @Test fun assign_if_null() { val has = SimpleObjectProperty("Hello") has.assignIfNull { "World" } assertEquals(has.value, "Hello") val hasNot = SimpleObjectProperty<String>() hasNot.assignIfNull { "World" } assertEquals(hasNot.value, "World") } @Test fun testDoubleToProperty() { val property = 5.0.toProperty() Assert.assertTrue(property is DoubleProperty) Assert.assertEquals(5.0, property.get(), .001) } @Test fun testFloatToProperty() { val property = 5.0f.toProperty() Assert.assertTrue(property is FloatProperty) Assert.assertEquals(5.0f, property.get(), .001f) } @Test fun testLongToProperty() { val property = 5L.toProperty() Assert.assertTrue(property is LongProperty) Assert.assertEquals(5, property.get()) } @Test fun testIntToProperty() { val property = 5.toProperty() Assert.assertTrue(property is IntegerProperty) Assert.assertEquals(5, property.get()) } @Test fun testBooleanToProperty() { val property = true.toProperty() Assert.assertTrue(property is BooleanProperty) Assert.assertTrue(property.get()) } @Test fun testStringToProperty() { val property = "Hello World!".toProperty() Assert.assertTrue(property is StringProperty) Assert.assertEquals("Hello World!", property.get()) } @Test fun testDoubleExpressionPlusNumber() { val property = 0.0.toProperty() val binding = property + 5 Assert.assertEquals(5.0, binding.get(), .001) property.value -= 5f Assert.assertEquals(0.0, binding.get(), .001) } @Test fun testDoubleExpressionPlusNumberProperty() { val property1 = 0.0.toProperty() val property2 = 5.toProperty() val binding = property1 + property2 Assert.assertEquals(5.0, binding.get(), .001) property1.value -= 10 Assert.assertEquals(-5.0, binding.get(), .001) property2.value = 0 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testDoublePropertyPlusAssignNumber() { val property = 0.0.toProperty() property += 5 Assert.assertEquals(5.0, property.get(), .001) } @Test fun testDoublePropertyPlusAssignNumberProperty() { val property1 = 0.0.toProperty() val property2 = 5.toProperty() property1 += property2 Assert.assertEquals(5.0, property1.get(), .001) } @Test fun testDoubleExpressionMinusNumber() { val property = 0.0.toProperty() val binding = property - 5 Assert.assertEquals(-5.0, binding.get(), .001) property.value -= 5f Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testDoubleExpressionMinusNumberProperty() { val property1 = 0.0.toProperty() val property2 = 5.toProperty() val binding = property1 - property2 Assert.assertEquals(-5.0, binding.get(), .001) property1.value -= 10 Assert.assertEquals(-15.0, binding.get(), .001) property2.value = 0 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testDoublePropertyMinusAssignNumber() { val property = 0.0.toProperty() property -= 5 Assert.assertEquals(-5.0, property.get(), .001) } @Test fun testDoublePropertyMinusAssignNumberProperty() { val property1 = 0.0.toProperty() val property2 = 5.toProperty() property1 -= property2 Assert.assertEquals(-5.0, property1.get(), .001) } @Test fun testDoublePropertyUnaryMinus() { val property = 1.0.toProperty() val binding = -property Assert.assertEquals(-1.0, binding.get(), .001) property += 1 Assert.assertEquals(-2.0, binding.get(), .001) } @Test fun testDoubleExpressionTimesNumber() { val property = 2.0.toProperty() val binding = property * 5 Assert.assertEquals(10.0, binding.get(), .001) property.value = 5.0 Assert.assertEquals(25.0, binding.get(), .001) } @Test fun testDoubleExpressionTimesNumberProperty() { val property1 = 2.0.toProperty() val property2 = 5.toProperty() val binding = property1 * property2 Assert.assertEquals(10.0, binding.get(), .001) property1.value = 5.0 Assert.assertEquals(25.0, binding.get(), .001) property2.value = 0 Assert.assertEquals(0.0, binding.get(), .001) } @Test fun testDoublePropertyTimesAssignNumber() { val property = 1.0.toProperty() property *= 5 Assert.assertEquals(5.0, property.get(), .001) } @Test fun testDoublePropertyTimesAssignNumberProperty() { val property1 = 1.0.toProperty() val property2 = 5.toProperty() property1 *= property2 Assert.assertEquals(5.0, property1.get(), .001) } @Test fun testDoubleExpressionDivNumber() { val property = 5.0.toProperty() val binding = property / 5 Assert.assertEquals(1.0, binding.get(), .001) property.value = 10.0 Assert.assertEquals(2.0, binding.get(), .001) } @Test fun testDoubleExpressionDivNumberProperty() { val property1 = 5.0.toProperty() val property2 = 5.toProperty() val binding = property1 / property2 Assert.assertEquals(1.0, binding.get(), .001) property1.value = 10.0 Assert.assertEquals(2.0, binding.get(), .001) property2.value = 20 Assert.assertEquals(0.5, binding.get(), .001) } @Test fun testDoublePropertyDivAssignNumber() { val property = 5.0.toProperty() property /= 5 Assert.assertEquals(1.0, property.get(), .001) } @Test fun testDoublePropertyDivAssignNumberProperty() { val property1 = 5.0.toProperty() val property2 = 5.toProperty() property1 /= property2 Assert.assertEquals(1.0, property1.get(), .001) } @Test fun testDoubleExpressionRemNumber() { val property = 6.0.toProperty() val binding = property % 5 Assert.assertEquals(1.0, binding.get(), .001) property.value = 12.0 Assert.assertEquals(2.0, binding.get(), .001) } @Test fun testDoubleExpressionRemNumberProperty() { val property1 = 6.0.toProperty() val property2 = 5.toProperty() val binding = property1 % property2 Assert.assertEquals(1.0, binding.get(), .001) property1.value = 12.0 Assert.assertEquals(2.0, binding.get(), .001) property2.value = 11 Assert.assertEquals(1.0, binding.get(), .001) } @Test fun testDoublePropertyRemAssignNumber() { val property = 6.0.toProperty() property %= 5 Assert.assertEquals(1.0, property.get(), .001) } @Test fun testDoublePropertyRemAssignNumberProperty() { val property1 = 6.0.toProperty() val property2 = 5.toProperty() property1 %= property2 Assert.assertEquals(1.0, property1.get(), .001) } @Test fun testDoublePropertyCompareToNumber() { val property = 5.0.toProperty() Assert.assertTrue(property > 4) Assert.assertTrue(property >= 5) Assert.assertTrue(property >= 4) Assert.assertTrue(property <= 5) Assert.assertTrue(property <= 5) Assert.assertTrue(property <= 6) Assert.assertTrue(property < 6) Assert.assertFalse(property > 6) Assert.assertFalse(property >= 6) Assert.assertFalse(property <= 4) Assert.assertFalse(property < 4) } @Test fun testDoublePropertyCompareToNumberProperty() { val property = 5.0.toProperty() Assert.assertTrue(property > 4.toProperty()) Assert.assertTrue(property >= 5.toProperty()) Assert.assertTrue(property >= 4.toProperty()) Assert.assertTrue(property <= 5.toProperty()) Assert.assertTrue(property <= 5.toProperty()) Assert.assertTrue(property <= 6.toProperty()) Assert.assertTrue(property < 6.toProperty()) Assert.assertFalse(property > 6.toProperty()) Assert.assertFalse(property >= 6.toProperty()) Assert.assertFalse(property <= 4.toProperty()) Assert.assertFalse(property < 4.toProperty()) } @Test fun testFloatExpressionPlusNumber() { val property = 0.0f.toProperty() val binding = property + 5 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(5.0f, binding.get(), .001f) property.value -= 5f Assert.assertEquals(0.0f, binding.get(), .001f) } @Test fun testFloatExpressionPlusDouble() { val property = 0.0f.toProperty() val binding = property + 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(5.0, binding.get(), .001) property.value -= 5f Assert.assertEquals(0.0, binding.get(), .001) } @Test fun testFloatExpressionPlusNumberProperty() { val property1 = 0.0f.toProperty() val property2 = 5.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(5.0f, binding.get(), .001f) property1.value -= 10f Assert.assertEquals(-5.0f, binding.get(), .001f) property2.value = 0 Assert.assertEquals(-10.0f, binding.get(), .001f) } @Test fun testFloatExpressionPlusDoubleProperty() { val property1 = 0.0f.toProperty() val property2 = 5.0.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(5.0, binding.get(), .001) property1.value -= 10f Assert.assertEquals(-5.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testFloatPropertyPlusAssignNumber() { val property = 0.0f.toProperty() property += 5 Assert.assertEquals(5.0f, property.get(), .001f) } @Test fun testFloatPropertyPlusAssignNumberProperty() { val property1 = 0.0f.toProperty() val property2 = 5.toProperty() property1 += property2 Assert.assertEquals(5.0f, property1.get(), .001f) } @Test fun testFloatExpressionMinusNumber() { val property = 0.0f.toProperty() val binding = property - 5 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(-5.0f, binding.get(), .001f) property.value -= 5f Assert.assertEquals(-10.0f, binding.get(), .001f) } @Test fun testFloatExpressionMinusDouble() { val property = 0.0f.toProperty() val binding = property - 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(-5.0, binding.get(), .001) property.value -= 5f Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testFloatExpressionMinusNumberProperty() { val property1 = 0.0f.toProperty() val property2 = 5.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(-5.0f, binding.get(), .001f) property1.value -= 10f Assert.assertEquals(-15.0f, binding.get(), .001f) property2.value = 0 Assert.assertEquals(-10.0f, binding.get(), .001f) } @Test fun testFloatExpressionMinusDoubleProperty() { val property1 = 0.0f.toProperty() val property2 = 5.0.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(-5.0, binding.get(), .001) property1.value -= 10f Assert.assertEquals(-15.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testFloatPropertyMinusAssignNumber() { val property = 0.0f.toProperty() property -= 5 Assert.assertEquals(-5.0f, property.get(), .001f) } @Test fun testFloatPropertyMinusAssignNumberProperty() { val property1 = 0.0f.toProperty() val property2 = 5.toProperty() property1 -= property2 Assert.assertEquals(-5.0f, property1.get(), .001f) } @Test fun testFloatPropertyUnaryMinus() { val property = 1.0f.toProperty() val binding = -property Assert.assertEquals(-1.0f, binding.get(), .001f) property += 1 Assert.assertEquals(-2.0f, binding.get(), .001f) } @Test fun testFloatExpressionTimesNumber() { val property = 2.0f.toProperty() val binding = property * 5 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(10.0f, binding.get(), .001f) property.value = 5f Assert.assertEquals(25.0f, binding.get(), .001f) } @Test fun testFloatExpressionTimesDouble() { val property = 2.0f.toProperty() val binding = property * 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(10.0, binding.get(), .001) property.value = 5f Assert.assertEquals(25.0, binding.get(), .001) } @Test fun testFloatExpressionTimesNumberProperty() { val property1 = 2.0f.toProperty() val property2 = 5.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(10.0f, binding.get(), .001f) property1.value = 10f Assert.assertEquals(50.0f, binding.get(), .001f) property2.value = 0 Assert.assertEquals(0.0f, binding.get(), .001f) } @Test fun testFloatExpressionTimesDoubleProperty() { val property1 = 2.0f.toProperty() val property2 = 5.0.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(10.0, binding.get(), .001) property1.value = 10f Assert.assertEquals(50.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(0.0, binding.get(), .001) } @Test fun testFloatPropertyTimesAssignNumber() { val property = 1.0f.toProperty() property *= 5 Assert.assertEquals(5.0f, property.get(), .001f) } @Test fun testFloatPropertyTimesAssignNumberProperty() { val property1 = 1.0f.toProperty() val property2 = 5.toProperty() property1 *= property2 Assert.assertEquals(5.0f, property1.get(), .001f) } @Test fun testFloatExpressionDivNumber() { val property = 5.0f.toProperty() val binding = property / 5 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(1.0f, binding.get(), .001f) property.value = 10f Assert.assertEquals(2.0f, binding.get(), .001f) } @Test fun testFloatExpressionDivDouble() { val property = 5.0f.toProperty() val binding = property / 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(1.0, binding.get(), .001) property.value = 10f Assert.assertEquals(2.0, binding.get(), .001) } @Test fun testFloatExpressionDivNumberProperty() { val property1 = 5.0f.toProperty() val property2 = 5.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(1.0f, binding.get(), .001f) property1.value = 10f Assert.assertEquals(2.0f, binding.get(), .001f) property2.value = 20 Assert.assertEquals(0.5f, binding.get(), .001f) } @Test fun testFloatExpressionDivDoubleProperty() { val property1 = 5.0f.toProperty() val property2 = 5.0.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(1.0, binding.get(), .001) property1.value = 10f Assert.assertEquals(2.0, binding.get(), .001) property2.value = 20.0 Assert.assertEquals(0.5, binding.get(), .001) } @Test fun testFloatPropertyDivAssignNumber() { val property = 5.0f.toProperty() property /= 5 Assert.assertEquals(1.0f, property.get(), .001f) } @Test fun testFloatPropertyDivAssignNumberProperty() { val property1 = 5.0f.toProperty() val property2 = 5.toProperty() property1 /= property2 Assert.assertEquals(1.0f, property1.get(), .001f) } @Test fun testFloatExpressionRemNumber() { val property = 6.0f.toProperty() val binding = property % 5 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(1.0f, binding.get(), .001f) property.value = 12.0f Assert.assertEquals(2.0f, binding.get(), .001f) } @Test fun testFloatExpressionRemDouble() { val property = 6.0f.toProperty() val binding = property % 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(1.0, binding.get(), .001) property.value = 12.0f Assert.assertEquals(2.0, binding.get(), .001) } @Test fun testFloatExpressionRemNumberProperty() { val property1 = 6.0f.toProperty() val property2 = 5.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(1.0f, binding.get(), .001f) property1.value = 12f Assert.assertEquals(2.0f, binding.get(), .001f) property2.value = 11 Assert.assertEquals(1.0f, binding.get(), .001f) } @Test fun testFloatExpressionRemDoubleProperty() { val property1 = 6.0f.toProperty() val property2 = 5.0.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(1.0, binding.get(), .001) property1.value = 12f Assert.assertEquals(2.0, binding.get(), .001) property2.value = 11.0 Assert.assertEquals(1.0, binding.get(), .001) } @Test fun testFloatPropertyRemAssignNumber() { val property = 6.0f.toProperty() property %= 5 Assert.assertEquals(1.0f, property.get(), .001f) } @Test fun testFloatPropertyRemAssignNumberProperty() { val property1 = 6.0f.toProperty() val property2 = 5.toProperty() property1 %= property2 Assert.assertEquals(1.0f, property1.get(), .001f) } @Test fun testFloatPropertyCompareToNumber() { val property = 5.0f.toProperty() Assert.assertTrue(property > 4) Assert.assertTrue(property >= 5) Assert.assertTrue(property >= 4) Assert.assertTrue(property <= 5) Assert.assertTrue(property <= 5) Assert.assertTrue(property <= 6) Assert.assertTrue(property < 6) Assert.assertFalse(property > 6) Assert.assertFalse(property >= 6) Assert.assertFalse(property <= 4) Assert.assertFalse(property < 4) } @Test fun testFloatPropertyCompareToNumberProperty() { val property = 5.0f.toProperty() Assert.assertTrue(property > 4.toProperty()) Assert.assertTrue(property >= 5.toProperty()) Assert.assertTrue(property >= 4.toProperty()) Assert.assertTrue(property <= 5.toProperty()) Assert.assertTrue(property <= 5.toProperty()) Assert.assertTrue(property <= 6.toProperty()) Assert.assertTrue(property < 6.toProperty()) Assert.assertFalse(property > 6.toProperty()) Assert.assertFalse(property >= 6.toProperty()) Assert.assertFalse(property <= 4.toProperty()) Assert.assertFalse(property < 4.toProperty()) } @Test fun testIntegerExpressionPlusInt() { val property = 0.toProperty() val binding = property + 5 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(5, binding.get()) property.value -= 5 Assert.assertEquals(0, binding.get()) } @Test fun testIntegerExpressionPlusLong() { val property = 0.toProperty() val binding = property + 5L Assert.assertTrue(binding is LongBinding) Assert.assertEquals(5L, binding.get()) property.value -= 5 Assert.assertEquals(0, binding.get()) } @Test fun testIntegerExpressionPlusFloat() { val property = 0.toProperty() val binding = property + 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(5f, binding.get(), .001f) property.value -= 5 Assert.assertEquals(0f, binding.get(), .001f) } @Test fun testIntegerExpressionPlusDouble() { val property = 0.toProperty() val binding = property + 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(5.0, binding.get(), .001) property.value -= 5 Assert.assertEquals(0.0, binding.get(), .001) } @Test fun testIntegerExpressionPlusIntegerProperty() { val property1 = 0.toProperty() val property2 = 5.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(5, binding.get()) property1.value -= 10 Assert.assertEquals(-5, binding.get()) property2.value = 0 Assert.assertEquals(-10, binding.get()) } @Test fun testIntegerExpressionPlusLongProperty() { val property1 = 0.toProperty() val property2 = 5L.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(5L, binding.get()) property1.value -= 10 Assert.assertEquals(-5L, binding.get()) property2.value = 0L Assert.assertEquals(-10L, binding.get()) } @Test fun testIntegerExpressionPlusFloatProperty() { val property1 = 0.toProperty() val property2 = 5f.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(5f, binding.get(), .001f) property1.value -= 10 Assert.assertEquals(-5f, binding.get(), .001f) property2.value = 0f Assert.assertEquals(-10f, binding.get(), .001f) } @Test fun testIntegerExpressionPlusDoubleProperty() { val property1 = 0.toProperty() val property2 = 5.0.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(5.0, binding.get(), .001) property1.value -= 10 Assert.assertEquals(-5.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testIntegerPropertyPlusAssignNumber() { val property = 0.toProperty() property += 5 Assert.assertEquals(5, property.get()) } @Test fun testIntegerPropertyPlusAssignNumberProperty() { val property1 = 0.toProperty() val property2 = 5.toProperty() property1 += property2 Assert.assertEquals(5, property1.get()) } @Test fun testIntegerExpressionMinusInt() { val property = 0.toProperty() val binding = property - 5 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(-5, binding.get()) property.value -= 5 Assert.assertEquals(-10, binding.get()) } @Test fun testIntegerExpressionMinusLong() { val property = 0.toProperty() val binding = property - 5L Assert.assertTrue(binding is LongBinding) Assert.assertEquals(-5L, binding.get()) property.value -= 5 Assert.assertEquals(-10L, binding.get()) } @Test fun testIntegerExpressionMinusFloat() { val property = 0.toProperty() val binding = property - 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(-5f, binding.get(), .001f) property.value -= 5 Assert.assertEquals(-10f, binding.get(), .001f) } @Test fun testIntegerExpressionMinusDouble() { val property = 0.toProperty() val binding = property - 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(-5.0, binding.get(), .001) property.value -= 5 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testIntegerExpressionMinusIntegerProperty() { val property1 = 0.toProperty() val property2 = 5.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(-5, binding.get()) property1.value -= 10 Assert.assertEquals(-15, binding.get()) property2.value = 0 Assert.assertEquals(-10, binding.get()) } @Test fun testIntegerExpressionMinusLongProperty() { val property1 = 0.toProperty() val property2 = 5L.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(-5L, binding.get()) property1.value -= 10 Assert.assertEquals(-15L, binding.get()) property2.value = 0L Assert.assertEquals(-10L, binding.get()) } @Test fun testIntegerExpressionMinusFloatProperty() { val property1 = 0.toProperty() val property2 = 5f.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(-5f, binding.get(), .001f) property1.value -= 10 Assert.assertEquals(-15f, binding.get(), .001f) property2.value = 0f Assert.assertEquals(-10f, binding.get(), .001f) } @Test fun testIntegerExpressionMinusDoubleProperty() { val property1 = 0.toProperty() val property2 = 5.0.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(-5.0, binding.get(), .001) property1.value -= 10 Assert.assertEquals(-15.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testIntegerPropertyMinusAssignNumber() { val property = 0.toProperty() property -= 5 Assert.assertEquals(-5, property.get()) } @Test fun testIntegerPropertyMinusAssignNumberProperty() { val property1 = 0.toProperty() val property2 = 5.toProperty() property1 -= property2 Assert.assertEquals(-5, property1.get()) } @Test fun testIntegerPropertyUnaryMinus() { val property = 1.toProperty() val binding = -property Assert.assertEquals(-1, binding.get()) property += 1 Assert.assertEquals(-2, binding.get()) } @Test fun testIntegerExpressionTimesInt() { val property = 2.toProperty() val binding = property * 5 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(10, binding.get()) property.value = 5 Assert.assertEquals(25, binding.get()) } @Test fun testIntegerExpressionTimesLong() { val property = 2.toProperty() val binding = property * 5L Assert.assertTrue(binding is LongBinding) Assert.assertEquals(10L, binding.get()) property.value = 5 Assert.assertEquals(25L, binding.get()) } @Test fun testIntegerExpressionTimesFloat() { val property = 2.toProperty() val binding = property * 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(10f, binding.get(), .001f) property.value = 5 Assert.assertEquals(25f, binding.get(), .001f) } @Test fun testIntegerExpressionTimesDouble() { val property = 2.toProperty() val binding = property * 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(10.0, binding.get(), .001) property.value = 5 Assert.assertEquals(25.0, binding.get(), .001) } @Test fun testIntegerExpressionTimesIntegerProperty() { val property1 = 2.toProperty() val property2 = 5.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(10, binding.get()) property1.value = 10 Assert.assertEquals(50, binding.get()) property2.value = 0 Assert.assertEquals(0, binding.get()) } @Test fun testIntegerExpressionTimesLongProperty() { val property1 = 2.toProperty() val property2 = 5L.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(10L, binding.get()) property1.value = 10 Assert.assertEquals(50L, binding.get()) property2.value = 0L Assert.assertEquals(0L, binding.get()) } @Test fun testIntegerExpressionTimesFloatProperty() { val property1 = 2.toProperty() val property2 = 5f.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(10f, binding.get(), .001f) property1.value = 10 Assert.assertEquals(50f, binding.get(), .001f) property2.value = 0f Assert.assertEquals(0f, binding.get(), .001f) } @Test fun testIntegerExpressionTimesDoubleProperty() { val property1 = 2.toProperty() val property2 = 5.0.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(10.0, binding.get(), .001) property1.value = 10 Assert.assertEquals(50.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(0.0, binding.get(), .001) } @Test fun testIntegerPropertyTimesAssignNumber() { val property = 1.toProperty() property *= 5 Assert.assertEquals(5, property.get()) } @Test fun testIntegerPropertyTimesAssignNumberProperty() { val property1 = 1.toProperty() val property2 = 5.toProperty() property1 *= property2 Assert.assertEquals(5, property1.get()) } @Test fun testIntegerExpressionDivInt() { val property = 10.toProperty() val binding = property / 5 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(2, binding.get()) property.value = 20 Assert.assertEquals(4, binding.get()) } @Test fun testIntegerExpressionDivLong() { val property = 10.toProperty() val binding = property / 5L Assert.assertTrue(binding is LongBinding) Assert.assertEquals(2L, binding.get()) property.value = 20 Assert.assertEquals(4L, binding.get()) } @Test fun testIntegerExpressionDivFloat() { val property = 10.toProperty() val binding = property / 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(2f, binding.get(), .001f) property.value = 20 Assert.assertEquals(4f, binding.get(), .001f) } @Test fun testIntegerExpressionDivDouble() { val property = 10.toProperty() val binding = property / 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(2.0, binding.get(), .001) property.value = 20 Assert.assertEquals(4.0, binding.get(), .001) } @Test fun testIntegerExpressionDivIntegerProperty() { val property1 = 10.toProperty() val property2 = 5.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(2, binding.get()) property1.value = 20 Assert.assertEquals(4, binding.get()) property2.value = 20 Assert.assertEquals(1, binding.get()) } @Test fun testIntegerExpressionDivLongProperty() { val property1 = 10.toProperty() val property2 = 5L.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(2L, binding.get()) property1.value = 20 Assert.assertEquals(4L, binding.get()) property2.value = 20L Assert.assertEquals(1L, binding.get()) } @Test fun testIntegerExpressionDivFloatProperty() { val property1 = 10.toProperty() val property2 = 5f.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(2f, binding.get(), .001f) property1.value = 20 Assert.assertEquals(4f, binding.get(), .001f) property2.value = 20f Assert.assertEquals(1f, binding.get(), .001f) } @Test fun testIntegerExpressionDivDoubleProperty() { val property1 = 10.toProperty() val property2 = 5.0.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(2.0, binding.get(), .001) property1.value = 20 Assert.assertEquals(4.0, binding.get(), .001) property2.value = 20.0 Assert.assertEquals(1.0, binding.get(), .001) } @Test fun testIntegerPropertyDivAssignNumber() { val property = 5.toProperty() property /= 5 Assert.assertEquals(1, property.get()) } @Test fun testIntegerPropertyDivAssignNumberProperty() { val property1 = 5.toProperty() val property2 = 5.toProperty() property1 /= property2 Assert.assertEquals(1, property1.get()) } @Test fun testIntegerExpressionRemInt() { val property = 6.toProperty() val binding = property % 5 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(1, binding.get()) property.value = 12 Assert.assertEquals(2, binding.get()) } @Test fun testIntegerExpressionRemLong() { val property = 6.toProperty() val binding = property % 5L Assert.assertTrue(binding is LongBinding) Assert.assertEquals(1L, binding.get()) property.value = 12 Assert.assertEquals(2L, binding.get()) } @Test fun testIntegerExpressionRemFloat() { val property = 6.toProperty() val binding = property % 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(1f, binding.get(), .001f) property.value = 12 Assert.assertEquals(2f, binding.get(), .001f) } @Test fun testIntegerExpressionRemDouble() { val property = 6.toProperty() val binding = property % 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(1.0, binding.get(), .001) property.value = 12 Assert.assertEquals(2.0, binding.get(), .001) } @Test fun testIntegerExpressionRemIntegerProperty() { val property1 = 6.toProperty() val property2 = 5.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is IntegerBinding) Assert.assertEquals(1, binding.get()) property1.value = 12 Assert.assertEquals(2, binding.get()) property2.value = 11 Assert.assertEquals(1, binding.get()) } @Test fun testIntegerExpressionRemLongProperty() { val property1 = 6.toProperty() val property2 = 5L.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(1L, binding.get()) property1.value = 12 Assert.assertEquals(2L, binding.get()) property2.value = 11L Assert.assertEquals(1L, binding.get()) } @Test fun testIntegerExpressionRemFloatProperty() { val property1 = 6.toProperty() val property2 = 5f.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(1f, binding.get(), .001f) property1.value = 12 Assert.assertEquals(2f, binding.get(), .001f) property2.value = 11f Assert.assertEquals(1f, binding.get(), .001f) } @Test fun testIntegerExpressionRemDoubleProperty() { val property1 = 6.toProperty() val property2 = 5.0.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(1.0, binding.get(), .001) property1.value = 12 Assert.assertEquals(2.0, binding.get(), .001) property2.value = 11.0 Assert.assertEquals(1.0, binding.get(), .001) } @Test fun testIntegerPropertyRemAssignNumber() { val property = 6.toProperty() property %= 5 Assert.assertEquals(1, property.get()) } @Test fun testIntegerPropertyRemAssignNumberProperty() { val property1 = 6.toProperty() val property2 = 5.toProperty() property1 %= property2 Assert.assertEquals(1, property1.get()) } @Test fun testIntegerPropertyRangeToInt() { val property = 0.toProperty() val sequence = property..9 var counter = 0 for (i in sequence) { Assert.assertEquals(counter++, i.get()) } Assert.assertEquals(10, counter) } @Test fun testIntegerPropertyRangeToIntegerProperty() { val property1 = 0.toProperty() val property2 = 9.toProperty() val sequence = property1..property2 var counter = 0 for (i in sequence) { Assert.assertEquals(counter++, i.get()) } Assert.assertEquals(10, counter) } @Test fun testIntegerPropertyRangeToLong() { val property = 0.toProperty() val sequence = property..9L var counter = 0L for (i in sequence) { Assert.assertEquals(counter++, i.get()) } Assert.assertEquals(10L, counter) } @Test fun testIntegerPropertyRangeToLongProperty() { val property1 = 0.toProperty() val property2 = 9L.toProperty() val sequence = property1..property2 var counter = 0L for (i in sequence) { Assert.assertEquals(counter++, i.get()) } Assert.assertEquals(10L, counter) } @Test fun testIntegerPropertyCompareToNumber() { val property = 5.toProperty() Assert.assertTrue(property > 4) Assert.assertTrue(property >= 5) Assert.assertTrue(property >= 4) Assert.assertTrue(property <= 5) Assert.assertTrue(property <= 5) Assert.assertTrue(property <= 6) Assert.assertTrue(property < 6) Assert.assertFalse(property > 6) Assert.assertFalse(property >= 6) Assert.assertFalse(property <= 4) Assert.assertFalse(property < 4) } @Test fun testIntegerPropertyCompareToNumberProperty() { val property = 5.toProperty() Assert.assertTrue(property > 4.toProperty()) Assert.assertTrue(property >= 5.toProperty()) Assert.assertTrue(property >= 4.toProperty()) Assert.assertTrue(property <= 5.toProperty()) Assert.assertTrue(property <= 5.toProperty()) Assert.assertTrue(property <= 6.toProperty()) Assert.assertTrue(property < 6.toProperty()) Assert.assertFalse(property > 6.toProperty()) Assert.assertFalse(property >= 6.toProperty()) Assert.assertFalse(property <= 4.toProperty()) Assert.assertFalse(property < 4.toProperty()) } @Test fun testLongExpressionPlusNumber() { val property = 0L.toProperty() val binding = property + 5 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(5L, binding.get()) property.value -= 5L Assert.assertEquals(0L, binding.get()) } @Test fun testLongExpressionPlusFloat() { val property = 0L.toProperty() val binding = property + 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(5f, binding.get(), .001f) property.value -= 5L Assert.assertEquals(0f, binding.get(), .001f) } @Test fun testLongExpressionPlusDouble() { val property = 0L.toProperty() val binding = property + 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(5.0, binding.get(), .001) property.value -= 5L Assert.assertEquals(0.0, binding.get(), .001) } @Test fun testLongExpressionPlusNumberProperty() { val property1 = 0L.toProperty() val property2 = 5.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(5L, binding.get()) property1.value -= 10L Assert.assertEquals(-5L, binding.get()) property2.value = 0 Assert.assertEquals(-10L, binding.get()) } @Test fun testLongExpressionPlusFloatProperty() { val property1 = 0L.toProperty() val property2 = 5f.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(5f, binding.get(), .001f) property1.value -= 10L Assert.assertEquals(-5f, binding.get(), .001f) property2.value = 0f Assert.assertEquals(-10f, binding.get(), .001f) } @Test fun testLongExpressionPlusDoubleProperty() { val property1 = 0L.toProperty() val property2 = 5.0.toProperty() val binding = property1 + property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(5.0, binding.get(), .001) property1.value -= 10L Assert.assertEquals(-5.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testLongPropertyPlusAssignNumber() { val property = 0L.toProperty() property += 5 Assert.assertEquals(5L, property.get()) } @Test fun testLongPropertyPlusAssignNumberProperty() { val property1 = 0L.toProperty() val property2 = 5.toProperty() property1 += property2 Assert.assertEquals(5L, property1.get()) } @Test fun testLongExpressionMinusNumber() { val property = 0L.toProperty() val binding = property - 5 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(-5L, binding.get()) property.value -= 5L Assert.assertEquals(-10L, binding.get()) } @Test fun testLongExpressionMinusFloat() { val property = 0L.toProperty() val binding = property - 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(-5f, binding.get(), .001f) property.value -= 5L Assert.assertEquals(-10f, binding.get(), .001f) } @Test fun testLongExpressionMinusDouble() { val property = 0L.toProperty() val binding = property - 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(-5.0, binding.get(), .001) property.value -= 5L Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testLongExpressionMinusNumberProperty() { val property1 = 0L.toProperty() val property2 = 5.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(-5L, binding.get()) property1.value -= 10L Assert.assertEquals(-15L, binding.get()) property2.value = 0 Assert.assertEquals(-10L, binding.get()) } @Test fun testLongExpressionMinusFloatProperty() { val property1 = 0L.toProperty() val property2 = 5f.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(-5f, binding.get(), .001f) property1.value -= 10L Assert.assertEquals(-15f, binding.get(), .001f) property2.value = 0f Assert.assertEquals(-10f, binding.get(), .001f) } @Test fun testLongExpressionMinusDoubleProperty() { val property1 = 0L.toProperty() val property2 = 5.0.toProperty() val binding = property1 - property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(-5.0, binding.get(), .001) property1.value -= 10L Assert.assertEquals(-15.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(-10.0, binding.get(), .001) } @Test fun testLongPropertyMinusAssignNumber() { val property = 0L.toProperty() property -= 5 Assert.assertEquals(-5L, property.get()) } @Test fun testLongPropertyMinusAssignNumberProperty() { val property1 = 0L.toProperty() val property2 = 5.toProperty() property1 -= property2 Assert.assertEquals(-5L, property1.get()) } @Test fun testLongPropertyUnaryMinus() { val property = 1L.toProperty() val binding = -property Assert.assertEquals(-1L, binding.get()) property += 1 Assert.assertEquals(-2L, binding.get()) } @Test fun testLongExpressionTimesNumber() { val property = 2L.toProperty() val binding = property * 5 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(10L, binding.get()) property.value = 5L Assert.assertEquals(25L, binding.get()) } @Test fun testLongExpressionTimesFloat() { val property = 2L.toProperty() val binding = property * 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(10f, binding.get(), .001f) property.value = 5L Assert.assertEquals(25f, binding.get(), .001f) } @Test fun testLongExpressionTimesDouble() { val property = 2L.toProperty() val binding = property * 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(10.0, binding.get(), .001) property.value = 5L Assert.assertEquals(25.0, binding.get(), .001) } @Test fun testLongExpressionTimesNumberProperty() { val property1 = 2L.toProperty() val property2 = 5.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(10L, binding.get()) property1.value = 10L Assert.assertEquals(50L, binding.get()) property2.value = 0 Assert.assertEquals(0L, binding.get()) } @Test fun testLongExpressionTimesFloatProperty() { val property1 = 2L.toProperty() val property2 = 5f.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(10f, binding.get(), .001f) property1.value = 10L Assert.assertEquals(50f, binding.get(), .001f) property2.value = 0f Assert.assertEquals(0f, binding.get(), .001f) } @Test fun testLongExpressionTimesDoubleProperty() { val property1 = 2L.toProperty() val property2 = 5.0.toProperty() val binding = property1 * property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(10.0, binding.get(), .001) property1.value = 10L Assert.assertEquals(50.0, binding.get(), .001) property2.value = 0.0 Assert.assertEquals(0.0, binding.get(), .001) } @Test fun testLongPropertyTimesAssignNumber() { val property = 1L.toProperty() property *= 5 Assert.assertEquals(5L, property.get()) } @Test fun testLongPropertyTimesAssignNumberProperty() { val property1 = 1L.toProperty() val property2 = 5.toProperty() property1 *= property2 Assert.assertEquals(5L, property1.get()) } @Test fun testLongExpressionDivNumber() { val property = 10L.toProperty() val binding = property / 5 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(2L, binding.get()) property.value = 20L Assert.assertEquals(4L, binding.get()) } @Test fun testLongExpressionDivFloat() { val property = 10L.toProperty() val binding = property / 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(2f, binding.get(), .001f) property.value = 20L Assert.assertEquals(4f, binding.get(), .001f) } @Test fun testLongExpressionDivDouble() { val property = 10L.toProperty() val binding = property / 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(2.0, binding.get(), .001) property.value = 20L Assert.assertEquals(4.0, binding.get(), .001) } @Test fun testLongExpressionDivNumberProperty() { val property1 = 10L.toProperty() val property2 = 5.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(2L, binding.get()) property1.value = 20L Assert.assertEquals(4L, binding.get()) property2.value = 20 Assert.assertEquals(1L, binding.get()) } @Test fun testLongExpressionDivFloatProperty() { val property1 = 10L.toProperty() val property2 = 5f.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(2f, binding.get(), .001f) property1.value = 20L Assert.assertEquals(4f, binding.get(), .001f) property2.value = 20f Assert.assertEquals(1f, binding.get(), .001f) } @Test fun testLongExpressionDivDoubleProperty() { val property1 = 10L.toProperty() val property2 = 5.0.toProperty() val binding = property1 / property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(2.0, binding.get(), .001) property1.value = 20L Assert.assertEquals(4.0, binding.get(), .001) property2.value = 20.0 Assert.assertEquals(1.0, binding.get(), .001) } @Test fun testLongPropertyDivAssignNumber() { val property = 5L.toProperty() property /= 5 Assert.assertEquals(1L, property.get()) } @Test fun testLongPropertyDivAssignNumberProperty() { val property1 = 5L.toProperty() val property2 = 5.toProperty() property1 /= property2 Assert.assertEquals(1L, property1.get()) } @Test fun testLongExpressionRemNumber() { val property = 6L.toProperty() val binding = property % 5 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(1L, binding.get()) property.value = 12L Assert.assertEquals(2L, binding.get()) } @Test fun testLongExpressionRemFloat() { val property = 6L.toProperty() val binding = property % 5f Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(1f, binding.get(), .001f) property.value = 12L Assert.assertEquals(2f, binding.get(), .001f) } @Test fun testLongExpressionRemDouble() { val property = 6L.toProperty() val binding = property % 5.0 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(1.0, binding.get(), .001) property.value = 12L Assert.assertEquals(2.0, binding.get(), .001) } @Test fun testLongExpressionRemNumberProperty() { val property1 = 6L.toProperty() val property2 = 5.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is LongBinding) Assert.assertEquals(1L, binding.get()) property1.value = 12L Assert.assertEquals(2L, binding.get()) property2.value = 11 Assert.assertEquals(1L, binding.get()) } @Test fun testLongExpressionRemFloatProperty() { val property1 = 6L.toProperty() val property2 = 5f.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is FloatBinding) Assert.assertEquals(1f, binding.get(), .001f) property1.value = 12L Assert.assertEquals(2f, binding.get(), .001f) property2.value = 11f Assert.assertEquals(1f, binding.get(), .001f) } @Test fun testLongExpressionRemDoubleProperty() { val property1 = 6L.toProperty() val property2 = 5.0.toProperty() val binding = property1 % property2 Assert.assertTrue(binding is DoubleBinding) Assert.assertEquals(1.0, binding.get(), .001) property1.value = 12L Assert.assertEquals(2.0, binding.get(), .001) property2.value = 11.0 Assert.assertEquals(1.0, binding.get(), .001) } @Test fun testLongPropertyRemAssignNumber() { val property = 6L.toProperty() property %= 5 Assert.assertEquals(1L, property.get()) } @Test fun testLongPropertyRemAssignNumberProperty() { val property1 = 6L.toProperty() val property2 = 5.toProperty() property1 %= property2 Assert.assertEquals(1L, property1.get()) } @Test fun testLongPropertyRangeToInt() { val property = 0L.toProperty() val sequence = property..9 var counter = 0L for (i in sequence) { Assert.assertEquals(counter++, i.get()) } Assert.assertEquals(10L, counter) } @Test fun testLongPropertyRangeToIntegerProperty() { val property1 = 0L.toProperty() val property2 = 9.toProperty() val sequence = property1..property2 var counter = 0L for (i in sequence) { Assert.assertEquals(counter++, i.get()) } Assert.assertEquals(10L, counter) } @Test fun testLongPropertyRangeToLong() { val property = 0L.toProperty() val sequence = property..9L var counter = 0L for (i in sequence) { Assert.assertEquals(counter++, i.get()) } Assert.assertEquals(10L, counter) } @Test fun testLongPropertyRangeToLongProperty() { val property1 = 0L.toProperty() val property2 = 9L.toProperty() val sequence = property1..property2 var counter = 0L for (i in sequence) { Assert.assertEquals(counter++, i.get()) } Assert.assertEquals(10L, counter) } @Test fun testLongPropertyCompareToNumber() { val property = 5L.toProperty() Assert.assertTrue(property > 4) Assert.assertTrue(property >= 5) Assert.assertTrue(property >= 4) Assert.assertTrue(property <= 5) Assert.assertTrue(property <= 5) Assert.assertTrue(property <= 6) Assert.assertTrue(property < 6) Assert.assertFalse(property > 6) Assert.assertFalse(property >= 6) Assert.assertFalse(property <= 4) Assert.assertFalse(property < 4) } @Test fun testLongPropertyCompareToNumberProperty() { val property = 5L.toProperty() Assert.assertTrue(property > 4.toProperty()) Assert.assertTrue(property >= 5.toProperty()) Assert.assertTrue(property >= 4.toProperty()) Assert.assertTrue(property <= 5.toProperty()) Assert.assertTrue(property <= 5.toProperty()) Assert.assertTrue(property <= 6.toProperty()) Assert.assertTrue(property < 6.toProperty()) Assert.assertFalse(property > 6.toProperty()) Assert.assertFalse(property >= 6.toProperty()) Assert.assertFalse(property <= 4.toProperty()) Assert.assertFalse(property < 4.toProperty()) } @Test fun testNumberExpressionGtInt() { val property = (-1).toProperty() val binding = property gt 0 Assert.assertFalse(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGtLong() { val property = (-1).toProperty() val binding = property gt 0L Assert.assertFalse(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGtFloat() { val property = (-1).toProperty() val binding = property gt 0f Assert.assertFalse(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGtDouble() { val property = (-1).toProperty() val binding = property gt 0.0 Assert.assertFalse(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGtNumberProperty() { val property = (-1).toProperty() val binding = property gt 0.0.toProperty() Assert.assertFalse(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGeInt() { val property = (-1).toProperty() val binding = property ge 0 Assert.assertFalse(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGeLong() { val property = (-1).toProperty() val binding = property ge 0L Assert.assertFalse(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGeFloat() { val property = (-1).toProperty() val binding = property ge 0f Assert.assertFalse(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGeDouble() { val property = (-1).toProperty() val binding = property ge 0.0 Assert.assertFalse(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionGeNumberProperty() { val property = (-1).toProperty() val binding = property ge 0.0.toProperty() Assert.assertFalse(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertTrue(binding.get()) } @Test fun testNumberExpressionEqInt() { val property = (-1).toProperty() val binding = property eq 0 Assert.assertFalse(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionEqLong() { val property = (-1).toProperty() val binding = property eq 0L Assert.assertFalse(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionEqNumberProperty() { val property = (-1).toProperty() val binding = property eq 0.0.toProperty() Assert.assertFalse(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLeInt() { val property = (-1).toProperty() val binding = property le 0 Assert.assertTrue(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLeLong() { val property = (-1).toProperty() val binding = property le 0L Assert.assertTrue(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLeFloat() { val property = (-1).toProperty() val binding = property le 0f Assert.assertTrue(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLeDouble() { val property = (-1).toProperty() val binding = property le 0.0 Assert.assertTrue(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLeNumberProperty() { val property = (-1).toProperty() val binding = property le 0.0.toProperty() Assert.assertTrue(binding.get()) property.value = 0 Assert.assertTrue(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLtInt() { val property = (-1).toProperty() val binding = property lt 0 Assert.assertTrue(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLtLong() { val property = (-1).toProperty() val binding = property lt 0L Assert.assertTrue(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLtFloat() { val property = (-1).toProperty() val binding = property lt 0f Assert.assertTrue(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLtDouble() { val property = (-1).toProperty() val binding = property lt 0.0 Assert.assertTrue(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testNumberExpressionLtNumberProperty() { val property = (-1).toProperty() val binding = property lt 0.0.toProperty() Assert.assertTrue(binding.get()) property.value = 0 Assert.assertFalse(binding.get()) property.value = 1 Assert.assertFalse(binding.get()) } @Test fun testBooleanExpressionNot() { val property = true.toProperty() val binding = !property Assert.assertFalse(binding.get()) property.value = false Assert.assertTrue(binding.get()) } @Test fun testBooleanExpressionAndBoolean() { val property = true.toProperty() val binding = property and true Assert.assertTrue(binding.get()) property.value = false Assert.assertFalse(binding.get()) } @Test fun testBooleanExpressionAndBooleanProperty() { val property1 = true.toProperty() val property2 = true.toProperty() val binding = property1 and property2 Assert.assertTrue(binding.get()) property1.value = false Assert.assertFalse(binding.get()) property1.value = true Assert.assertTrue(binding.get()) property2.value = false Assert.assertFalse(binding.get()) } @Test fun testBooleanExpressionOrBoolean() { val property = false.toProperty() val binding = property or false Assert.assertFalse(binding.get()) property.value = true Assert.assertTrue(binding.get()) } @Test fun testBooleanExpressionOrBooleanProperty() { val property1 = false.toProperty() val property2 = false.toProperty() val binding = property1 or property2 Assert.assertFalse(binding.get()) property1.value = true Assert.assertTrue(binding.get()) property2.value = true Assert.assertTrue(binding.get()) } @Test fun testBooleanExpressionXorBoolean() { val property = false.toProperty() val binding = property xor true Assert.assertTrue(binding.get()) property.value = true Assert.assertFalse(binding.get()) } @Test fun testBooleanExpressionXorBooleanProperty() { val property1 = false.toProperty() val property2 = false.toProperty() val binding = property1 xor property2 Assert.assertFalse(binding.get()) property1.value = true Assert.assertTrue(binding.get()) property2.value = true Assert.assertFalse(binding.get()) } @Test fun testBooleanExpressionEqBoolean() { val property = false.toProperty() val binding = property eq false Assert.assertTrue(binding.get()) property.value = true Assert.assertFalse(binding.get()) } @Test fun testBooleanExpressionEqBooleanProperty() { val property1 = false.toProperty() val property2 = false.toProperty() val binding = property1 eq property2 Assert.assertTrue(binding.get()) property1.value = true Assert.assertFalse(binding.get()) property2.value = true Assert.assertTrue(binding.get()) } @Test fun testStringExpressionPlusAny() { val property = "Hello ".toProperty() val binding = property + "World!" Assert.assertTrue(binding.get() == "Hello World!") property.value = "Bye " Assert.assertTrue(binding.get() == "Bye World!") } @Test fun testStringPropertyPlusAssignAny() { val property = "Hello ".toProperty() Assert.assertTrue(property.get() == "Hello ") property += "World!" Assert.assertTrue(property.get() == "Hello World!") } @Test fun testStringExpressionGetInt() { val property = "Hello World!".toProperty() val binding = property[0] Assert.assertEquals('H', binding.value) property.value = "Bye World!" Assert.assertEquals('B', binding.value) } @Test fun testStringExpressionGetIntProperty() { val property = "Hello World!".toProperty() val indexProperty = 0.toProperty() val binding = property[indexProperty] Assert.assertEquals('H', binding.value) property.value = "Bye World!" Assert.assertEquals('B', binding.value) indexProperty.value = 1 Assert.assertEquals('y', binding.value) } @Test fun testStringExpressionGetIntToInt() { val property = "foo()".toProperty() val binding = property[0, 3] Assert.assertEquals("foo", binding.get()) property.value = "bar()" Assert.assertEquals("bar", binding.get()) } @Test fun testStringExpressionGetIntegerPropertyToInt() { val property = "foo()".toProperty() val startIndex = 0.toProperty() val binding = property[startIndex, 3] Assert.assertEquals("foo", binding.get()) property.value = "bar()" Assert.assertEquals("bar", binding.get()) startIndex.value = 1 Assert.assertEquals("ar", binding.get()) } @Test fun testStringExpressionGetIntToIntegerProperty() { val property = "foo()".toProperty() val endIndex = 3.toProperty() val binding = property[0, endIndex] Assert.assertEquals("foo", binding.get()) property.value = "bar()" Assert.assertEquals("bar", binding.get()) endIndex.value = 5 Assert.assertEquals("bar()", binding.get()) } @Test fun testStringExpressionGetIntegerPropertyToIntegerProperty() { val property = "foo()".toProperty() val startIndex = 0.toProperty() val endIndex = 3.toProperty() val binding = property[startIndex, endIndex] Assert.assertEquals("foo", binding.get()) property.value = "bar()" Assert.assertEquals("bar", binding.get()) startIndex.value = 3 endIndex.value = 5 Assert.assertEquals("()", binding.get()) } @Test fun testStringExpressionUnaryMinus() { val property = "god a ward".toProperty() val binding = -property Assert.assertEquals("draw a dog", binding.get()) property.value = "dog a ward" Assert.assertEquals("draw a god", binding.get()) } @Test fun testStringExpressionCompareToString() { val property = "Bravo".toProperty() Assert.assertTrue(property > "Alpha") Assert.assertTrue(property >= "Alpha") Assert.assertTrue(property >= "Bravo") Assert.assertTrue(property <= "Bravo") Assert.assertTrue(property <= "Charlie") Assert.assertTrue(property < "Charlie") Assert.assertFalse(property < "Alpha") Assert.assertFalse(property <= "Alpha") Assert.assertFalse(property >= "Charlie") Assert.assertFalse(property > "Charlie") } @Test fun testStringExpressionCompareToStringProperty() { val property = "Bravo".toProperty() Assert.assertTrue(property > "Alpha".toProperty()) Assert.assertTrue(property >= "Alpha".toProperty()) Assert.assertTrue(property >= "Bravo".toProperty()) Assert.assertTrue(property <= "Bravo".toProperty()) Assert.assertTrue(property <= "Charlie".toProperty()) Assert.assertTrue(property < "Charlie".toProperty()) Assert.assertFalse(property < "Alpha".toProperty()) Assert.assertFalse(property <= "Alpha".toProperty()) Assert.assertFalse(property >= "Charlie".toProperty()) Assert.assertFalse(property > "Charlie".toProperty()) } @Test fun testStringExpressionGtString() { val property = "Bravo".toProperty() val binding = property gt "Alpha" Assert.assertTrue(binding.get()) property.value = "Alpha" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionGtStringProperty() { val property1 = "Charlie".toProperty() val property2 = "Bravo".toProperty() val binding = property1 gt property2 Assert.assertTrue(binding.get()) property1.value = "Bravo" Assert.assertFalse(binding.get()) property2.value = "Alpha" Assert.assertTrue(binding.get()) } @Test fun testStringExpressionGeString() { val property = "Charlie".toProperty() val binding = property ge "Bravo" Assert.assertTrue(binding.get()) property.value = "Bravo" Assert.assertTrue(binding.get()) property.value = "Alpha" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionGeStringProperty() { val property1 = "Charlie".toProperty() val property2 = "Bravo".toProperty() val binding = property1 ge property2 Assert.assertTrue(binding.get()) property1.value = "Bravo" Assert.assertTrue(binding.get()) property2.value = "Alpha" Assert.assertTrue(binding.get()) property2.value = "Charlie" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionEqString() { val property = "Bravo".toProperty() val binding = property eq "Bravo" Assert.assertTrue(binding.get()) property.value = "Alpha" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionEqStringProperty() { val property1 = "Bravo".toProperty() val property2 = "Bravo".toProperty() val binding = property1 eq property2 Assert.assertTrue(binding.get()) property1.value = "Alpha" Assert.assertFalse(binding.get()) property2.value = "Alpha" Assert.assertTrue(binding.get()) } @Test fun testStringExpressionLeString() { val property = "Alpha".toProperty() val binding = property le "Bravo" Assert.assertTrue(binding.get()) property.value = "Bravo" Assert.assertTrue(binding.get()) property.value = "Charlie" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionLeStringProperty() { val property1 = "Alpha".toProperty() val property2 = "Bravo".toProperty() val binding = property1 le property2 Assert.assertTrue(binding.get()) property1.value = "Bravo" Assert.assertTrue(binding.get()) property2.value = "Charlie" Assert.assertTrue(binding.get()) property2.value = "Alpha" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionLtString() { val property = "Alpha".toProperty() val binding = property lt "Bravo" Assert.assertTrue(binding.get()) property.value = "Bravo" Assert.assertFalse(binding.get()) property.value = "Charlie" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionLtStringProperty() { val property1 = "Alpha".toProperty() val property2 = "Bravo".toProperty() val binding = property1 lt property2 Assert.assertTrue(binding.get()) property1.value = "Bravo" Assert.assertFalse(binding.get()) property2.value = "Charlie" Assert.assertTrue(binding.get()) property2.value = "Alpha" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionEqIgnoreCaseString() { val property = "Hello World!".toProperty() val binding = property eqIgnoreCase "hello world!" Assert.assertTrue(binding.get()) property.value = "Bye World!" Assert.assertFalse(binding.get()) } @Test fun testStringExpressionEqIgnoreCaseStringProperty() { val property1 = "Hello World!".toProperty() val property2 = "hello world!".toProperty() val binding = property1 eqIgnoreCase property2 Assert.assertTrue(binding.get()) property1.value = "bye world!" Assert.assertFalse(binding.get()) property2.value = "Bye World!" Assert.assertTrue(binding.get()) } @Test fun propertyFromMapKey() { val map = mutableMapOf("hello" to "world", "number" to 42) val helloProperty = map.toProperty("hello") { SimpleStringProperty(it as String?) } val numberProperty = map.toProperty("number") { SimpleIntegerProperty(it as Int) } helloProperty.value = "there" numberProperty.value = 43 Assert.assertEquals("there", map["hello"]) Assert.assertEquals(43, map["number"]) } // class ListHolder { // val listProperty: ListProperty<String> = SimpleListProperty<String>(FXCollections.observableArrayList()) // var list: MutableList<String> by listProperty // } // // @Test fun listPropertyDelegateModifyList() { // val listHolder = ListHolder() // var notified = false // listHolder.listProperty.addListener { _, _, _-> notified = true } // // listHolder.list.add("Test") // Assert.assertTrue(notified) // // notified = false // listHolder.list.remove("Test") // Assert.assertTrue(notified) // // notified = false // listHolder.list.addAll(arrayOf("1", "2")) // Assert.assertTrue(notified) // // notified = false // listHolder.list.clear() // Assert.assertTrue(notified) // } // // @Test fun listPropertyDelegateChangeList() { // val listHolder = ListHolder() // var notified = false // listHolder.listProperty.addListener { _, _, _-> notified = true } // // listHolder.list = mutableListOf("Test") // Assert.assertTrue(notified) // } // // class SetHolder { // val setProperty: SetProperty<String> = SimpleSetProperty<String>(FXCollections.observableSet()) // var set: MutableSet<String> by setProperty // } // // @Test fun setPropertyDelegateModifySet() { // val setHolder = SetHolder() // var notified = false // setHolder.setProperty.addListener { _, _, _-> notified = true } // // setHolder.set.add("Test") // Assert.assertTrue(notified) // // notified = false // setHolder.set.remove("Test") // Assert.assertTrue(notified) // // notified = false // setHolder.set.addAll(arrayOf("1", "2")) // Assert.assertTrue(notified) // // notified = false // setHolder.set.clear() // Assert.assertTrue(notified) // } // // @Test fun setPropertyDelegateChangeSet() { // val setHolder = SetHolder() // var notified = false // setHolder.setProperty.addListener { _, _, _-> notified = true } // // setHolder.set = mutableSetOf("Test") // Assert.assertTrue(notified) // } // // class MapHolder { // val mapProperty: MapProperty<Int, String> = SimpleMapProperty<Int, String>(FXCollections.observableHashMap()) // var map: MutableMap<Int, String> by mapProperty // } // // @Test fun mapPropertyDelegateModifyMap() { // val mapHolder = MapHolder() // var notified = false // mapHolder.mapProperty.addListener { _, _, _-> notified = true } // // mapHolder.map.put(0, "Test") // Assert.assertTrue(notified) // // notified = false // mapHolder.map.remove(0) // Assert.assertTrue(notified) // // notified = false // mapHolder.map.putAll(mapOf(1 to "1", 2 to "2")) // Assert.assertTrue(notified) // // notified = false // mapHolder.map.clear() // Assert.assertTrue(notified) // } // // @Test fun mapPropertyDelegateChangeMap() { // val mapHolder = MapHolder() // var notified = false // mapHolder.mapProperty.addListener { _, _, _-> notified = true } // // mapHolder.map = mutableMapOf(0 to "Test") // Assert.assertTrue(notified) // } }
apache-2.0
cc9e556a8f6f9789e0112ce4a751b652
27.790119
119
0.616796
4.338793
false
true
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/insight/generation/ui/EventGenerationDialog.kt
1
1259
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.insight.generation.ui import com.demonwav.mcdev.asset.MCDevBundle import com.demonwav.mcdev.insight.generation.GenerationData import com.intellij.openapi.editor.Editor import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo class EventGenerationDialog( editor: Editor, private val panel: EventGenerationPanel, className: String, defaultListenerName: String ) : DialogWrapper(editor.component, false) { private val wizard: EventListenerWizard = EventListenerWizard(panel.panel, className, defaultListenerName) var data: GenerationData? = null private set init { title = MCDevBundle.message("generate.event_listener.settings") isOKActionEnabled = true setValidationDelay(0) init() } override fun doOKAction() { data = panel.gatherData() super.doOKAction() } override fun createCenterPanel() = wizard.panel override fun doValidate(): ValidationInfo? { return panel.doValidate() } val chosenName: String get() = wizard.chosenClassName }
mit
8cc7ad4be8e759d486905d5c4c78cf87
23.211538
110
0.709293
4.371528
false
false
false
false
ohmae/mmupnp
mmupnp/src/test/java/net/mm2d/upnp/internal/manager/SubscribeServiceTest.kt
1
8619
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.manager import com.google.common.truth.Truth.assertThat import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import kotlinx.coroutines.runBlocking import net.mm2d.upnp.Service import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.util.concurrent.TimeUnit @Suppress("TestFunctionName", "NonAsciiCharacters") @RunWith(JUnit4::class) class SubscribeServiceTest { @Test fun getService_Serviceが取得できる() { val service: Service = mockk(relaxed = true) val subscribeService = SubscribeService(service, 1000, false) assertThat(subscribeService.service).isEqualTo(service) } @Test fun getNextScanTime_keepでないとき開始時間とタイムアウトの合計に等しい() { val service: Service = mockk(relaxed = true) val timeout = 1000L val start = System.currentTimeMillis() val subscribeService = SubscribeService(service, timeout, false) assertThat(subscribeService.getNextScanTime() - (start + timeout)).isLessThan(100L) } @Test fun getNextScanTime_keepである時serviceのgetSubscriptionStartとの差はgetSubscriptionTimeoutより小さい() { val service: Service = mockk(relaxed = true) val start = System.currentTimeMillis() val timeout = 1000L val subscribeService = SubscribeService(service, timeout, true) val time = subscribeService.getNextScanTime() assertThat(time).isGreaterThan(start) assertThat(time).isLessThan(start + timeout) } @Test fun getNextScanTime_keepである時failしてもserviceのgetSubscriptionStartとの差はgetSubscriptionTimeoutより小さい() { val service: Service = mockk(relaxed = true) val start = System.currentTimeMillis() val timeout = 1000L coEvery { service.renewSubscribe() } returns false val subscribeService = SubscribeService(service, timeout, true) runBlocking { subscribeService.renewSubscribe(subscribeService.getNextScanTime()) } val time = subscribeService.getNextScanTime() assertThat(time).isGreaterThan(start) assertThat(time).isLessThan(start + timeout) } @Test fun getNextScanTime_keepである時failCountが0のときより1のほうが大きな値になる() { val timeout = 1000L val service: Service = mockk(relaxed = true) coEvery { service.renewSubscribe() } returns false val subscribeService = SubscribeService(service, timeout, true) val time1 = subscribeService.getNextScanTime() runBlocking { subscribeService.renewSubscribe(time1) } val time2 = subscribeService.getNextScanTime() assertThat(time1).isLessThan(time2) } @Test fun isFailed_2回連続失敗でtrue() { val service: Service = mockk(relaxed = true) coEvery { service.renewSubscribe() } returns false val subscribeService = SubscribeService(service, 0L, true) val start = System.currentTimeMillis() assertThat(subscribeService.isFailed()).isFalse() runBlocking { subscribeService.renewSubscribe(start) } assertThat(subscribeService.isFailed()).isFalse() runBlocking { subscribeService.renewSubscribe(start) } assertThat(subscribeService.isFailed()).isTrue() } @Test fun isFailed_連続しない2回失敗ではfalse() { val service: Service = mockk(relaxed = true) val subscribeService = SubscribeService(service, 0L, true) assertThat(subscribeService.isFailed()).isFalse() coEvery { service.renewSubscribe() } returns false runBlocking { subscribeService.renewSubscribe(0) } assertThat(subscribeService.isFailed()).isFalse() coEvery { service.renewSubscribe() } returns true runBlocking { subscribeService.renewSubscribe(0) } assertThat(subscribeService.isFailed()).isFalse() coEvery { service.renewSubscribe() } returns false runBlocking { subscribeService.renewSubscribe(0) } assertThat(subscribeService.isFailed()).isFalse() } @Test fun isExpired_期限が切れるとtrue() { val service: Service = mockk(relaxed = true) val start = System.currentTimeMillis() val timeout = 1000L val expiryTime = start + timeout val subscribeService = SubscribeService(service, timeout, false) assertThat(subscribeService.isExpired(expiryTime)).isFalse() assertThat(subscribeService.isExpired(expiryTime + 100L)).isTrue() } @Test fun renewSubscribe_keepがfalseならrenewSubscribeを呼ばない() { val timeout = 1000L val service: Service = mockk(relaxed = true) coEvery { service.renewSubscribe() } returns true val subscribeService = SubscribeService(service, timeout, false) val time = subscribeService.getNextScanTime() runBlocking { assertThat(subscribeService.renewSubscribe(time)).isTrue() } coVerify(inverse = true) { service.renewSubscribe() } } @Test fun renewSubscribe_keepがtrueでも時間の前ではrenewSubscribeを呼ばない() { val timeout = 1000L val service: Service = mockk(relaxed = true) coEvery { service.renewSubscribe() } returns true val subscribeService = SubscribeService(service, timeout, true) val time = subscribeService.getNextScanTime() runBlocking { assertThat(subscribeService.renewSubscribe(time - 1)).isTrue() } coVerify(inverse = true) { service.renewSubscribe() } } @Test fun renewSubscribe_keepがtrueで時間を過ぎていたらrenewSubscribeを呼ぶ() { val timeout = 1000L val service: Service = mockk(relaxed = true) coEvery { service.renewSubscribe() } returns true val subscribeService = SubscribeService(service, timeout, true) val time = subscribeService.getNextScanTime() runBlocking { assertThat(subscribeService.renewSubscribe(time)).isTrue() } coVerify(exactly = 1) { service.renewSubscribe() } } @Test fun calculateRenewTime() { val service: Service = mockk(relaxed = true) val start = System.currentTimeMillis() val subscribeService = SubscribeService(service, TimeUnit.SECONDS.toMillis(300), false) assertThat(subscribeService.calculateRenewTime() - start - TimeUnit.SECONDS.toMillis(140)).isLessThan(100L) subscribeService.renew(TimeUnit.SECONDS.toMillis(16)) assertThat(subscribeService.calculateRenewTime() - start - TimeUnit.SECONDS.toMillis(4)).isLessThan(100L) } @Test fun renewSubscribe() { val service: Service = mockk(relaxed = true) val subscribeService = SubscribeService(service, TimeUnit.SECONDS.toMillis(300), true) val start = System.currentTimeMillis() runBlocking { subscribeService.renewSubscribe(TimeUnit.SECONDS.toMillis(300) + start) subscribeService.renewSubscribe(TimeUnit.SECONDS.toMillis(300) + start) } assertThat(subscribeService.isFailed()).isTrue() } @Test fun hashCode_Serviceと同一() { val service: Service = mockk(relaxed = true) val subscribeService = SubscribeService(service, TimeUnit.SECONDS.toMillis(300), false) assertThat(subscribeService.hashCode()).isEqualTo(service.hashCode()) } @Test fun equals_同一インスタンスであれば真() { val service: Service = mockk(relaxed = true) val subscribeService = SubscribeService(service, TimeUnit.SECONDS.toMillis(300), false) assertThat(subscribeService == subscribeService).isTrue() } @Test fun equals_Serviceが同一であれば真() { val service: Service = mockk(relaxed = true) val subscribeService1 = SubscribeService(service, TimeUnit.SECONDS.toMillis(300), false) val subscribeService2 = SubscribeService(service, TimeUnit.SECONDS.toMillis(300), false) assertThat(subscribeService1 == subscribeService1).isTrue() assertThat(subscribeService1 == subscribeService2).isTrue() } }
mit
35cd09915bbcc7ac21829a32e52215be
33.802521
115
0.677894
4.467638
false
true
false
false
soywiz/korge
@old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Timeline.kt
1
7695
package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Entity.* import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Timeline.* import kotlin.math.* /** * Represents a time line in a Spriter SCML file. * A time line holds an [.id], a [.name] and at least one [Key]. * @author Trixt0r */ class Timeline internal constructor( val id: Int, val name: String, val objectInfo: ObjectInfo, keys: Int ) { val keys: Array<Key> = Array<Key>(keys) { Key.DUMMY } private var keyPointer = 0 internal fun addKey(key: Key) { this.keys[keyPointer++] = key } /** * Returns a [Key] at the given index * @param index the index of the key. * * * @return the key with the given index. * * * @throws IndexOutOfBoundsException if the index is out of range */ fun getKey(index: Int): Key { return this.keys[index] } override fun toString(): String { var toReturn = "" + this::class + "|[id:" + id + ", name: " + name + ", object_info: " + objectInfo for (key in keys) toReturn += "\n" + key toReturn += "]" return toReturn } /** * Represents a time line key in a Spriter SCML file. * A key holds an [.id], a [.time], a [.spin], an [.object] and a [.curve]. * @author Trixt0r */ class Key(val id: Int, var time: Int, val spin: Int, val curve: Curve) { var active: Boolean = false private var `object`: Object? = null constructor(id: Int, time: Int = 0, spin: Int = 1) : this(id, time, 1, Curve()) {} fun setObject(`object`: Object?) { if (`object` == null) throw IllegalArgumentException("object can not be null!") this.`object` = `object` } fun `object`(): Object { return this.`object`!! } override fun toString(): String { return "" + this::class + "|[id: " + id + ", time: " + time + ", spin: " + spin + "\ncurve: " + curve + "\nobject:" + `object` + "]" } /** * Represents a bone in a Spriter SCML file. * A bone holds a [.position], [.scale], an [.angle] and a [.pivot]. * Bones are the only objects which can be used as a parent for other tweenable objects. * @author Trixt0r */ open class Bone constructor( position: Point = Point(), scale: Point = Point(1f, 1f), pivot: Point = Point(0f, 1f), var _angle: Float = 0f ) { val position: Point = Point(position) val scale: Point = Point(scale) val pivot: Point = Point(pivot) constructor(bone: Bone) : this(bone.position, bone.scale, bone.pivot, bone._angle) /** * Returns whether this instance is a Spriter object or a bone. * @return true if this instance is a Spriter bone */ val isBone: Boolean get() = this !is Object /** * Sets the values of this bone to the values of the given bone * @param bone the bone */ fun set(bone: Bone) { this[bone.position, bone._angle, bone.scale] = bone.pivot } /** * Sets the given values for this bone. * @param x the new position in x direction * * * @param y the new position in y direction * * * @param angle the new angle * * * @param scaleX the new scale in x direction * * * @param scaleY the new scale in y direction * * * @param pivotX the new pivot in x direction * * * @param pivotY the new pivot in y direction */ operator fun set( x: Float, y: Float, angle: Float, scaleX: Float, scaleY: Float, pivotX: Float, pivotY: Float ) { this._angle = angle this.position.set(x, y) this.scale.set(scaleX, scaleY) this.pivot.set(pivotX, pivotY) } /** * Sets the given values for this bone. * @param position the new position * * * @param angle the new angle * * * @param scale the new scale * * * @param pivot the new pivot */ operator fun set(position: Point, angle: Float, scale: Point, pivot: Point) { this[position.x, position.y, angle, scale.x, scale.y, pivot.x] = pivot.y } /** * Maps this bone from it's parent's coordinate system to a global one. * @param parent the parent bone of this bone */ fun unmap(parent: Bone) { this._angle *= sign(parent.scale.x) * sign(parent.scale.y) this._angle += parent._angle this.scale.scale(parent.scale) this.position.scale(parent.scale) this.position.rotate(parent._angle) this.position.translate(parent.position) } /** * Maps this from it's global coordinate system to the parent's one. * @param parent the parent bone of this bone */ fun map(parent: Bone) { this.position.translate(-parent.position.x, -parent.position.y) this.position.rotate(-parent._angle) this.position.scale(1f / parent.scale.x, 1f / parent.scale.y) this.scale.scale(1f / parent.scale.x, 1f / parent.scale.y) this._angle -= parent._angle this._angle *= sign(parent.scale.x) * sign(parent.scale.y) } override fun toString(): String = "${this::class}|position: $position, scale: $scale, angle: $_angle" } /** * Represents an object in a Spriter SCML file. * A file has the same properties as a bone with an alpha and file extension. * @author Trixt0r */ class Object constructor( position: Point = Point(), scale: Point = Point(1f, 1f), pivot: Point = Point(0f, 1f), angle: Float = 0f, var alpha: Float = 1f, val ref: FileReference = FileReference( -1, -1 ) ) : Bone(position, scale, pivot, angle) { constructor(`object`: Object) : this( `object`.position.copy(), `object`.scale.copy(), `object`.pivot.copy(), `object`._angle, `object`.alpha, `object`.ref ) { } /** * Sets the values of this object to the values of the given object. * @param object the object */ fun set(`object`: Object) { this[`object`.position, `object`._angle, `object`.scale, `object`.pivot, `object`.alpha] = `object`.ref } /** * Sets the given values for this object. * @param x the new position in x direction * * * @param y the new position in y direction * * * @param angle the new angle * * * @param scaleX the new scale in x direction * * * @param scaleY the new scale in y direction * * * @param pivotX the new pivot in x direction * * * @param pivotY the new pivot in y direction * * * @param alpha the new alpha value * * * @param folder the new folder index * * * @param file the new file index */ operator fun set( x: Float, y: Float, angle: Float, scaleX: Float, scaleY: Float, pivotX: Float, pivotY: Float, alpha: Float, folder: Int, file: Int ) { super.set(x, y, angle, scaleX, scaleY, pivotX, pivotY) this.alpha = alpha this.ref.folder = folder this.ref.file = file } /** * Sets the given values for this object. * @param position the new position * * * @param angle the new angle * * * @param scale the new scale * * * @param pivot the new pivot * * * @param alpha the new alpha value * * * @param fileRef the new file reference */ operator fun set( position: Point, angle: Float, scale: Point, pivot: Point, alpha: Float, fileRef: FileReference ) { this[position.x, position.y, angle, scale.x, scale.y, pivot.x, pivot.y, alpha, fileRef.folder] = fileRef.file } override fun toString(): String { return super.toString() + ", pivot: " + pivot + ", alpha: " + alpha + ", reference: " + ref } } companion object { var DUMMY = Key(0) } } companion object { var DUMMY = Timeline(0, "", ObjectInfo.Companion.DUMMY, 0) } }
apache-2.0
787f6023bdde5d08092cd81906f9a30e
25.811847
135
0.613125
3.318241
false
false
false
false
Ztiany/Repository
Kotlin/Kotlin-Coroutines/src/main/kotlin/core/select/05_SwitchOverAChannelOfDeferredValues.kt
2
2444
package core.select import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce import kotlinx.coroutines.selects.select /* 我们现在来编写一个通道生产者函数,它消费一个产生延迟字符串的通道,并等待每个接收的延迟值,但它只在下一个延迟值到达或者通道关闭之前处于运行状态。 此示例将 onReceiveOrNull 和 onAwait 子句放在同一个 select 中: */ @ExperimentalCoroutinesApi private fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> { var current = input.receive() // start with first received deferred value 从第一个接收到的延迟值开始 while (isActive) { // loop while not cancelled/closed val next = select<Deferred<String>?> { // return next deferred value from this select or null input.onReceiveOrNull { update -> println("onReceiveOrNull $update") update // replaces next value to wait } current.onAwait { value -> send(value) // send value that current deferred has produced 发送当前延迟生成的值 input.receiveOrNull() // and use the next deferred from the input channel 然后使用从输入通道得到的下一个延迟值 } } if (next == null) { println("Channel was closed") break // out of loop } else { current = next } } } private fun CoroutineScope.asyncString(str: String, time: Long) = async { delay(time) str } fun main() = runBlocking<Unit> { //sampleStart val chan = Channel<Deferred<String>>() // the channel for test launch { // launch printing coroutine for (s in switchMapDeferreds(chan)) println(s) // print each received string } chan.send(asyncString("BEGIN", 100)) delay(200) // enough time for "BEGIN" to be produced chan.send(asyncString("Slow", 500)) delay(100) // not enough time to produce slow chan.send(asyncString("Replace", 100)) delay(500) // give it time before the last one chan.send(asyncString("END", 500)) delay(1000) // give it time to process chan.close() // close the channel ... delay(500) // and wait some time to let it finish //sampleEnd }
apache-2.0
1cd2c13d3fe322ba1f3e9ab7c3fab220
34.918033
108
0.658447
4.048059
false
false
false
false
isuPatches/WiseFy
wisefy/src/androidTest/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacyTests.kt
1
13210
package com.isupatches.wisefy.connection import com.isupatches.wisefy.TEST_SSID import com.isupatches.wisefy.TEST_SSID2 import com.isupatches.wisefy.TEST_TIMEOUT import com.isupatches.wisefy.constants.MOBILE import com.isupatches.wisefy.constants.WIFI import com.isupatches.wisefy.internal.base.BaseInstrumentationTest import org.junit.After import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test /** * Used to test the WiseFyConnectionLegacy class and functionality determining various connection states. * * @see WiseFyConnectionLegacy * * @author Patches * @since 4.0 */ internal class WiseFyConnectionLegacyTests : BaseInstrumentationTest() { private val wisefyConnection = WiseFyConnectionLegacy.create( mockConnectivityManager, mockWifiManager ) @Before fun setUp() { wisefyConnection.init() } @After override fun tearDown() { super.tearDown() wisefyConnection.destroy() } /* * isCurrentNetworkConnectedToSSID tests */ @Test fun isCurrentNetworkConnectedToSSID_failure_nullSSIDParam() { assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(null)) } @Test fun isCurrentNetworkConnectedToSSID_failure_emptySSIDParam() { assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID("")) } @Test fun isCurrentNetworkConnectedToSSID_failure_nullConnectionInfo() { mockNetworkUtil.currentNetwork_null() assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) } @Test fun isCurrentNetworkConnectedToSSID_failure_nullSSID() { mockNetworkUtil.currentNetwork(null) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = null) assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) } @Test fun isCurrentNetworkConnectedToSSID_failure_emptySSID() { mockNetworkUtil.currentNetwork("") mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = null) assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) } @Test fun isCurrentNetworkConnectedToSSID_failure_differentSSID() { mockNetworkUtil.currentNetwork(TEST_SSID2) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = null) assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) } @Test fun isCurrentNetworkConnectedToSSID_failure_notAvailable() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = true, type = null) assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) } @Test fun isCurrentNetworkConnectedToSSID_failure_notAvailableOrConnected() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = false, type = null) assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) } @Test fun isCurrentNetworkConnectedToSSID_failure_notConnected() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = false, type = null) assertFalse(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) } @Test fun isCurrentNetworkConnectedToSSID_success() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = null) assertTrue(wisefyConnection.isCurrentNetworkConnectedToSSID(TEST_SSID)) } /* * isNetworkConnected tests */ @Test fun isNetworkConnected_failure_nullNetworkInfoParam() { assertFalse(wisefyConnection.isNetworkConnected()) } @Test fun isNetworkConnected_failure_notAvailable() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = true, type = null) assertFalse(wisefyConnection.isNetworkConnected()) } @Test fun isNetworkConnected_failure_notAvailableOrConnected() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = false, type = null) assertFalse(wisefyConnection.isNetworkConnected()) } @Test fun isNetworkConnected_failure_notConnected() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = false, type = null) assertFalse(wisefyConnection.isNetworkConnected()) } @Test fun isNetworkConnected_success() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = null) assertTrue(wisefyConnection.isNetworkConnected()) } /* * isDeviceConnectedToMobileNetwork tests */ @Test fun isDeviceConnectedToMobileNetwork_failure_nullNetworkInfo() { assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) } @Test fun isDeviceConnectedToMobileNetwork_failure_notAvailableOrConnected() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = false, type = MOBILE) assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) } @Test fun isDeviceConnectedToMobileNetwork_failure_notAvailable() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = true, type = MOBILE) assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) } @Test fun isDeviceConnectedToMobileNetwork_failure_notConnected() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = false, type = MOBILE) assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) } @Test fun isDeviceConnectedToMobileNetwork_failure_nullTypeName() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = null) assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) } @Test fun isDeviceConnectedToMobileNetwork_failure_differentTypeName() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = WIFI) assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) } @Test fun isDeviceConnectedToMobileNetwork_failure_differentTypeName_differentCase() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = "wifi") assertFalse(wisefyConnection.isDeviceConnectedToMobileNetwork()) } @Test fun isDeviceConnectedToMobileNetwork_success() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = MOBILE) assertTrue(wisefyConnection.isDeviceConnectedToMobileNetwork()) } @Test fun isDeviceConnectedToMobileNetwork_success_differentCase() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = "mobile") assertTrue(wisefyConnection.isDeviceConnectedToMobileNetwork()) } /* * isDeviceConnectedToWifiNetwork tests */ @Test fun isDeviceConnectedToWifiNetwork_failure_nullNetworkInfo() { assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) } @Test fun isDeviceConnectedToWifiNetwork_failure_notAvailableOrConnected() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = false, type = WIFI) assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) } @Test fun isDeviceConnectedToWifiNetwork_failure_notAvailable() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = true, type = WIFI) assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) } @Test fun isDeviceConnectedToWifiNetwork_failure_notConnected() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = false, type = WIFI) assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) } @Test fun isDeviceConnectedToWifiNetwork_failure_nullTypeName() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = null) assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) } @Test fun isDeviceConnectedToWifiNetwork_failure_differentTypeName() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = MOBILE) assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) } @Test fun isDeviceConnectedToWifiNetwork_failure_differentTypeName_differentCase() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = "mobile") assertFalse(wisefyConnection.isDeviceConnectedToWifiNetwork()) } @Test fun isDeviceConnectedToWifiNetwork_success() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = WIFI) assertTrue(wisefyConnection.isDeviceConnectedToWifiNetwork()) } @Test fun isDeviceConnectedToWifiNetwork_success_differentCase() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = "wifi") assertTrue(wisefyConnection.isDeviceConnectedToWifiNetwork()) } /* * isDeviceRoaming tests */ @Test fun isDeviceRoaming_failure_nullNetworkInfo() { assertFalse(wisefyConnection.isDeviceRoaming()) } @Test fun isDeviceRoaming_failure() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.isDeviceRoaming(false) assertFalse(wisefyConnection.isDeviceRoaming()) } @Test fun isDeviceRoaming_success() { mockNetworkUtil.currentNetwork(TEST_SSID) mockNetworkUtil.isDeviceRoaming(true) assertTrue(wisefyConnection.isDeviceRoaming()) } /* * waitToConnectToSSID tests */ @Test fun waitToConnectToSSID_failure_nullSSIDParam() { assertFalse(wisefyConnection.waitToConnectToSSID(null, TEST_TIMEOUT)) } @Test fun waitToConnectToSSID_failure_nullConnectionInfo() { mockNetworkUtil.currentNetwork_null() assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) } @Test fun waitToConnectToSSID_failure_nullSSID() { mockNetworkUtil.currentNetwork(null) assertFalse(wisefyConnection.waitToConnectToSSID(null, TEST_TIMEOUT)) } @Test fun waitToConnectToSSID_failure_differentSSID() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = WIFI) mockNetworkUtil.currentNetwork(TEST_SSID2) assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) } @Test fun waitToConnectToSSID_failure_notAvailable() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = true, type = WIFI) mockNetworkUtil.currentNetwork(TEST_SSID) assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) } @Test fun waitToConnectToSSID_failure_notAvailableOrConnected() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = false, isConnected = false, type = WIFI) mockNetworkUtil.currentNetwork(TEST_SSID) assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) } @Test fun waitToConnectToSSID_failure_notConnected() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = false, type = WIFI) mockNetworkUtil.currentNetwork(TEST_SSID) assertFalse(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) } @Test fun waitToConnectToSSID_success() { mockNetworkUtil.currentNetworkConnectionStatus(isAvailable = true, isConnected = true, type = WIFI) mockNetworkUtil.currentNetwork(TEST_SSID) assertTrue(wisefyConnection.waitToConnectToSSID(TEST_SSID, TEST_TIMEOUT)) } }
apache-2.0
1cd2bf517cb714daa3b924eed55ec83d
36.635328
111
0.741938
5.188531
false
true
false
false
AromaTech/banana-data-operations
src/main/java/tech/aroma/data/sql/SQLUserRepository.kt
3
5426
/* * Copyright 2017 RedRoma, 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 tech.aroma.data.sql import org.slf4j.LoggerFactory import org.springframework.dao.EmptyResultDataAccessException import org.springframework.jdbc.core.JdbcOperations import tech.aroma.data.UserRepository import tech.aroma.data.assertions.RequestAssertions.validUser import tech.aroma.data.sql.SQLStatements.Deletes import tech.aroma.data.sql.SQLStatements.Inserts import tech.aroma.data.sql.SQLStatements.Queries import tech.aroma.thrift.User import tech.aroma.thrift.exceptions.InvalidArgumentException import tech.aroma.thrift.exceptions.UserDoesNotExistException import tech.sirwellington.alchemy.arguments.Arguments.checkThat import tech.sirwellington.alchemy.arguments.assertions.* import javax.inject.Inject /** * * @author SirWellington */ internal class SQLUserRepository @Inject constructor(val database: JdbcOperations, val serializer: DatabaseSerializer<User>) : UserRepository { private companion object { private val LOG = LoggerFactory.getLogger(this::class.java) } override fun saveUser(user: User) { checkThat(user) .throwing(InvalidArgumentException::class.java) .isA(validUser()) val sql = Inserts.USER try { serializer.save(user, sql, database) } catch(ex: Exception) { failWithMessage("Failed to save user in database: [$user]", ex) } } override fun getUser(userId: String): User { checkUserId(userId) val sql = Queries.SELECT_USER return try { database.queryForObject(sql, serializer, userId.toUUID()) } catch (ex: EmptyResultDataAccessException) { logAndFailWithNoSuchUser(userId) } catch (ex: Exception) { val message = "Failed to retrieve User with ID [$userId] from database" failWithMessage(message, ex) } } override fun deleteUser(userId: String) { checkUserId(userId) val sql = Deletes.USER try { val updated = database.update(sql, userId.toUUID()) LOG.info("Successfully deleted $userId. $updated rows affedted") } catch (ex: Exception) { failWithMessage("Failed to delete user $userId", ex) } } override fun containsUser(userId: String): Boolean { checkUserId(userId) val sql = Queries.CHECK_USER return try { database.queryForObject(sql, Boolean::class.java, userId.toUUID()) } catch (ex: Exception) { failWithMessage("Failed to check if user exists: [$userId]", ex) } } override fun getUserByEmail(emailAddress: String): User { checkThat(emailAddress) .throwing(InvalidArgumentException::class.java) .isA(validEmailAddress()) val sql = Queries.SELECT_USER_BY_EMAIL return try { database.queryForObject(sql, serializer, emailAddress) } catch (ex: EmptyResultDataAccessException) { val message = "Could not find a user with email address: [$emailAddress]" logAndFailWithNoSuchUser(message) } catch (ex: Exception) { failWithMessage("Failed to get a user by $emailAddress", ex) } } override fun findByGithubProfile(githubProfile: String): User { checkThat(githubProfile) .throwing(InvalidArgumentException::class.java) .isA(nonEmptyString()) val sql = Queries.SELECT_USER_BY_GITHUB return try { database.queryForObject(sql, serializer, githubProfile) } catch (ex: EmptyResultDataAccessException) { val message = "Could not find a user with Github profile [$githubProfile]" logAndFailWithNoSuchUser(message) } catch (ex: Exception) { val message = "Failed to query for a user with Github profile [$githubProfile]" failWithMessage(message, ex) } } override fun getRecentlyCreatedUsers(): MutableList<User> { val sql = Queries.SELECT_RECENT_USERS return try { database.query(sql, serializer) } catch (ex: Exception) { val message = "Failed to return a list of recent Users" LOG.error(message, ex) return mutableListOf() } } private fun logAndFailWithNoSuchUser(message: String? = null): Nothing { val message = message ?: "User does not exist" LOG.warn(message) throw UserDoesNotExistException(message) } }
apache-2.0
6a29b65b4857a5f5436ba3910d2d1f46
26.974227
91
0.626428
4.743007
false
false
false
false
Xenoage/Zong
core/src/com/xenoage/zong/core/text/FormattedTextStyle.kt
1
1025
package com.xenoage.zong.core.text import com.xenoage.utils.Cache import com.xenoage.utils.color.Color import com.xenoage.utils.font.FontInfo import com.xenoage.utils.font.FontInfo.Companion.defaultFontInfo import com.xenoage.zong.core.format.Defaults /** * Style of a [FormattedTextString]. */ data class FormattedTextStyle private constructor( val fontInfo: FontInfo, val color: Color, val superscript: Superscript ) { companion object { val defaultColor = Color.black val defaultSuperscript = Superscript.Normal val defaultFormattedTextStyle = FormattedTextStyle(defaultFontInfo, defaultColor, defaultSuperscript) var cache = Cache<FormattedTextStyle, FormattedTextStyle>(100) operator fun invoke(fontInfo: FontInfo = Defaults.defaultFont, color: Color = defaultColor, superscript: Superscript = defaultSuperscript): FormattedTextStyle { val style = FormattedTextStyle(fontInfo, color, superscript) //can be garbage collected if already in cache return cache[style, { style }] } } }
agpl-3.0
915ce3031b98d24df2e5574837f59e84
29.147059
110
0.78439
3.957529
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/implementMembers/ImplementMembersFix.kt
4
1146
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.implementMembers import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.lang.core.psi.RsImplItem /** * Adds unimplemented methods and associated types to an impl block */ class ImplementMembersFix( implBody: RsImplItem ) : LocalQuickFixAndIntentionActionOnPsiElement(implBody) { override fun getText(): String = "Implement members" override fun getFamilyName(): String = text override fun startInWriteAction(): Boolean = false override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement = currentFile override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val impl = (startElement as RsImplItem) generateTraitMembers(impl, editor) } }
mit
e6443091f24c29e2ae66389a3d18c491
28.384615
89
0.742583
4.876596
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/graphql/database/src/main/kotlin/org/tsdes/advanced/graphql/database/repository/DefaultDataService.kt
1
1198
package org.tsdes.advanced.graphql.database.repository import org.springframework.stereotype.Service import org.tsdes.advanced.graphql.database.entity.AuthorEntity import org.tsdes.advanced.graphql.database.entity.CommentEntity import org.tsdes.advanced.graphql.database.entity.PostEntity import javax.annotation.PostConstruct import javax.transaction.Transactional @Service class DefaultDataService( private val postRepository: PostRepository, private val authorRepository: AuthorRepository ) { @PostConstruct @Transactional fun initialize() { val a0 = AuthorEntity("Foo", "Bar") val a1 = AuthorEntity("John", "Smith") val p0 = PostEntity(a0, "Foo is the word!") val p1 = PostEntity(a0, "On the many uses of the word Foo") val p2 = PostEntity(a1, "On GraphQL") val c0 = CommentEntity(a1, p0, "No it is not!") val c1 = CommentEntity(a0, p0, "Yes it is!") val c2 = CommentEntity(a1, p1, "Please just stop") p0.comments.add(c0) p0.comments.add(c1) p1.comments.add(c2) authorRepository.saveAll(listOf(a0, a1)) postRepository.saveAll(listOf(p0, p1, p2)) } }
lgpl-3.0
86e00da597a089fcb916b9c26bbb32aa
29.74359
67
0.687813
3.732087
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/Clickable.kt
3
21663
/* * 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.foundation import androidx.compose.foundation.gestures.PressGestureScope import androidx.compose.foundation.gestures.detectTapAndPress import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onKeyEvent import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.canScroll import androidx.compose.ui.input.consumeScrollContainerInfo import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.disabled import androidx.compose.ui.semantics.onClick import androidx.compose.ui.semantics.onLongClick import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.center import androidx.compose.ui.unit.toOffset import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * Configure component to receive clicks via input or accessibility "click" event. * * Add this modifier to the element to make it clickable within its bounds and show a default * indication when it's pressed. * * This version has no [MutableInteractionSource] or [Indication] parameters, default indication from * [LocalIndication] will be used. To specify [MutableInteractionSource] or [Indication], use another * overload. * * If you need to support double click or long click alongside the single click, consider * using [combinedClickable]. * * @sample androidx.compose.foundation.samples.ClickableSample * * @param enabled Controls the enabled state. When `false`, [onClick], and this modifier will * appear disabled for accessibility services * @param onClickLabel semantic / accessibility label for the [onClick] action * @param role the type of user interface element. Accessibility services might use this * to describe the element or do customizations * @param onClick will be called when user clicks on the element */ fun Modifier.clickable( enabled: Boolean = true, onClickLabel: String? = null, role: Role? = null, onClick: () -> Unit ) = composed( inspectorInfo = debugInspectorInfo { name = "clickable" properties["enabled"] = enabled properties["onClickLabel"] = onClickLabel properties["role"] = role properties["onClick"] = onClick } ) { Modifier.clickable( enabled = enabled, onClickLabel = onClickLabel, onClick = onClick, role = role, indication = LocalIndication.current, interactionSource = remember { MutableInteractionSource() } ) } /** * Configure component to receive clicks via input or accessibility "click" event. * * Add this modifier to the element to make it clickable within its bounds and show an indication * as specified in [indication] parameter. * * If you need to support double click or long click alongside the single click, consider * using [combinedClickable]. * * @sample androidx.compose.foundation.samples.ClickableSample * * @param interactionSource [MutableInteractionSource] that will be used to dispatch * [PressInteraction.Press] when this clickable is pressed. Only the initial (first) press will be * recorded and dispatched with [MutableInteractionSource]. * @param indication indication to be shown when modified element is pressed. By default, * indication from [LocalIndication] will be used. Pass `null` to show no indication, or * current value from [LocalIndication] to show theme default * @param enabled Controls the enabled state. When `false`, [onClick], and this modifier will * appear disabled for accessibility services * @param onClickLabel semantic / accessibility label for the [onClick] action * @param role the type of user interface element. Accessibility services might use this * to describe the element or do customizations * @param onClick will be called when user clicks on the element */ fun Modifier.clickable( interactionSource: MutableInteractionSource, indication: Indication?, enabled: Boolean = true, onClickLabel: String? = null, role: Role? = null, onClick: () -> Unit ) = composed( factory = { val onClickState = rememberUpdatedState(onClick) val pressedInteraction = remember { mutableStateOf<PressInteraction.Press?>(null) } val currentKeyPressInteractions = remember { mutableMapOf<Key, PressInteraction.Press>() } if (enabled) { PressedInteractionSourceDisposableEffect( interactionSource, pressedInteraction, currentKeyPressInteractions ) } val delayPressInteraction = remember { mutableStateOf({ true }) } val centreOffset = remember { mutableStateOf(Offset.Zero) } val gesture = Modifier.pointerInput(interactionSource, enabled) { centreOffset.value = size.center.toOffset() detectTapAndPress( onPress = { offset -> if (enabled) { handlePressInteraction( offset, interactionSource, pressedInteraction, delayPressInteraction ) } }, onTap = { if (enabled) onClickState.value.invoke() } ) } Modifier .consumeScrollContainerInfo { scrollContainerInfo -> delayPressInteraction.value = { scrollContainerInfo?.canScroll() == true } } .genericClickableWithoutGesture( gestureModifiers = gesture, interactionSource = interactionSource, indication = indication, indicationScope = rememberCoroutineScope(), currentKeyPressInteractions = currentKeyPressInteractions, keyClickOffset = centreOffset, enabled = enabled, onClickLabel = onClickLabel, role = role, onLongClickLabel = null, onLongClick = null, onClick = onClick ) }, inspectorInfo = debugInspectorInfo { name = "clickable" properties["enabled"] = enabled properties["onClickLabel"] = onClickLabel properties["role"] = role properties["onClick"] = onClick properties["indication"] = indication properties["interactionSource"] = interactionSource } ) /** * Configure component to receive clicks, double clicks and long clicks via input or accessibility * "click" event. * * Add this modifier to the element to make it clickable within its bounds. * * If you need only click handling, and no double or long clicks, consider using [clickable] * * This version has no [MutableInteractionSource] or [Indication] parameters, default indication * from [LocalIndication] will be used. To specify [MutableInteractionSource] or [Indication], * use another overload. * * @sample androidx.compose.foundation.samples.ClickableSample * * @param enabled Controls the enabled state. When `false`, [onClick], [onLongClick] or * [onDoubleClick] won't be invoked * @param onClickLabel semantic / accessibility label for the [onClick] action * @param role the type of user interface element. Accessibility services might use this * to describe the element or do customizations * @param onLongClickLabel semantic / accessibility label for the [onLongClick] action * @param onLongClick will be called when user long presses on the element * @param onDoubleClick will be called when user double clicks on the element * @param onClick will be called when user clicks on the element */ @ExperimentalFoundationApi fun Modifier.combinedClickable( enabled: Boolean = true, onClickLabel: String? = null, role: Role? = null, onLongClickLabel: String? = null, onLongClick: (() -> Unit)? = null, onDoubleClick: (() -> Unit)? = null, onClick: () -> Unit ) = composed( inspectorInfo = debugInspectorInfo { name = "combinedClickable" properties["enabled"] = enabled properties["onClickLabel"] = onClickLabel properties["role"] = role properties["onClick"] = onClick properties["onDoubleClick"] = onDoubleClick properties["onLongClick"] = onLongClick properties["onLongClickLabel"] = onLongClickLabel } ) { Modifier.combinedClickable( enabled = enabled, onClickLabel = onClickLabel, onLongClickLabel = onLongClickLabel, onLongClick = onLongClick, onDoubleClick = onDoubleClick, onClick = onClick, role = role, indication = LocalIndication.current, interactionSource = remember { MutableInteractionSource() } ) } /** * Configure component to receive clicks, double clicks and long clicks via input or accessibility * "click" event. * * Add this modifier to the element to make it clickable within its bounds. * * If you need only click handling, and no double or long clicks, consider using [clickable]. * * Add this modifier to the element to make it clickable within its bounds. * * @sample androidx.compose.foundation.samples.ClickableSample * * @param interactionSource [MutableInteractionSource] that will be used to emit * [PressInteraction.Press] when this clickable is pressed. Only the initial (first) press will be * recorded and emitted with [MutableInteractionSource]. * @param indication indication to be shown when modified element is pressed. By default, * indication from [LocalIndication] will be used. Pass `null` to show no indication, or * current value from [LocalIndication] to show theme default * @param enabled Controls the enabled state. When `false`, [onClick], [onLongClick] or * [onDoubleClick] won't be invoked * @param onClickLabel semantic / accessibility label for the [onClick] action * @param role the type of user interface element. Accessibility services might use this * to describe the element or do customizations * @param onLongClickLabel semantic / accessibility label for the [onLongClick] action * @param onLongClick will be called when user long presses on the element * @param onDoubleClick will be called when user double clicks on the element * @param onClick will be called when user clicks on the element */ @ExperimentalFoundationApi fun Modifier.combinedClickable( interactionSource: MutableInteractionSource, indication: Indication?, enabled: Boolean = true, onClickLabel: String? = null, role: Role? = null, onLongClickLabel: String? = null, onLongClick: (() -> Unit)? = null, onDoubleClick: (() -> Unit)? = null, onClick: () -> Unit ) = composed( factory = { val onClickState = rememberUpdatedState(onClick) val onLongClickState = rememberUpdatedState(onLongClick) val onDoubleClickState = rememberUpdatedState(onDoubleClick) val hasLongClick = onLongClick != null val hasDoubleClick = onDoubleClick != null val pressedInteraction = remember { mutableStateOf<PressInteraction.Press?>(null) } val currentKeyPressInteractions = remember { mutableMapOf<Key, PressInteraction.Press>() } if (enabled) { // Handles the case where a long click causes a null onLongClick lambda to be passed, // so we can cancel the existing press. DisposableEffect(hasLongClick) { onDispose { pressedInteraction.value?.let { oldValue -> val interaction = PressInteraction.Cancel(oldValue) interactionSource.tryEmit(interaction) pressedInteraction.value = null } } } PressedInteractionSourceDisposableEffect( interactionSource, pressedInteraction, currentKeyPressInteractions ) } val delayPressInteraction = remember { mutableStateOf({ true }) } val centreOffset = remember { mutableStateOf(Offset.Zero) } val gesture = Modifier.pointerInput(interactionSource, hasLongClick, hasDoubleClick, enabled) { centreOffset.value = size.center.toOffset() detectTapGestures( onDoubleTap = if (hasDoubleClick && enabled) { { onDoubleClickState.value?.invoke() } } else { null }, onLongPress = if (hasLongClick && enabled) { { onLongClickState.value?.invoke() } } else { null }, onPress = { offset -> if (enabled) { handlePressInteraction( offset, interactionSource, pressedInteraction, delayPressInteraction ) } }, onTap = { if (enabled) onClickState.value.invoke() } ) } Modifier .genericClickableWithoutGesture( gestureModifiers = gesture, interactionSource = interactionSource, indication = indication, indicationScope = rememberCoroutineScope(), currentKeyPressInteractions = currentKeyPressInteractions, keyClickOffset = centreOffset, enabled = enabled, onClickLabel = onClickLabel, role = role, onLongClickLabel = onLongClickLabel, onLongClick = onLongClick, onClick = onClick ) .consumeScrollContainerInfo { scrollContainerInfo -> delayPressInteraction.value = { scrollContainerInfo?.canScroll() == true } } }, inspectorInfo = debugInspectorInfo { name = "combinedClickable" properties["enabled"] = enabled properties["onClickLabel"] = onClickLabel properties["role"] = role properties["onClick"] = onClick properties["onDoubleClick"] = onDoubleClick properties["onLongClick"] = onLongClick properties["onLongClickLabel"] = onLongClickLabel properties["indication"] = indication properties["interactionSource"] = interactionSource } ) @Composable internal fun PressedInteractionSourceDisposableEffect( interactionSource: MutableInteractionSource, pressedInteraction: MutableState<PressInteraction.Press?>, currentKeyPressInteractions: MutableMap<Key, PressInteraction.Press> ) { DisposableEffect(interactionSource) { onDispose { pressedInteraction.value?.let { oldValue -> val interaction = PressInteraction.Cancel(oldValue) interactionSource.tryEmit(interaction) pressedInteraction.value = null } currentKeyPressInteractions.values.forEach { interactionSource.tryEmit(PressInteraction.Cancel(it)) } currentKeyPressInteractions.clear() } } } internal suspend fun PressGestureScope.handlePressInteraction( pressPoint: Offset, interactionSource: MutableInteractionSource, pressedInteraction: MutableState<PressInteraction.Press?>, delayPressInteraction: State<() -> Boolean> ) { coroutineScope { val delayJob = launch { if (delayPressInteraction.value()) { delay(TapIndicationDelay) } val pressInteraction = PressInteraction.Press(pressPoint) interactionSource.emit(pressInteraction) pressedInteraction.value = pressInteraction } val success = tryAwaitRelease() if (delayJob.isActive) { delayJob.cancelAndJoin() // The press released successfully, before the timeout duration - emit the press // interaction instantly. No else branch - if the press was cancelled before the // timeout, we don't want to emit a press interaction. if (success) { val pressInteraction = PressInteraction.Press(pressPoint) val releaseInteraction = PressInteraction.Release(pressInteraction) interactionSource.emit(pressInteraction) interactionSource.emit(releaseInteraction) } } else { pressedInteraction.value?.let { pressInteraction -> val endInteraction = if (success) { PressInteraction.Release(pressInteraction) } else { PressInteraction.Cancel(pressInteraction) } interactionSource.emit(endInteraction) } } pressedInteraction.value = null } } /** * How long to wait before appearing 'pressed' (emitting [PressInteraction.Press]) - if a touch * down will quickly become a drag / scroll, this timeout means that we don't show a press effect. */ internal expect val TapIndicationDelay: Long /** * Whether the specified [KeyEvent] should trigger a press for a clickable component. */ internal expect val KeyEvent.isPress: Boolean /** * Whether the specified [KeyEvent] should trigger a click for a clickable component. */ internal expect val KeyEvent.isClick: Boolean internal fun Modifier.genericClickableWithoutGesture( gestureModifiers: Modifier, interactionSource: MutableInteractionSource, indication: Indication?, indicationScope: CoroutineScope, currentKeyPressInteractions: MutableMap<Key, PressInteraction.Press>, keyClickOffset: State<Offset>, enabled: Boolean = true, onClickLabel: String? = null, role: Role? = null, onLongClickLabel: String? = null, onLongClick: (() -> Unit)? = null, onClick: () -> Unit ): Modifier { fun Modifier.clickSemantics() = this.semantics(mergeDescendants = true) { if (role != null) { this.role = role } // b/156468846: add long click semantics and double click if needed onClick( action = { onClick(); true }, label = onClickLabel ) if (onLongClick != null) { onLongClick(action = { onLongClick(); true }, label = onLongClickLabel) } if (!enabled) { disabled() } } fun Modifier.detectPressAndClickFromKey() = this.onKeyEvent { keyEvent -> when { enabled && keyEvent.isPress -> { // If the key already exists in the map, keyEvent is a repeat event. // We ignore it as we only want to emit an interaction for the initial key press. if (!currentKeyPressInteractions.containsKey(keyEvent.key)) { val press = PressInteraction.Press(keyClickOffset.value) currentKeyPressInteractions[keyEvent.key] = press indicationScope.launch { interactionSource.emit(press) } true } else { false } } enabled && keyEvent.isClick -> { currentKeyPressInteractions.remove(keyEvent.key)?.let { indicationScope.launch { interactionSource.emit(PressInteraction.Release(it)) } } onClick() true } else -> false } } return this .clickSemantics() .detectPressAndClickFromKey() .indication(interactionSource, indication) .hoverable(enabled = enabled, interactionSource = interactionSource) .focusableInNonTouchMode(enabled = enabled, interactionSource = interactionSource) .then(gestureModifiers) }
apache-2.0
af4ce0113bc3fe127d18fa64fb1c4f39
40.264762
101
0.656603
5.364785
false
false
false
false
androidx/androidx
lifecycle/lifecycle-runtime-ktx-lint/src/main/java/androidx/lifecycle/lint/RepeatOnLifecycleDetector.kt
3
5679
/* * 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.lifecycle.lint import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import com.android.tools.lint.detector.api.isKotlin import com.intellij.psi.PsiMethod import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UClass import org.jetbrains.uast.UMethod import org.jetbrains.uast.UastFacade import org.jetbrains.uast.visitor.AbstractUastVisitor /** * Lint check for detecting calls to the suspend `repeatOnLifecycle` APIs in wrong lifecycle * methods of [androidx.fragment.app.Fragment] or [androidx.core.app.ComponentActivity]. */ class RepeatOnLifecycleDetector : Detector(), SourceCodeScanner { companion object { val ISSUE = Issue.create( id = "RepeatOnLifecycleWrongUsage", briefDescription = "Wrong usage of repeatOnLifecycle.", explanation = """The repeatOnLifecycle APIs should be used when the View is created, \ that is in the `onCreate` lifecycle method for Activities, or `onViewCreated` in \ case you're using Fragments.""", category = Category.CORRECTNESS, severity = Severity.ERROR, implementation = Implementation( RepeatOnLifecycleDetector::class.java, Scope.JAVA_FILE_SCOPE ), androidSpecific = true ) } private val lifecycleMethods = setOf("onStart", "onResume") override fun applicableSuperClasses(): List<String>? = listOf(FRAGMENT_CLASS, ACTIVITY_CLASS) override fun visitClass(context: JavaContext, declaration: UClass) { if (!isKotlin(context.psiFile)) return // Check only Kotlin files val visitedMethods = mutableSetOf<PsiMethod>() declaration.methods.forEach { method -> if (lifecycleMethods.contains(method.name)) { val visitor = RecursiveMethodVisitor( context, declaration.name, method, visitedMethods ) method.uastBody?.accept(visitor) } } } } /** * A UAST Visitor that recursively explores all method calls within an Activity or Fragment * lifecycle method to check for wrong method calls to repeatOnLifecycle. * * @param context The context of the lint request. * @param originClassName The name of the class being checked. * @param lifecycleMethod The originating lifecycle method. */ private class RecursiveMethodVisitor( private val context: JavaContext, private val originClassName: String?, private val lifecycleMethod: PsiMethod, private val visitedMethods: MutableSet<PsiMethod> ) : AbstractUastVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { val psiMethod = node.resolve() ?: return super.visitCallExpression(node) if (visitedMethods.contains(psiMethod)) { return super.visitCallExpression(node) } // Don't add UNSAFE_METHOD to the list of visitedMethods if (psiMethod.name != UNSAFE_METHOD.name) { visitedMethods.add(psiMethod) } // Check current method and report if there's a wrong repeatOnLifecycle usage if (!checkMethodCall(psiMethod, node)) { val uastNode = UastFacade.convertElementWithParent( psiMethod, UMethod::class.java ) as? UMethod uastNode?.uastBody?.accept(this) } return super.visitCallExpression(node) } /** * Checks if the current method call is not correct. * * Returns `true` and report the appropriate lint issue if an error is found, otherwise return * `false`. * * @param psiMethod The resolved [PsiMethod] of the call to check. * @param expression Original expression. * @return `true` if a lint error was found and reported, `false` otherwise. */ private fun checkMethodCall(psiMethod: PsiMethod, expression: UCallExpression): Boolean { val method = Method(psiMethod.containingClass?.qualifiedName, psiMethod.name) return if (method == UNSAFE_METHOD) { context.report( RepeatOnLifecycleDetector.ISSUE, context.getLocation(expression), "Wrong usage of ${method.name} from $originClassName.${lifecycleMethod.name}." ) true } else { false } } } internal data class Method(val cls: String?, val name: String) private val UNSAFE_METHOD = Method( "androidx.lifecycle.RepeatOnLifecycleKt", "repeatOnLifecycle" ) private const val FRAGMENT_CLASS = "androidx.fragment.app.Fragment" private const val ACTIVITY_CLASS = "androidx.core.app.ComponentActivity"
apache-2.0
7a64fd04eb829fb3b7df8cbdeb2ce2bc
38.713287
98
0.690438
4.752301
false
false
false
false
androidx/androidx
compose/material3/material3/integration-tests/material3-catalog/src/main/java/androidx/compose/material3/catalog/library/ui/component/ComponentItem.kt
3
2888
/* * 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.compose.material3.catalog.library.ui.component import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedCard import androidx.compose.material3.Text import androidx.compose.material3.catalog.library.model.Component import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp @OptIn(ExperimentalMaterial3Api::class) @Composable fun ComponentItem( component: Component, onClick: (component: Component) -> Unit ) { OutlinedCard( onClick = { onClick(component) }, modifier = Modifier .height(ComponentItemHeight) .padding(ComponentItemOuterPadding) ) { Box(modifier = Modifier.fillMaxSize().padding(ComponentItemInnerPadding)) { Image( painter = painterResource(id = component.icon), contentDescription = null, modifier = Modifier .size(ComponentItemIconSize) .align(Alignment.Center), colorFilter = if (component.tintIcon) { ColorFilter.tint(LocalContentColor.current) } else { null }, contentScale = ContentScale.Inside ) Text( text = component.name, modifier = Modifier.align(Alignment.BottomStart), style = MaterialTheme.typography.bodySmall ) } } } private val ComponentItemHeight = 180.dp private val ComponentItemOuterPadding = 4.dp private val ComponentItemInnerPadding = 16.dp private val ComponentItemIconSize = 80.dp
apache-2.0
cb15a88a0ea624a7257c78236e7e1dc6
36.506494
83
0.709834
4.718954
false
false
false
false
cat-in-the-dark/GamesServer
lib-server/src/main/kotlin/org/catinthedark/server/GameHandler.kt
1
2003
package org.catinthedark.server import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.channel.SimpleChannelInboundHandler import org.catinthedark.shared.event_bus.BusRegister import org.catinthedark.shared.event_bus.EventBus import org.catinthedark.shared.invokers.Invoker import org.slf4j.LoggerFactory /** * This is main Netty handler. * It sends events to [EventBus] about client connections, disconnections and messages. * This service listen to [TCPMessage] on [EventBus]. * You can send a message to other clients by sending [TCPMessage] via [EventBus] */ class GameHandler( private val invoker: Invoker, private val channels: MutableMap<String, Channel> ) : SimpleChannelInboundHandler<Any>() { private val log = LoggerFactory.getLogger(this::class.java) override fun handlerAdded(ctx: ChannelHandlerContext?) { super.handlerAdded(ctx) BusRegister.register(this) } override fun handlerRemoved(ctx: ChannelHandlerContext?) { super.handlerRemoved(ctx) BusRegister.unregister(this) } override fun channelRead0(ctx: ChannelHandlerContext, msg: Any?) { if (msg == null) return EventBus.send("GameHandler#channelRead0", invoker, msg, ctx.channel().id().asLongText()) } override fun channelRegistered(ctx: ChannelHandlerContext) { val id = ctx.channel().id().asLongText() channels.put(id, ctx.channel()) EventBus.send("GameHandler#channelRegistered", invoker, OnClientConnected( ctx.channel().remoteAddress(), id )) super.channelRegistered(ctx) } override fun channelUnregistered(ctx: ChannelHandlerContext) { val id = ctx.channel().id().asLongText() EventBus.send("GameHandler#channelUnregistered", invoker, OnClientDisconnected( ctx.channel().remoteAddress(), id )) channels.remove(id) super.channelUnregistered(ctx) } }
mit
f15490dc70237aeaa7bddb42c6b14d3f
34.140351
96
0.702946
4.461024
false
false
false
false
Soya93/Extract-Refactoring
platform/configuration-store-impl/src/XmlElementStorage.kt
4
9244
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.util.JDOMUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.SmartHashSet import com.intellij.util.loadElement import gnu.trove.THashMap import org.jdom.Attribute import org.jdom.Element abstract class XmlElementStorage protected constructor(protected val fileSpec: String, protected val rootElementName: String, protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null, roamingType: RoamingType? = RoamingType.DEFAULT, provider: StreamProvider? = null) : StorageBaseEx<StateMap>() { val roamingType: RoamingType = roamingType ?: RoamingType.DEFAULT private val provider: StreamProvider? = if (provider == null || roamingType == RoamingType.DISABLED || !provider.isApplicable(fileSpec, this.roamingType)) null else provider protected abstract fun loadLocalData(): Element? override final fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean) = storageData.getState(componentName, archive) override fun archiveState(storageData: StateMap, componentName: String, serializedState: Element?) { storageData.archive(componentName, serializedState) } override fun hasState(storageData: StateMap, componentName: String) = storageData.hasState(componentName) override fun loadData(): StateMap { val element: Element? // we don't use local data if has stream provider if (provider != null && provider.enabled) { try { element = loadDataFromProvider() dataLoadedFromProvider(element) } catch (e: Exception) { LOG.error(e) element = null } } else { element = loadLocalData() } return if (element == null) StateMap.EMPTY else loadState(element) } protected open fun dataLoadedFromProvider(element: Element?) { } private fun loadDataFromProvider() = provider!!.read(fileSpec, roamingType)?.let { loadElement(it) } private fun loadState(element: Element): StateMap { beforeElementLoaded(element) return StateMap.fromMap(FileStorageCoreUtil.load(element, pathMacroSubstitutor, true)) } fun setDefaultState(element: Element) { element.name = rootElementName storageDataRef.set(loadState(element)) } override fun startExternalization() = if (checkIsSavingDisabled()) null else createSaveSession(getStorageData()) protected abstract fun createSaveSession(states: StateMap): StateStorage.ExternalizationSession override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) { val oldData = storageDataRef.get() val newData = getStorageData(true) if (oldData == null) { LOG.debug { "analyzeExternalChangesAndUpdateIfNeed: old data null, load new for ${toString()}" } componentNames.addAll(newData.keys()) } else { val changedComponentNames = oldData.getChangedComponentNames(newData) LOG.debug { "analyzeExternalChangesAndUpdateIfNeed: changedComponentNames $changedComponentNames for ${toString()}" } if (!ContainerUtil.isEmpty(changedComponentNames)) { componentNames.addAll(changedComponentNames) } } } private fun setStates(oldStorageData: StateMap, newStorageData: StateMap?) { if (oldStorageData !== newStorageData && storageDataRef.getAndSet(newStorageData) !== oldStorageData) { LOG.warn("Old storage data is not equal to current, new storage data was set anyway") } } abstract class XmlElementStorageSaveSession<T : XmlElementStorage>(private val originalStates: StateMap, protected val storage: T) : SaveSessionBase() { private var copiedStates: MutableMap<String, Any>? = null private val newLiveStates = THashMap<String, Element>() override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStates == null) null else this override fun setSerializedState(componentName: String, element: Element?) { element?.normalizeRootName() if (copiedStates == null) { copiedStates = setStateAndCloneIfNeed(componentName, element, originalStates, newLiveStates) } else { updateState(copiedStates!!, componentName, element, newLiveStates) } } override fun save() { val stateMap = StateMap.fromMap(copiedStates!!) var element = save(stateMap, storage.rootElementName, newLiveStates) if (element == null || JDOMUtil.isEmpty(element)) { element = null } else { storage.beforeElementSaved(element) } val provider = storage.provider if (provider != null && provider.enabled) { if (element == null) { provider.delete(storage.fileSpec, storage.roamingType) } else { // we should use standard line-separator (\n) - stream provider can share file content on any OS provider.write(storage.fileSpec, element.toBufferExposingByteArray(), storage.roamingType) } } else { saveLocally(element) } storage.setStates(originalStates, stateMap) } protected abstract fun saveLocally(element: Element?) } protected open fun beforeElementLoaded(element: Element) { } protected open fun beforeElementSaved(element: Element) { if (pathMacroSubstitutor != null) { try { pathMacroSubstitutor.collapsePaths(element) } finally { pathMacroSubstitutor.reset() } } } fun updatedFromStreamProvider(changedComponentNames: MutableSet<String>, deleted: Boolean) { if (roamingType == RoamingType.DISABLED) { // storage roaming was changed to DISABLED, but settings repository has old state return } try { val newElement = if (deleted) null else loadDataFromProvider() val states = storageDataRef.get() if (newElement == null) { // if data was loaded, mark as changed all loaded components if (states != null) { changedComponentNames.addAll(states.keys()) setStates(states, null) } } else if (states != null) { val newStates = loadState(newElement) changedComponentNames.addAll(states.getChangedComponentNames(newStates)) setStates(states, newStates) } } catch (e: Throwable) { LOG.error(e) } } } fun save(states: StateMap, rootElementName: String, newLiveStates: Map<String, Element>? = null): Element? { if (states.isEmpty()) { return null } val rootElement = Element(rootElementName) for (componentName in states.keys()) { val element = states.getElement(componentName, newLiveStates) ?: continue // name attribute should be first val elementAttributes = element.attributes if (elementAttributes.isEmpty()) { element.setAttribute(FileStorageCoreUtil.NAME, componentName) } else { var nameAttribute: Attribute? = element.getAttribute(FileStorageCoreUtil.NAME) if (nameAttribute == null) { nameAttribute = Attribute(FileStorageCoreUtil.NAME, componentName) elementAttributes.add(0, nameAttribute) } else { nameAttribute.value = componentName if (elementAttributes.get(0) != nameAttribute) { elementAttributes.remove(nameAttribute) elementAttributes.add(0, nameAttribute) } } } rootElement.addContent(element) } return rootElement } internal fun Element.normalizeRootName(): Element { if (parent != null) { LOG.warn("State element must not have parent ${JDOMUtil.writeElement(this)}") detach() } name = FileStorageCoreUtil.COMPONENT return this } // newStorageData - myStates contains only live (unarchived) states private fun StateMap.getChangedComponentNames(newStates: StateMap): Set<String> { val bothStates = keys().toMutableSet() bothStates.retainAll(newStates.keys()) val diffs = SmartHashSet<String>() diffs.addAll(newStates.keys()) diffs.addAll(keys()) diffs.removeAll(bothStates) for (componentName in bothStates) { compare(componentName, newStates, diffs) } return diffs }
apache-2.0
3276e4702103ee8baeeac88b61983b1a
35.541502
175
0.696993
5.034858
false
false
false
false
jooby-project/jooby
modules/jooby-openapi/src/test/kotlin/kt/i2121/Controller2121.kt
1
1081
/* * Jooby https://jooby.io * Apache License Version 2.0 https://jooby.io/LICENSE.txt * Copyright 2014 Edgar Espina */ package kt.i2121 import io.jooby.annotations.GET import io.jooby.annotations.Path import io.jooby.annotations.QueryParam import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.Parameter import kotlinx.coroutines.delay @Path("/") class Controller2121 { @Operation( summary = "Values for single ID", description = "Delivers full data for an ID for a given year", parameters = [ Parameter( name = "year", example = "2018", description = "The year where the data will be retrieved", required = true ), Parameter( name = "id", example = "XD12345", description = "An ID value which belongs to a dataset", required = true )] ) @GET suspend fun listDataForID(@QueryParam year: Int, @QueryParam id: String): String { delay(1000L) return "Welcome to Jooby! Year=${year} and ID=${id}" } }
apache-2.0
45a887ecd206088e4296776de7f6df6d
25.365854
84
0.637373
4.033582
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/util/data/PreferenceHelper.kt
1
6484
package me.proxer.app.util.data import android.content.SharedPreferences import androidx.core.content.edit import com.f2prateek.rx.preferences2.RxSharedPreferences import me.proxer.app.manga.MangaReaderOrientation import me.proxer.app.settings.theme.ThemeContainer import me.proxer.app.util.extension.getSafeString import me.proxer.app.util.wrapper.MaterialDrawerWrapper.DrawerItem import okhttp3.logging.HttpLoggingInterceptor import org.threeten.bp.Instant /** * @author Ruben Gees */ @Suppress("UseDataClass") class PreferenceHelper( initializer: LocalDataInitializer, rxSharedPreferences: RxSharedPreferences, private val sharedPreferences: SharedPreferences ) { companion object { const val CAST_INTRODUCTORY_OVERLAY_SHOWN = "cast_introductory_overlay_shown" const val LAUNCHES = "launches" const val RATED = "rated" const val TWO_FACTOR_AUTHENTICATION = "two_factor_authentication" const val LAST_TAG_UPDATE_DATE = "last_tag_update_date" const val LAST_NEWS_DATE = "last_news_date" const val AGE_CONFIRMATION = "age_confirmation" const val AUTO_BOOKMARK = "auto_bookmark" const val CHECK_CELLULAR = "check_cellular" const val START_PAGE = "start_page" const val THEME = "theme" const val NOTIFICATIONS_NEWS = "notifications_news" const val NOTIFICATIONS_ACCOUNT = "notifications_account" const val NOTIFICATIONS_CHAT = "notifications_chat" const val NOTIFICATIONS_INTERVAL = "notifications_interval" const val MANGA_READER_ORIENTATION = "manga_reader_orientation" const val EXTERNAL_CACHE = "external_cache" const val HTTP_LOG_LEVEL = "http_log_level" const val HTTP_VERBOSE = "http_log_verbose" const val HTTP_REDACT_TOKEN = "http_log_redact_token" } init { initializer.initAndMigrateIfNecessary() } var wasCastIntroductoryOverlayShown: Boolean get() = sharedPreferences.getBoolean(CAST_INTRODUCTORY_OVERLAY_SHOWN, false) set(value) { sharedPreferences.edit { putBoolean(CAST_INTRODUCTORY_OVERLAY_SHOWN, value) } } var launches: Int get() = sharedPreferences.getInt(LAUNCHES, 0) private set(value) { sharedPreferences.edit { putInt(LAUNCHES, value) } } var hasRated: Boolean get() = sharedPreferences.getBoolean(RATED, false) set(value) { sharedPreferences.edit { putBoolean(RATED, value) } } var isTwoFactorAuthenticationEnabled: Boolean get() = sharedPreferences.getBoolean(TWO_FACTOR_AUTHENTICATION, false) set(value) { sharedPreferences.edit { putBoolean(TWO_FACTOR_AUTHENTICATION, value) } } var lastTagUpdateDate: Instant get() = Instant.ofEpochMilli(sharedPreferences.getLong(LAST_TAG_UPDATE_DATE, 0L)) set(value) { sharedPreferences.edit { putLong(LAST_TAG_UPDATE_DATE, value.toEpochMilli()) } } var lastNewsDate: Instant get() = Instant.ofEpochMilli(sharedPreferences.getLong(LAST_NEWS_DATE, 0L)) set(value) { sharedPreferences.edit { putLong(LAST_NEWS_DATE, value.toEpochMilli()) } } var isAgeRestrictedMediaAllowed get() = sharedPreferences.getBoolean(AGE_CONFIRMATION, false) set(value) { sharedPreferences.edit { putBoolean(AGE_CONFIRMATION, value) } } val isAgeRestrictedMediaAllowedObservable = rxSharedPreferences.getBoolean(AGE_CONFIRMATION, false) .asObservable() .skip(1) .publish() .autoConnect() val areBookmarksAutomatic get() = sharedPreferences.getBoolean(AUTO_BOOKMARK, false) var shouldCheckCellular get() = sharedPreferences.getBoolean(CHECK_CELLULAR, true) set(value) { sharedPreferences.edit { putBoolean(CHECK_CELLULAR, value) } } val startPage get() = DrawerItem.fromIdOrDefault( sharedPreferences.getSafeString(START_PAGE, "0").toLongOrNull() ) var areNewsNotificationsEnabled get() = sharedPreferences.getBoolean(NOTIFICATIONS_NEWS, false) set(value) { sharedPreferences.edit { putBoolean(NOTIFICATIONS_NEWS, value) } } var areAccountNotificationsEnabled get() = sharedPreferences.getBoolean(NOTIFICATIONS_ACCOUNT, false) set(value) { sharedPreferences.edit { putBoolean(NOTIFICATIONS_ACCOUNT, value) } } val areChatNotificationsEnabled get() = sharedPreferences.getBoolean(NOTIFICATIONS_CHAT, true) val notificationsInterval get() = sharedPreferences.getSafeString(NOTIFICATIONS_INTERVAL, "30").toLong() var mangaReaderOrientation get() = MangaReaderOrientation.values()[ sharedPreferences.getInt(MANGA_READER_ORIENTATION, MangaReaderOrientation.VERTICAL.ordinal) ] set(value) { sharedPreferences.edit { putInt(MANGA_READER_ORIENTATION, value.ordinal) } } var shouldCacheExternally get() = sharedPreferences.getBoolean(EXTERNAL_CACHE, true) set(value) { sharedPreferences.edit { putBoolean(EXTERNAL_CACHE, value) } } val isCacheExternallySet get() = sharedPreferences.contains(EXTERNAL_CACHE) var themeContainer get() = ThemeContainer.fromPreferenceString(sharedPreferences.getSafeString(THEME, "0_2")) set(value) { sharedPreferences.edit { putString(THEME, value.toPreferenceString()) } } val themeObservable = rxSharedPreferences.getString(THEME, "0_2") .asObservable() .skip(1) .map { ThemeContainer.fromPreferenceString(it) } .publish() .autoConnect() val httpLogLevel get() = when (sharedPreferences.getString(HTTP_LOG_LEVEL, "0")) { "0" -> HttpLoggingInterceptor.Level.BASIC "1" -> HttpLoggingInterceptor.Level.HEADERS "2" -> HttpLoggingInterceptor.Level.BODY else -> error("Unknown http log level saved in shared preferences") } val shouldLogHttpVerbose get() = sharedPreferences.getBoolean(HTTP_VERBOSE, false) val shouldRedactToken get() = sharedPreferences.getBoolean(HTTP_REDACT_TOKEN, false) fun incrementLaunches() = sharedPreferences.edit { putInt(LAUNCHES, sharedPreferences.getInt(LAUNCHES, 0) + 1) } }
gpl-3.0
9de67788c3e795306d775d2429d1f1df
35.632768
116
0.675663
4.608387
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/data/ImageLoader.kt
1
3057
/* * Copyright (C) 2017-2019 yvolk (Yuri Volkov), http://yurivolkov.com * * 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 org.andstatus.app.data import android.view.View import io.vavr.control.Try import org.andstatus.app.MyActivity import org.andstatus.app.graphics.AttachedImageView import org.andstatus.app.graphics.CachedImage import org.andstatus.app.graphics.IdentifiableImageView import org.andstatus.app.graphics.ImageCaches import org.andstatus.app.util.MyLog import org.andstatus.app.util.TryUtils class ImageLoader(mediaFile: MediaFile, private val myActivity: MyActivity, private val imageView: IdentifiableImageView) : AbstractImageLoader(mediaFile, "-asyn-" + imageView.myViewId) { @Volatile private var logged = false fun load(): Try<CachedImage> { return TryUtils.ofNullable( if (skip()) null else ImageCaches.loadAndGetImage(imageView.getCacheName(), mediaFile)) } fun set(tryImage: Try<CachedImage>) { if (skip()) return tryImage.onSuccess { image: CachedImage -> if (image.id != mediaFile.id) { logResult("Wrong image.id:${image.id} on Set") return@onSuccess } try { if (imageView is AttachedImageView) imageView.setMeasuresLocked(true) if (mediaFile.isInvestigated) { mediaFile.logResult("Before Set loaded", taskSuffix) } imageView.setLoaded() imageView.setImageDrawable(image.getDrawable()) imageView.visibility = View.VISIBLE logResult("Set loaded") } catch (e: Exception) { MyLog.d(mediaFile, mediaFile.getMsgLog("Error on setting loaded image", taskSuffix), e) } }.onFailure { e: Throwable -> logResult("No success on Set loaded") } } private fun skip(): Boolean { if (!myActivity.isMyResumed()) { logResult("Skipped not resumed activity") return true } if (imageView.isLoaded()) { logResult("Skipped already loaded") return true } if (imageView.getImageId() != mediaFile.id) { logResult("Skipped view.imageId:" + imageView.getImageId()) return true } return false } private fun logResult(msgLog: String) { if (!logged) { logged = true mediaFile.logResult(msgLog, taskSuffix) } } }
apache-2.0
ba77028f69b3e38e381bd394ada0f155
35.831325
103
0.634936
4.528889
false
false
false
false
world-federation-of-advertisers/panel-exchange-client
src/main/kotlin/org/wfanet/panelmatch/client/eventpreprocessing/EncryptEventsDoFn.kt
1
2764
// Copyright 2021 The Cross-Media Measurement Authors // // 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 org.wfanet.panelmatch.client.eventpreprocessing import com.google.common.base.Stopwatch import com.google.protobuf.ByteString import java.util.concurrent.TimeUnit import org.apache.beam.sdk.metrics.Metrics import org.apache.beam.sdk.transforms.DoFn import org.apache.beam.sdk.values.KV import org.apache.beam.sdk.values.PCollectionView import org.wfanet.panelmatch.common.beam.kvOf import org.wfanet.panelmatch.common.compression.CompressionParameters /** * Encrypts each of a batch of pairs of ByteStrings. * * The outputs are suitable for use as database entries in the Private Membership protocol. */ class EncryptEventsDoFn( private val eventPreprocessor: EventPreprocessor, private val identifierHashPepperProvider: IdentifierHashPepperProvider, private val hkdfPepperProvider: HkdfPepperProvider, private val deterministicCommutativeCipherKeyProvider: DeterministicCommutativeCipherKeyProvider, private val compressionParametersView: PCollectionView<CompressionParameters> ) : DoFn<MutableList<KV<ByteString, ByteString>>, KV<Long, ByteString>>() { private val jniCallTimeDistribution = Metrics.distribution(BatchingDoFn::class.java, "jni-call-time-micros") @ProcessElement fun process(c: ProcessContext) { val events: MutableList<KV<ByteString, ByteString>> = c.element() val request = preprocessEventsRequest { cryptoKey = deterministicCommutativeCipherKeyProvider.get() identifierHashPepper = identifierHashPepperProvider.get() hkdfPepper = hkdfPepperProvider.get() compressionParameters = c.sideInput(compressionParametersView) for (event in events) { unprocessedEvents += unprocessedEvent { id = event.key data = event.value } } } val stopWatch: Stopwatch = Stopwatch.createStarted() val response: PreprocessEventsResponse = eventPreprocessor.preprocess(request) stopWatch.stop() jniCallTimeDistribution.update(stopWatch.elapsed(TimeUnit.MICROSECONDS)) for (processedEvent in response.processedEventsList) { c.output(kvOf(processedEvent.encryptedId, processedEvent.encryptedData)) } } }
apache-2.0
22af4445d4c6980471e65eaeb9811fb9
40.878788
99
0.773878
4.213415
false
true
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/photos/dto/PhotosPhoto.kt
1
3446
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.photos.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import com.vk.sdk.api.base.dto.BaseBoolInt import kotlin.Boolean import kotlin.Float import kotlin.Int import kotlin.String import kotlin.collections.List /** * @param albumId - Album ID * @param date - Date when uploaded * @param id - Photo ID * @param ownerId - Photo owner's ID * @param hasTags - Whether photo has attached tag links * @param accessKey - Access key for the photo * @param height - Original photo height * @param images * @param lat - Latitude * @param long - Longitude * @param photo256 - URL of image with 2560 px width * @param canComment - Information whether current user can comment the photo * @param place * @param postId - Post ID * @param sizes * @param text - Photo caption * @param userId - ID of the user who have uploaded the photo * @param width - Original photo width */ data class PhotosPhoto( @SerializedName("album_id") val albumId: Int, @SerializedName("date") val date: Int, @SerializedName("id") val id: Int, @SerializedName("owner_id") val ownerId: UserId, @SerializedName("has_tags") val hasTags: Boolean, @SerializedName("access_key") val accessKey: String? = null, @SerializedName("height") val height: Int? = null, @SerializedName("images") val images: List<PhotosImage>? = null, @SerializedName("lat") val lat: Float? = null, @SerializedName("long") val long: Float? = null, @SerializedName("photo_256") val photo256: String? = null, @SerializedName("can_comment") val canComment: BaseBoolInt? = null, @SerializedName("place") val place: String? = null, @SerializedName("post_id") val postId: Int? = null, @SerializedName("sizes") val sizes: List<PhotosPhotoSizes>? = null, @SerializedName("text") val text: String? = null, @SerializedName("user_id") val userId: UserId? = null, @SerializedName("width") val width: Int? = null )
mit
1edb67940cff13a837d234e244296d99
34.895833
81
0.677307
4.182039
false
false
false
false
felipebz/sonar-plsql
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/RaiseStandardExceptionCheck.kt
1
2592
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.checks import com.felipebz.flr.api.AstNode import org.sonar.plsqlopen.asTree import org.sonar.plsqlopen.sslr.RaiseStatement import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.annotations.* import java.util.* @Rule(priority = Priority.MAJOR) @ConstantRemediation("20min") @RuleInfo(scope = RuleInfo.Scope.ALL) @ActivatedByDefault class RaiseStandardExceptionCheck : AbstractBaseCheck() { private val standardExceptions = listOf( "ACCESS_INTO_NULL", "CASE_NOT_FOUND", "COLLECTION_IS_NULL", "CURSOR_ALREADY_OPEN", "DUP_VAL_ON_INDEX", "INVALID_CURSOR", "INVALID_NUMBER", "LOGIN_DENIED", "NO_DATA_FOUND", "NOT_LOGGED_ON", "PROGRAM_ERROR", "ROWTYPE_MISMATCH", "SELF_IS_NULL", "STORAGE_ERROR", "SUBSCRIPT_BEYOND_COUNT", "SUBSCRIPT_OUTSIDE_LIMIT", "SYS_INVALID_ROWID", "TIMEOUT_ON_RESOURCE", "TOO_MANY_ROWS", "VALUE_ERROR", "ZERO_DIVIDE") override fun init() { subscribeTo(PlSqlGrammar.RAISE_STATEMENT) } override fun visitNode(node: AstNode) { val statement = node.asTree<RaiseStatement>() val exceptionIdentifier = statement.exception if (exceptionIdentifier != null) { val exceptionName = exceptionIdentifier.tokenOriginalValue if (standardExceptions.contains(exceptionName.uppercase(Locale.getDefault()))) { addLineIssue(getLocalizedMessage(), exceptionIdentifier.tokenLine, exceptionName) } } } }
lgpl-3.0
4cf0e6f5c5fa71efb2e5c0e74585c85c
34.027027
97
0.660108
4.341709
false
false
false
false
yt-tkhs/Search-Filter-UI
app/src/main/java/jp/yitt/filter/SearchConditionListAdapter.kt
1
1477
package jp.yitt.filter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.TextView import java.util.* class SearchConditionListAdapter(val searchConditions: ArrayList<String>) : RecyclerView.Adapter<SearchConditionListAdapter.ViewHolder>() { var listener: OnSearchConditionClickListener? = null override fun getItemCount(): Int = searchConditions.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.textCondition.text = searchConditions.get(position) if (listener != null) { holder.layoutRoot.setOnClickListener { listener!!.onSearchConditionClick(position) }; } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.list_item_search_condition, parent, false)) fun setOnSearchConditionClickListener(listener: OnSearchConditionClickListener) { this.listener = listener } interface OnSearchConditionClickListener { fun onSearchConditionClick(position: Int) } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val textCondition = view.findViewById(R.id.text_condition) as TextView val layoutRoot = view.findViewById(R.id.layout_root) as FrameLayout } }
apache-2.0
8d03d438d9d0ba5ac9d1ac7dd288afff
34.190476
97
0.740691
4.764516
false
false
false
false
BloodWorkXGaming/ExNihiloCreatio
src/main/java/exnihilocreatio/json/CustomFluidJson.kt
1
1230
package exnihilocreatio.json import com.google.gson.* import exnihilocreatio.util.LogUtil import net.minecraftforge.fluids.Fluid import net.minecraftforge.fluids.FluidRegistry import java.lang.reflect.Type object CustomFluidJson : JsonDeserializer<Fluid>, JsonSerializer<Fluid> { override fun serialize(src: Fluid, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { LogUtil.debug("Serialized fluid $src as ${src.name}") return JsonPrimitive(src.name) } @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Fluid { if (json.isJsonPrimitive && json.asJsonPrimitive.isString) { return FluidRegistry.getFluid(json.asString) } else { val helper = JsonHelper(json) val name = helper.getString("name") val fluid = FluidRegistry.getFluid(name) if (fluid == null) { LogUtil.error("Error parsing JSON: Invalid Fluid: $json") LogUtil.error("This may result in crashing or other undefined behavior") return FluidRegistry.WATER } return fluid } } }
mit
9fc636afd09eec6c436e439f80d839d4
33.194444
108
0.669919
4.939759
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/analytic/AnalyticImpl.kt
1
13053
package org.stepic.droid.analytic import android.content.Context import android.content.res.Configuration import android.content.res.Resources import android.os.Bundle import androidx.core.app.NotificationManagerCompat import androidx.core.os.bundleOf import com.amplitude.api.Amplitude import com.amplitude.api.Identify import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.crashlytics.FirebaseCrashlytics import com.google.firebase.ktx.Firebase import com.yandex.metrica.YandexMetrica import com.yandex.metrica.profile.Attribute import com.yandex.metrica.profile.UserProfile import org.json.JSONObject import org.stepic.droid.base.App import org.stepic.droid.configuration.Config import org.stepic.droid.configuration.RemoteConfig import org.stepic.droid.di.AppSingleton import org.stepic.droid.util.isARSupported import org.stepik.android.domain.base.analytic.AnalyticEvent import org.stepik.android.domain.base.analytic.AnalyticSource import org.stepik.android.domain.base.analytic.UserProperty import org.stepik.android.domain.base.analytic.UserPropertySource import ru.nobird.android.view.base.ui.extension.isNightModeEnabled import java.util.HashMap import java.util.Locale import javax.inject.Inject @AppSingleton class AnalyticImpl @Inject constructor( context: Context, config: Config, private val stepikAnalytic: StepikAnalytic ) : Analytic { private companion object { private const val FIREBASE_USER_PROPERTY_NAME_LIMIT = 24 private const val FIREBASE_USER_PROPERTY_VALUE_LIMIT = 36 private const val FIREBASE_LENGTH_LIMIT = 40 inline fun updateYandexUserProfile(mutation: UserProfile.Builder.() -> Unit) { val userProfile = UserProfile.newBuilder() .apply(mutation) .build() YandexMetrica.reportUserProfile(userProfile) } } private val firebaseAnalytics = Firebase.analytics private val firebaseCrashlytics = FirebaseCrashlytics.getInstance() private val amplitude = Amplitude.getInstance() .initialize(context, config.amplitudeApiKey) .enableForegroundTracking(App.application) init { val isNotificationsEnabled = NotificationManagerCompat.from(context).areNotificationsEnabled() amplitude.identify(Identify() .set(AmplitudeAnalytic.Properties.APPLICATION_ID, context.packageName) .set(AmplitudeAnalytic.Properties.PUSH_PERMISSION, if (isNotificationsEnabled) "granted" else "not_granted") .set(AmplitudeAnalytic.Properties.IS_NIGHT_MODE_ENABLED, context.isNightModeEnabled().toString()) .set(AmplitudeAnalytic.Properties.IS_AR_SUPPORTED, context.isARSupported().toString()) ) updateYandexUserProfile { apply(Attribute.notificationsEnabled().withValue(isNotificationsEnabled)) apply(Attribute.customBoolean(AmplitudeAnalytic.Properties.IS_NIGHT_MODE_ENABLED).withValue(context.isNightModeEnabled())) apply(Attribute.customBoolean(AmplitudeAnalytic.Properties.IS_AR_SUPPORTED).withValue(context.isARSupported())) } setFirebaseUserProperty(AmplitudeAnalytic.Properties.PUSH_PERMISSION, if (isNotificationsEnabled) "granted" else "not_granted") setFirebaseUserProperty(AmplitudeAnalytic.Properties.IS_NIGHT_MODE_ENABLED, context.isNightModeEnabled().toString()) setFirebaseUserProperty(AmplitudeAnalytic.Properties.IS_AR_SUPPORTED, context.isARSupported().toString()) } // Amplitude properties private fun syncAmplitudeProperties() { setScreenOrientation(Resources.getSystem().configuration.orientation) } override fun setUserId(userId: String) { firebaseAnalytics.setUserId(userId) firebaseCrashlytics.setUserId(userId) YandexMetrica.setUserProfileID(userId) amplitude.identify(Identify().set(AmplitudeAnalytic.Properties.STEPIK_ID, userId)) } override fun setCoursesCount(coursesCount: Int) { amplitude.identify(Identify().set(AmplitudeAnalytic.Properties.COURSES_COUNT, coursesCount)) updateYandexUserProfile { apply(Attribute.customNumber(AmplitudeAnalytic.Properties.COURSES_COUNT).withValue(coursesCount.toDouble())) } setFirebaseUserProperty(AmplitudeAnalytic.Properties.COURSES_COUNT, coursesCount.toString()) } override fun setSubmissionsCount(submissionsCount: Long, delta: Long) { amplitude.identify(Identify().set(AmplitudeAnalytic.Properties.SUBMISSIONS_COUNT, submissionsCount + delta)) updateYandexUserProfile { apply(Attribute.customCounter(AmplitudeAnalytic.Properties.SUBMISSIONS_COUNT).withDelta(delta.toDouble())) } setFirebaseUserProperty(AmplitudeAnalytic.Properties.SUBMISSIONS_COUNT, (submissionsCount + delta).toString()) } override fun setScreenOrientation(orientation: Int) { val orientationName = if (orientation == Configuration.ORIENTATION_PORTRAIT) "portrait" else "landscape" amplitude.identify(Identify().set(AmplitudeAnalytic.Properties.SCREEN_ORIENTATION, orientationName)) updateYandexUserProfile { apply(Attribute.customString(AmplitudeAnalytic.Properties.SCREEN_ORIENTATION).withValue(orientationName)) } setFirebaseUserProperty(AmplitudeAnalytic.Properties.SCREEN_ORIENTATION, orientationName) } override fun setStreaksNotificationsEnabled(isEnabled: Boolean) { amplitude.identify(Identify().set(AmplitudeAnalytic.Properties.STREAKS_NOTIFICATIONS_ENABLED, if (isEnabled) "enabled" else "disabled")) updateYandexUserProfile { apply(Attribute.customBoolean(AmplitudeAnalytic.Properties.STREAKS_NOTIFICATIONS_ENABLED).withValue(isEnabled)) } setFirebaseUserProperty(AmplitudeAnalytic.Properties.STREAKS_NOTIFICATIONS_ENABLED, if (isEnabled) "enabled" else "disabled") } override fun setTeachingCoursesCount(coursesCount: Int) { amplitude.identify(Identify().set(AmplitudeAnalytic.Properties.TEACHING_COURSES_COUNT, coursesCount)) updateYandexUserProfile { apply(Attribute.customNumber(AmplitudeAnalytic.Properties.TEACHING_COURSES_COUNT).withValue(coursesCount.toDouble())) } setFirebaseUserProperty(AmplitudeAnalytic.Properties.TEACHING_COURSES_COUNT, coursesCount.toString()) } override fun setGoogleServicesAvailable(isAvailable: Boolean) { amplitude.identify(Identify().set(AmplitudeAnalytic.Properties.IS_GOOGLE_SERVICES_AVAILABLE, isAvailable.toString())) updateYandexUserProfile { apply(Attribute.customBoolean(AmplitudeAnalytic.Properties.IS_GOOGLE_SERVICES_AVAILABLE).withValue(isAvailable)) } setFirebaseUserProperty(AmplitudeAnalytic.Properties.IS_GOOGLE_SERVICES_AVAILABLE, isAvailable.toString()) } override fun report(analyticEvent: AnalyticEvent) { if (AnalyticSource.YANDEX in analyticEvent.sources) { YandexMetrica.reportEvent(analyticEvent.name, analyticEvent.params) } if (AnalyticSource.AMPLITUDE in analyticEvent.sources) { syncAmplitudeProperties() val properties = JSONObject() for ((k, v) in analyticEvent.params.entries) { properties.put(k, v) } amplitude.logEvent(analyticEvent.name, properties) firebaseCrashlytics.log("${analyticEvent.name}=${analyticEvent.params}") } if (AnalyticSource.FIREBASE in analyticEvent.sources) { val bundle = bundleOf(*analyticEvent.params.map { (a, b) -> a to b }.toTypedArray()) val firebaseEventName = castStringToFirebaseEvent(analyticEvent.name) firebaseAnalytics.logEvent(firebaseEventName, bundle) } if (AnalyticSource.STEPIK_API in analyticEvent.sources) { stepikAnalytic.logEvent(analyticEvent.name, analyticEvent.params) } } override fun reportUserProperty(userProperty: UserProperty) { if (UserPropertySource.YANDEX in userProperty.sources) { val userProfileUpdate = when (val value = userProperty.value) { is String -> Attribute.customString(userProperty.name).withValue(value) is Boolean -> Attribute.customBoolean(userProperty.name).withValue(value) is Number -> Attribute.customNumber(userProperty.name).withValue(value.toDouble()) else -> throw IllegalArgumentException("Invalid argument type") } updateYandexUserProfile { apply(userProfileUpdate) } } if (UserPropertySource.AMPLITUDE in userProperty.sources) { val identify = when (val value = userProperty.value) { is String -> Identify().set(userProperty.name, value) is Boolean -> Identify().set(userProperty.name, value) is Long -> Identify().set(userProperty.name, value) is Double -> Identify().set(userProperty.name, value) else -> throw IllegalArgumentException("Invalid argument type") } amplitude.identify(identify) } if (UserPropertySource.FIREBASE in userProperty.sources) { setFirebaseUserProperty(userProperty.name, userProperty.value.toString()) } } override fun reportAmplitudeEvent(eventName: String) = reportAmplitudeEvent(eventName, null) override fun reportAmplitudeEvent(eventName: String, params: Map<String, Any>?) { syncAmplitudeProperties() val properties = JSONObject() params?.let { for ((k, v) in it.entries) { properties.put(k, v) } } amplitude.logEvent(eventName, properties) YandexMetrica.reportEvent(eventName, params) firebaseCrashlytics.log("$eventName=$params") val bundle = bundleOf(*params?.map { (a, b) -> a to b }?.toTypedArray() ?: emptyArray()) val firebaseEventName = castStringToFirebaseEvent(eventName) firebaseAnalytics.logEvent(firebaseEventName, bundle) } override fun setUserProperty(name: String, value: String) { amplitude.identify(Identify().set(name, value)) updateYandexUserProfile { apply(Attribute.customString(name).withValue(value)) } firebaseCrashlytics.setCustomKey(name, value) setFirebaseUserProperty(name, value) } // End of amplitude properties override fun reportEventValue(eventName: String, value: Long) { val bundle = Bundle() bundle.putLong(FirebaseAnalytics.Param.VALUE, value) reportEvent(eventName, bundle) } override fun reportEvent(eventName: String, bundle: Bundle?) { val map: HashMap<String, String> = HashMap() bundle?.keySet()?.forEach { map[it] = java.lang.String.valueOf(bundle[it]) // handle null as bundle[it].toString() calls object.toString() and cause NPE instead of Any?.toString() } if (map.isEmpty()) { YandexMetrica.reportEvent(eventName) } else { YandexMetrica.reportEvent(eventName, map as Map<String, Any>?) } val eventNameLocal = castStringToFirebaseEvent(eventName) firebaseAnalytics.logEvent(eventNameLocal, bundle) } override fun reportEvent(eventName: String) { reportEvent(eventName, null) } override fun reportError(message: String, throwable: Throwable) { firebaseCrashlytics.recordException(throwable) YandexMetrica.reportError(message, throwable) } override fun reportEvent(eventName: String, id: String) { reportEventWithIdName(eventName, id, null) } override fun reportEventWithName(eventName: String, name: String?) { val bundle = Bundle() if (name != null) { bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name) } reportEvent(eventName, bundle) } override fun reportEventWithIdName(eventName: String, id: String, name: String?) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id) if (name != null) { bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name) } reportEvent(eventName, bundle) } private fun setFirebaseUserProperty(name: String, value: String) { firebaseAnalytics.setUserProperty(name.take(FIREBASE_USER_PROPERTY_NAME_LIMIT), value.take(FIREBASE_USER_PROPERTY_VALUE_LIMIT)) } private fun castStringToFirebaseEvent(eventName: String): String { val firebaseEventName = eventName .decapitalize(Locale.ENGLISH) .replace(' ', '_') return firebaseEventName.take(FIREBASE_LENGTH_LIMIT) } }
apache-2.0
1d85af8a38418c551541dd8636639212
45.123675
163
0.699456
4.758658
false
false
false
false
Unpublished/AmazeFileManager
app/src/main/java/com/amaze/filemanager/filesystem/FileProperties.kt
2
8700
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem import android.app.usage.StorageStatsManager import android.content.Context import android.net.Uri import android.os.Build import android.os.Build.VERSION_CODES.O import android.os.Environment import android.os.storage.StorageManager import android.provider.DocumentsContract import com.amaze.filemanager.application.AppConfig import com.amaze.filemanager.database.CloudHandler import com.amaze.filemanager.filesystem.DeleteOperation.deleteFile import com.amaze.filemanager.filesystem.ExternalSdCardOperation.isOnExtSdCard import com.amaze.filemanager.filesystem.smb.CifsContexts import com.amaze.filemanager.filesystem.ssh.SshConnectionPool import com.amaze.filemanager.utils.OTGUtil import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.util.regex.Pattern // TODO check if these can be done with just File methods // TODO make all of these methods File extensions object FileProperties { private const val STORAGE_PRIMARY = "primary" private const val COM_ANDROID_EXTERNALSTORAGE_DOCUMENTS = "com.android.externalstorage.documents" val EXCLUDED_DIRS = arrayOf( File(Environment.getExternalStorageDirectory(), "Android/data").absolutePath, File(Environment.getExternalStorageDirectory(), "Android/obb").absolutePath ) /** * Check if a file is readable. * * @param file The file * @return true if the file is reabable. */ @JvmStatic fun isReadable(file: File?): Boolean { if (file == null) return false if (!file.exists()) return false return try { file.canRead() } catch (e: SecurityException) { return false } } /** * Check if a file is writable. Detects write issues on external SD card. * * @param file The file * @return true if the file is writable. */ @JvmStatic fun isWritable(file: File?): Boolean { if (file == null) return false val isExisting = file.exists() try { val output = FileOutputStream(file, true) try { output.close() } catch (e: IOException) { e.printStackTrace() // do nothing. } } catch (e: FileNotFoundException) { e.printStackTrace() return false } val result = file.canWrite() // Ensure that file is not created during this process. if (!isExisting) { file.delete() } return result } /** * Check for a directory if it is possible to create files within this directory, either via * normal writing or via Storage Access Framework. * * @param folder The directory * @return true if it is possible to write in this directory. */ @JvmStatic fun isWritableNormalOrSaf(folder: File?, c: Context): Boolean { if (folder == null) { return false } // Verify that this is a directory. if (!folder.exists() || !folder.isDirectory) { return false } // Find a non-existing file in this directory. var i = 0 var file: File do { val fileName = "AugendiagnoseDummyFile" + ++i file = File(folder, fileName) } while (file.exists()) // First check regular writability if (isWritable(file)) { return true } // Next check SAF writability. val document = ExternalSdCardOperation.getDocumentFile(file, false, c) document ?: return false // This should have created the file - otherwise something is wrong with access URL. val result = document.canWrite() && file.exists() // Ensure that the dummy file is not remaining. deleteFile(file, c) return result } // Utility methods for Kitkat /** * Checks whether the target path exists or is writable * * @param f the target path * @return 1 if exists or writable, 0 if not writable */ @JvmStatic fun checkFolder(f: String?, context: Context): Int { if (f == null) return 0 if (f.startsWith(CifsContexts.SMB_URI_PREFIX) || f.startsWith(SshConnectionPool.SSH_URI_PREFIX) || f.startsWith(OTGUtil.PREFIX_OTG) || f.startsWith(CloudHandler.CLOUD_PREFIX_BOX) || f.startsWith(CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE) || f.startsWith(CloudHandler.CLOUD_PREFIX_DROPBOX) || f.startsWith(CloudHandler.CLOUD_PREFIX_ONE_DRIVE) || f.startsWith("content://") ) return 1 val folder = File(f) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && isOnExtSdCard(folder, context) ) { if (!folder.exists() || !folder.isDirectory) { return 0 } // On Android 5, trigger storage access framework. if (isWritableNormalOrSaf(folder, context)) { return 1 } } else return if (Build.VERSION.SDK_INT == 19 && isOnExtSdCard(folder, context) ) { // Assume that Kitkat workaround works 1 } else if (folder.canWrite()) { 1 } else { 0 } return 0 } /** * Validate given text is a valid filename. * * @param text * @return true if given text is a valid filename */ @JvmStatic fun isValidFilename(text: String): Boolean { val filenameRegex = Pattern.compile("[\\\\\\/:\\*\\?\"<>\\|\\x01-\\x1F\\x7F]", Pattern.CASE_INSENSITIVE) // It's not easy to use regex to detect single/double dot while leaving valid values // (filename.zip) behind... // So we simply use equality to check them return !filenameRegex.matcher(text).find() && "." != text && ".." != text } @JvmStatic fun unmapPathForApi30OrAbove(uriPath: String): String? { val uri = Uri.parse(uriPath) return uri.path?.let { p -> File( Environment.getExternalStorageDirectory(), p.substringAfter("tree/primary:") ).absolutePath } } @JvmStatic fun remapPathForApi30OrAbove(path: String, openDocumentTree: Boolean = false): String { return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q && EXCLUDED_DIRS.contains(path)) { val suffix = path.substringAfter(Environment.getExternalStorageDirectory().absolutePath) val documentId = "$STORAGE_PRIMARY:${suffix.substring(1)}" SafRootHolder.volumeLabel = STORAGE_PRIMARY if (openDocumentTree) { DocumentsContract.buildDocumentUri( COM_ANDROID_EXTERNALSTORAGE_DOCUMENTS, documentId ).toString() } else { DocumentsContract.buildTreeDocumentUri( COM_ANDROID_EXTERNALSTORAGE_DOCUMENTS, documentId ).toString() } } else { path } } @JvmStatic fun getDeviceStorageRemainingSpace(volume: String = STORAGE_PRIMARY): Long { return if (STORAGE_PRIMARY.equals(volume)) { if (Build.VERSION.SDK_INT < O) { Environment.getExternalStorageDirectory().freeSpace } else { AppConfig.getInstance().getSystemService(StorageStatsManager::class.java) .getFreeBytes(StorageManager.UUID_DEFAULT) } } else 0L } }
gpl-3.0
a8ed791234523aa621bab1a966a0a76b
33.251969
107
0.614253
4.588608
false
false
false
false
Maccimo/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/BuildContextImpl.kt
2
14920
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") package org.jetbrains.intellij.build.impl import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.Strings import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.jps.model.JpsModel import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes import org.jetbrains.jps.model.java.JavaResourceRootProperties import org.jetbrains.jps.model.java.JavaSourceRootProperties import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.util.JpsPathUtil import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.ConcurrentLinkedQueue class BuildContextImpl private constructor(private val compilationContext: CompilationContextImpl, override val productProperties: ProductProperties, override val windowsDistributionCustomizer: WindowsDistributionCustomizer?, override val linuxDistributionCustomizer: LinuxDistributionCustomizer?, override val macDistributionCustomizer: MacDistributionCustomizer?, override val proprietaryBuildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY, private val distFiles: ConcurrentLinkedQueue<Map.Entry<Path, String>>) : BuildContext { override val fullBuildNumber: String get() = "${applicationInfo.productCode}-$buildNumber" override val systemSelector: String get() = productProperties.getSystemSelector(applicationInfo, buildNumber) override val buildNumber: String = options.buildNumber ?: readSnapshotBuildNumber(paths.communityHomeDir) override val xBootClassPathJarNames: List<String> get() = productProperties.xBootClassPathJarNames override var bootClassPathJarNames = persistentListOf("util.jar", "util_rt.jar") override var classpathCustomizer: (MutableSet<String>) -> Unit = {} override val applicationInfo: ApplicationInfoProperties = ApplicationInfoPropertiesImpl(project, productProperties, options).patch(this) private var builtinModulesData: BuiltinModulesFileData? = null init { if (productProperties.productCode == null) { productProperties.productCode = applicationInfo.productCode } check(!systemSelector.contains(' ')) { "System selector must not contain spaces: $systemSelector" } options.buildStepsToSkip.addAll(productProperties.incompatibleBuildSteps) if (!options.buildStepsToSkip.isEmpty()) { Span.current().addEvent("build steps to be skipped", Attributes.of( AttributeKey.stringArrayKey("stepsToSkip"), options.buildStepsToSkip.toImmutableList() )) } configureProjectorPlugin(productProperties) } companion object { @JvmStatic @JvmOverloads fun createContext(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, productProperties: ProductProperties, proprietaryBuildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY, options: BuildOptions = BuildOptions()): BuildContextImpl { val projectHomeAsString = FileUtilRt.toSystemIndependentName(projectHome.toString()) val windowsDistributionCustomizer = productProperties.createWindowsCustomizer(projectHomeAsString) val linuxDistributionCustomizer = productProperties.createLinuxCustomizer(projectHomeAsString) val macDistributionCustomizer = productProperties.createMacCustomizer(projectHomeAsString) val compilationContext = CompilationContextImpl.create( communityHome = communityHome, projectHome = projectHome, buildOutputRootEvaluator = createBuildOutputRootEvaluator(projectHome, productProperties, options), options = options ) return BuildContextImpl(compilationContext = compilationContext, productProperties = productProperties, windowsDistributionCustomizer = windowsDistributionCustomizer, linuxDistributionCustomizer = linuxDistributionCustomizer, macDistributionCustomizer = macDistributionCustomizer, proprietaryBuildTools = proprietaryBuildTools, distFiles = ConcurrentLinkedQueue()) } } override var builtinModule: BuiltinModulesFileData? get() { if (options.buildStepsToSkip.contains(BuildOptions.PROVIDED_MODULES_LIST_STEP)) { return null } return builtinModulesData ?: throw IllegalStateException("builtinModulesData is not set. " + "Make sure `BuildTasksImpl.buildProvidedModuleList` was called before") } set(value) { check(builtinModulesData == null) { "builtinModulesData was already set" } builtinModulesData = value } override fun addDistFile(file: Map.Entry<Path, String>) { messages.debug("$file requested to be added to app resources") distFiles.add(file) } override fun getDistFiles(): Collection<Map.Entry<Path, String>> { return java.util.List.copyOf(distFiles) } override fun findApplicationInfoModule(): JpsModule { return findRequiredModule(productProperties.applicationInfoModule) } override val options: BuildOptions get() = compilationContext.options @Suppress("SSBasedInspection") override val messages: BuildMessages get() = compilationContext.messages override val dependenciesProperties: DependenciesProperties get() = compilationContext.dependenciesProperties override val paths: BuildPaths get() = compilationContext.paths override val bundledRuntime: BundledRuntime get() = compilationContext.bundledRuntime override val project: JpsProject get() = compilationContext.project override val projectModel: JpsModel get() = compilationContext.projectModel override val compilationData: JpsCompilationData get() = compilationContext.compilationData override val stableJavaExecutable: Path get() = compilationContext.stableJavaExecutable override val stableJdkHome: Path get() = compilationContext.stableJdkHome override val projectOutputDirectory: Path get() = compilationContext.projectOutputDirectory override fun findRequiredModule(name: String): JpsModule { return compilationContext.findRequiredModule(name) } override fun findModule(name: String): JpsModule? { return compilationContext.findModule(name) } override fun getOldModuleName(newName: String): String? { return compilationContext.getOldModuleName(newName) } override fun getModuleOutputDir(module: JpsModule): Path { return compilationContext.getModuleOutputDir(module) } override fun getModuleTestsOutputPath(module: JpsModule): String { return compilationContext.getModuleTestsOutputPath(module) } override fun getModuleRuntimeClasspath(module: JpsModule, forTests: Boolean): List<String> { return compilationContext.getModuleRuntimeClasspath(module, forTests) } override fun notifyArtifactBuilt(artifactPath: Path) { compilationContext.notifyArtifactWasBuilt(artifactPath) } override fun notifyArtifactWasBuilt(artifactPath: Path) { compilationContext.notifyArtifactWasBuilt(artifactPath) } override fun findFileInModuleSources(moduleName: String, relativePath: String): Path? { for (info in getSourceRootsWithPrefixes(findRequiredModule(moduleName))) { if (relativePath.startsWith(info.second)) { val result = info.first.resolve(Strings.trimStart(Strings.trimStart(relativePath, info.second), "/")) if (Files.exists(result)) { return result } } } return null } override fun signFiles(files: List<Path>, options: Map<String, String>) { if (proprietaryBuildTools.signTool == null) { Span.current().addEvent("files won't be signed", Attributes.of( AttributeKey.stringArrayKey("files"), files.map(Path::toString), AttributeKey.stringKey("reason"), "sign tool isn't defined") ) } else { proprietaryBuildTools.signTool.signFiles(files, this, options) } } override fun executeStep(stepMessage: String, stepId: String, step: Runnable): Boolean { if (options.buildStepsToSkip.contains(stepId)) { Span.current().addEvent("skip step", Attributes.of(AttributeKey.stringKey("name"), stepMessage)) } else { messages.block(stepMessage, step::run) } return true } override fun shouldBuildDistributions(): Boolean { return options.targetOs.lowercase() != BuildOptions.OS_NONE } override fun shouldBuildDistributionForOS(os: OsFamily, arch: JvmArchitecture): Boolean { return shouldBuildDistributions() && listOf(BuildOptions.OS_ALL, os.osId).contains(options.targetOs.lowercase()) && (options.targetArch == null || options.targetArch == arch) } override fun createCopyForProduct(productProperties: ProductProperties, projectHomeForCustomizers: Path): BuildContext { val projectHomeForCustomizersAsString = FileUtilRt.toSystemIndependentName(projectHomeForCustomizers.toString()) /** * FIXME compiled classes are assumed to be already fetched in the FIXME from [CompilationContextImpl.prepareForBuild], please change them together */ val options = BuildOptions() options.useCompiledClassesFromProjectOutput = true val compilationContextCopy = compilationContext.createCopy( messages = messages, options = options, buildOutputRootEvaluator = createBuildOutputRootEvaluator(paths.projectHome, productProperties, options) ) val copy = BuildContextImpl( compilationContext = compilationContextCopy, productProperties = productProperties, windowsDistributionCustomizer = productProperties.createWindowsCustomizer(projectHomeForCustomizersAsString), linuxDistributionCustomizer = productProperties.createLinuxCustomizer(projectHomeForCustomizersAsString), macDistributionCustomizer = productProperties.createMacCustomizer(projectHomeForCustomizersAsString), proprietaryBuildTools = proprietaryBuildTools, distFiles = ConcurrentLinkedQueue() ) copy.paths.artifactDir = paths.artifactDir.resolve(productProperties.productCode!!) copy.paths.artifacts = "${paths.artifacts}/${productProperties.productCode}" copy.compilationContext.prepareForBuild() return copy } override fun includeBreakGenLibraries() = isJavaSupportedInProduct private val isJavaSupportedInProduct: Boolean get() = productProperties.productLayout.bundledPluginModules.contains("intellij.java.plugin") override fun patchInspectScript(path: Path) { //todo[nik] use placeholder in inspect.sh/inspect.bat file instead Files.writeString(path, Files.readString(path).replace(" inspect ", " ${productProperties.inspectCommandName} ")) } override fun getAdditionalJvmArguments(os: OsFamily): List<String> { val jvmArgs: MutableList<String> = ArrayList() val classLoader = productProperties.classLoader if (classLoader != null) { jvmArgs.add("-Djava.system.class.loader=$classLoader") if (classLoader == "com.intellij.util.lang.PathClassLoader") { jvmArgs.add("-Didea.strict.classpath=true") } } jvmArgs.add("-Didea.vendor.name=" + applicationInfo.shortCompanyName) jvmArgs.add("-Didea.paths.selector=$systemSelector") if (productProperties.platformPrefix != null) { jvmArgs.add("-Didea.platform.prefix=${productProperties.platformPrefix}") } jvmArgs.addAll(productProperties.additionalIdeJvmArguments) if (productProperties.toolsJarRequired) { jvmArgs.add("-Didea.jre.check=true") } if (productProperties.useSplash) { @Suppress("SpellCheckingInspection") jvmArgs.add("-Dsplash=true") } jvmArgs.addAll(getCommandLineArgumentsForOpenPackages(this, os)) return jvmArgs } } private fun createBuildOutputRootEvaluator(projectHome: Path, productProperties: ProductProperties, buildOptions: BuildOptions): (JpsProject) -> Path { return { project -> val appInfo = ApplicationInfoPropertiesImpl(project = project, productProperties = productProperties, buildOptions = buildOptions) projectHome.resolve("out/${productProperties.getOutputDirectoryName(appInfo)}") } } private fun getSourceRootsWithPrefixes(module: JpsModule): Sequence<Pair<Path, String>> { return module.sourceRoots.asSequence() .filter { root: JpsModuleSourceRoot -> JavaModuleSourceRootTypes.PRODUCTION.contains(root.rootType) } .map { moduleSourceRoot: JpsModuleSourceRoot -> var prefix: String val properties = moduleSourceRoot.properties prefix = if (properties is JavaSourceRootProperties) { properties.packagePrefix.replace(".", "/") } else { (properties as JavaResourceRootProperties).relativeOutputPath } if (!prefix.endsWith("/")) { prefix += "/" } Pair(Path.of(JpsPathUtil.urlToPath(moduleSourceRoot.url)), prefix.trimStart('/')) } } private const val projectorPlugin = "intellij.cwm.plugin.projector" private const val projectorJar = "plugins/cwm-plugin-projector/lib/projector/projector.jar" private fun configureProjectorPlugin(properties: ProductProperties) { // configure only if versionCheckerConfig is not empty - // otherwise will be an error because versionCheckerConfig expected to contain a default version (e.g. "" to "11") if (properties.versionCheckerConfig.isNotEmpty() && properties.productLayout.bundledPluginModules.contains(projectorPlugin) && !properties.versionCheckerConfig.containsKey(projectorJar)) { properties.versionCheckerConfig = properties.versionCheckerConfig.put(projectorJar, "17") } } private fun readSnapshotBuildNumber(communityHome: BuildDependenciesCommunityRoot): String { return Files.readString(communityHome.communityRoot.resolve("build.txt")).trim { it <= ' ' } }
apache-2.0
783804d5f4ca37c38091ecd5131d24f4
43.537313
151
0.729759
5.611132
false
false
false
false
nitiwari-dev/android-percent-layout-sample
app/src/main/java/com/coderconsole/percent_layout_sample/MainActivity.kt
1
2257
/* * Copyright (C) 2018 Nitesh Tiwari. * * 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.coderconsole.percent_layout_sample import android.app.Activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.OrientationHelper import android.view.LayoutInflater import com.coderconsole.percent_layout_sample.adapter.PercentAdapter import com.coderconsole.percent_layout_sample.databinding.ActivityMainBinding import com.coderconsole.percent_layout_sample.model.PercentModel class MainActivity : AppCompatActivity() { private lateinit var mMainActivityMainBinding: ActivityMainBinding val percentArray = arrayOf("20-50", "50-50", "50-100", "Tile 1", "Tile 2", "Chaining and Ratios", "Backgrounds") var mPercentList = arrayListOf<PercentModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mMainActivityMainBinding = ActivityMainBinding.inflate(LayoutInflater.from(this)) setContentView(mMainActivityMainBinding.root) init() } private fun init() { val percentRecyclerView = mMainActivityMainBinding.percentList percentRecyclerView.setHasFixedSize(true) val linearLayoutManager = LinearLayoutManager(this, OrientationHelper.VERTICAL, false) percentRecyclerView.layoutManager = linearLayoutManager fillList() val percentAdapter = PercentAdapter(this, mPercentList) percentRecyclerView.adapter = percentAdapter } private fun fillList(){ for (percent in percentArray) { mPercentList.add(PercentModel(percent)) } } }
apache-2.0
6d601f259d4183c24a3764b695d9b6c0
33.19697
116
0.746566
4.541247
false
false
false
false
JStege1206/AdventOfCode
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day12.kt
1
920
package nl.jstege.adventofcode.aoc2015.days import com.fasterxml.jackson.databind.JsonNode import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.head import nl.jstege.adventofcode.aoccommon.utils.extensions.toJson /** * * @author Jelle Stege */ class Day12 : Day(title = "JSAbacusFramework.io") { override fun first(input: Sequence<String>): Any = input.head.toJson().sum() override fun second(input: Sequence<String>): Any = input.head.toJson().sumWithoutRed() private fun JsonNode.sum(): Int { if (this.isInt) return this.asInt() return this.sumBy { it.sum() } } private fun JsonNode.sumWithoutRed(): Int { if (this.isInt) return this.asInt() if (this.any { it.isTextual && it.asText() == "red" && this.isObject }) { return 0 } return this.sumBy { it.sumWithoutRed() } } }
mit
965a40a5901ffe88d8bb4ba74e7b22fa
29.666667
91
0.670652
3.709677
false
false
false
false
jacobwu/pcrek
spring-fx/src/main/kotlin/io/whatthedill/spring/fx/ApplicationContextFxmlLoader.kt
1
1245
package io.whatthedill.spring.fx import javafx.fxml.FXMLLoader import javafx.scene.Parent import org.slf4j.LoggerFactory import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.core.io.Resource class ApplicationContextFxmlLoader : SpringFxmlLoader, ApplicationContextAware { override fun setApplicationContext(applicationContext: ApplicationContext?) { this.applicationContext = applicationContext } private var applicationContext: ApplicationContext? = null override fun load(resource: Resource): Parent { LOGGER.debug("Loading fxml: [{}]", resource) resource.inputStream.use { fxmlStream -> val loader = FXMLLoader() loader.setControllerFactory { clazz -> LOGGER.debug("Getting bean of type [{}]", clazz) val bean = applicationContext!!.getBean(clazz) LOGGER.trace("Found bean [{}] as the type [{}]", bean, clazz) bean } return loader.load<Parent>(fxmlStream) } } companion object { private val LOGGER = LoggerFactory.getLogger(ApplicationContextFxmlLoader::class.java) } }
mit
f19b0c7e4dbdfbc1afd7d4bbe46b3c73
35.617647
94
0.689157
5.165975
false
false
false
false
ingokegel/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/CompilationContextImpl.kt
1
20520
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package org.jetbrains.intellij.build.impl import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.io.NioFiles import com.intellij.util.PathUtilRt import com.intellij.util.SystemProperties import com.intellij.util.xml.dom.readXmlAsModel import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.ConsoleSpanExporter.Companion.setPathRoot import org.jetbrains.intellij.build.TracerProviderManager.flush import org.jetbrains.intellij.build.TracerProviderManager.setOutput import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.dependencies.BuildDependenciesDownloader import org.jetbrains.intellij.build.dependencies.DependenciesProperties import org.jetbrains.intellij.build.dependencies.JdkDownloader import org.jetbrains.intellij.build.impl.JdkUtils.defineJdk import org.jetbrains.intellij.build.impl.JdkUtils.readModulesFromReleaseFile import org.jetbrains.intellij.build.impl.logging.BuildMessagesHandler import org.jetbrains.intellij.build.impl.logging.BuildMessagesImpl import org.jetbrains.intellij.build.kotlin.KotlinBinaries import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.JpsGlobal import org.jetbrains.jps.model.JpsModel import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.artifact.JpsArtifact import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.java.JpsJavaSdkType import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsProjectLoader import org.jetbrains.jps.util.JpsPathUtil import java.io.File import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.exists @JvmOverloads fun createCompilationContext(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, defaultOutputRoot: Path, options: BuildOptions = BuildOptions()): CompilationContextImpl { return CompilationContextImpl.create(communityHome = communityHome, projectHome = projectHome, buildOutputRootEvaluator = { defaultOutputRoot }, options = options) } class CompilationContextImpl private constructor(model: JpsModel, communityHome: BuildDependenciesCommunityRoot, projectHome: Path, override val messages: BuildMessages, private val oldToNewModuleName: Map<String, String>, buildOutputRootEvaluator: (JpsProject) -> Path, override val options: BuildOptions) : CompilationContext { fun createCopy(messages: BuildMessages, options: BuildOptions, buildOutputRootEvaluator: (JpsProject) -> Path): CompilationContextImpl { val copy = CompilationContextImpl(model = projectModel, communityHome = paths.communityHomeDir, projectHome = paths.projectHome, messages = messages, oldToNewModuleName = oldToNewModuleName, buildOutputRootEvaluator = buildOutputRootEvaluator, options = options) copy.compilationData = compilationData return copy } fun prepareForBuild() { checkCompilationOptions() NioFiles.deleteRecursively(paths.logDir) Files.createDirectories(paths.logDir) compilationData = JpsCompilationData( dataStorageRoot = paths.buildOutputDir.resolve(".jps-build-data"), buildLogFile = paths.logDir.resolve("compilation.log"), categoriesWithDebugLevelNullable = System.getProperty("intellij.build.debug.logging.categories", "") ) val projectArtifactsDirName = "project-artifacts" overrideProjectOutputDirectory() val baseArtifactsOutput = "${paths.buildOutputRoot}/$projectArtifactsDirName" JpsArtifactService.getInstance().getArtifacts(project).forEach { setOutputPath(it, "$baseArtifactsOutput/${PathUtilRt.getFileName(it.outputPath)}") } if (!options.useCompiledClassesFromProjectOutput) { messages.info("Incremental compilation: ${options.incrementalCompilation}") } suppressWarnings(project) flush() setPathRoot(paths.buildOutputDir) /** * FIXME should be called lazily, yet it breaks [TestingTasks.runTests], needs investigation */ CompilationTasks.create(this).reuseCompiledClassesIfProvided() } private fun overrideProjectOutputDirectory() { if (options.projectClassesOutputDirectory != null && !options.projectClassesOutputDirectory.isNullOrEmpty()) { setProjectOutputDirectory0(this, options.projectClassesOutputDirectory!!) } else if (options.useCompiledClassesFromProjectOutput) { val outputDir = projectOutputDirectory if (!outputDir.exists()) { throw RuntimeException("${BuildOptions.USE_COMPILED_CLASSES_PROPERTY} is enabled," + " but the project output directory $outputDir doesn\'t exist") } } else { setProjectOutputDirectory0(this, "${paths.buildOutputRoot}/classes") } } override val projectOutputDirectory: Path get() = JpsPathUtil.urlToFile(JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(project).outputUrl).toPath() fun setProjectOutputDirectory(outputDirectory: String) { val url = "file://${FileUtilRt.toSystemIndependentName(outputDirectory)}" JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(project).outputUrl = url } private fun checkCompilationOptions() { if (options.useCompiledClassesFromProjectOutput && options.incrementalCompilation) { messages.warning( "\'" + BuildOptions.USE_COMPILED_CLASSES_PROPERTY + "\' is specified, so \'incremental compilation\' option will be ignored") options.incrementalCompilation = false } if (options.pathToCompiledClassesArchive != null && options.incrementalCompilation) { messages.warning("Paths to the compiled project output is specified, so 'incremental compilation' option will be ignored") options.incrementalCompilation = false } if (options.pathToCompiledClassesArchive != null && options.useCompiledClassesFromProjectOutput) { messages.warning( "\'" + BuildOptions.USE_COMPILED_CLASSES_PROPERTY + "\' is specified, so the archive with compiled project output won\'t be used") options.pathToCompiledClassesArchive = null } if (options.pathToCompiledClassesArchivesMetadata != null && options.incrementalCompilation) { messages.warning("Paths to the compiled project output metadata is specified, so 'incremental compilation' option will be ignored") options.incrementalCompilation = false } if (options.pathToCompiledClassesArchivesMetadata != null && options.useCompiledClassesFromProjectOutput) { messages.warning("\'" + BuildOptions.USE_COMPILED_CLASSES_PROPERTY + "\' is specified, so the archive with the compiled project output metadata won\'t be used to fetch compile output") options.pathToCompiledClassesArchivesMetadata = null } } override fun findRequiredModule(name: String): JpsModule { val module = findModule(name) check(module != null) { "Cannot find required module \'$name\' in the project" } return module } override fun findModule(name: String): JpsModule? { val actualName: String? if (oldToNewModuleName.containsKey(name)) { actualName = oldToNewModuleName[name] messages.warning("Old module name \'$name\' is used in the build scripts; use the new name \'$actualName\' instead") } else { actualName = name } return nameToModule.get(actualName) } override fun getOldModuleName(newName: String) = newToOldModuleName.get(newName) override fun getModuleOutputDir(module: JpsModule): Path { val url = JpsJavaExtensionService.getInstance().getOutputUrl(module, false) check(url != null) { "Output directory for ${module.name} isn\'t set" } return Path.of(JpsPathUtil.urlToPath(url)) } override fun getModuleTestsOutputPath(module: JpsModule): String { val outputDirectory = JpsJavaExtensionService.getInstance().getOutputDirectory(module, true) check(outputDirectory != null) { "Output directory for ${module.name} isn\'t set" } return outputDirectory.absolutePath } override fun getModuleRuntimeClasspath(module: JpsModule, forTests: Boolean): List<String> { val enumerator = JpsJavaExtensionService.dependencies(module).recursively() // if project requires different SDKs they all shouldn't be added to test classpath .also { if (forTests) it.withoutSdk() } .includedIn(JpsJavaClasspathKind.runtime(forTests)) return enumerator.classes().roots.map { it.absolutePath } } override fun notifyArtifactWasBuilt(artifactPath: Path) { if (options.buildStepsToSkip.contains(BuildOptions.TEAMCITY_ARTIFACTS_PUBLICATION_STEP)) { return } val isRegularFile = Files.isRegularFile(artifactPath) var targetDirectoryPath = "" if (artifactPath.parent.startsWith(paths.artifactDir)) { targetDirectoryPath = FileUtilRt.toSystemIndependentName(paths.artifactDir.relativize(artifactPath.parent).toString()) } if (!isRegularFile) { targetDirectoryPath = (if (!targetDirectoryPath.isEmpty()) "$targetDirectoryPath/" else "") + artifactPath.fileName } var pathToReport = artifactPath.toString() if (targetDirectoryPath.isNotEmpty()) { pathToReport += "=>$targetDirectoryPath" } messages.artifactBuilt(pathToReport) } override val paths: BuildPaths override val project: JpsProject val global: JpsGlobal override val projectModel: JpsModel = model private val newToOldModuleName: Map<String, String> private val nameToModule: Map<String?, JpsModule> override val dependenciesProperties: DependenciesProperties override val bundledRuntime: BundledRuntime override lateinit var compilationData: JpsCompilationData override val stableJavaExecutable: Path override val stableJdkHome: Path companion object { private fun printEnvironmentDebugInfo() { // print it to the stdout since TeamCity will remove any sensitive fields from build log automatically // don't write it to debug log file! val env = System.getenv() for (key in env.keys.sorted()) { println("ENV $key = ${env[key]}") } val properties = System.getProperties() for (propertyName in properties.keys.sortedBy { it as String }) { println("PROPERTY $propertyName = ${properties[propertyName].toString()}") } } internal fun create(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, buildOutputRootEvaluator: (JpsProject) -> Path, options: BuildOptions = BuildOptions()): CompilationContextImpl { // This is not a proper place to initialize tracker for downloader // but this is the only place which is called in most build scripts BuildDependenciesDownloader.TRACER = BuildDependenciesOpenTelemetryTracer.INSTANCE val messages = BuildMessagesImpl.create() if (sequenceOf("platform/build-scripts", "bin/idea.properties", "build.txt").any { !Files.exists(communityHome.communityRoot.resolve(it)) }) { messages.error("communityHome ($communityHome) doesn\'t point to a directory containing IntelliJ Community sources") } if (options.printEnvironmentInfo) { messages.block("Environment info") { messages.info("Community home: ${communityHome.communityRoot}") messages.info("Project home: $projectHome") printEnvironmentDebugInfo() } } logFreeDiskSpace(dir = projectHome, phase = "before downloading dependencies") val kotlinBinaries = KotlinBinaries(communityHome, options, messages) val model = loadProject(projectHome, kotlinBinaries) val oldToNewModuleName = loadModuleRenamingHistory(projectHome, messages) + loadModuleRenamingHistory(communityHome.communityRoot, messages) val context = CompilationContextImpl(model = model, communityHome = communityHome, projectHome = projectHome, messages = messages, oldToNewModuleName = oldToNewModuleName, buildOutputRootEvaluator = buildOutputRootEvaluator, options = options) defineJavaSdk(context) messages.block("Preparing for build") { context.prepareForBuild() } // not as part of prepareForBuild because prepareForBuild may be called several times per each product or another flavor // (see createCopyForProduct) setOutput(context.paths.logDir.resolve("trace.json")) messages.setDebugLogPath(context.paths.logDir.resolve("debug.log")) // This is not a proper place to initialize logging // but this is the only place which is called in most build scripts BuildMessagesHandler.initLogging(messages) return context } } init { project = model.project global = model.global newToOldModuleName = oldToNewModuleName.entries.associate { it.value to it.key } val modules = model.project.modules this.nameToModule = modules.associateBy { it.name } val buildOut = options.outputRootPath?.let { Path.of(it) } ?: buildOutputRootEvaluator(project) val logDir = options.logPath?.let { Path.of(it).toAbsolutePath().normalize() } ?: buildOut.resolve("log") paths = BuildPathsImpl(communityHome, projectHome, buildOut, logDir) val projectDependenciesProperties = paths.projectHome.resolve("build/dependencies.properties") dependenciesProperties = if (Files.exists(projectDependenciesProperties)) { DependenciesProperties(paths.communityHomeDir, projectDependenciesProperties) } else { DependenciesProperties(paths.communityHomeDir) } bundledRuntime = BundledRuntimeImpl(options, paths, dependenciesProperties, messages::error, messages::info) stableJdkHome = JdkDownloader.getJdkHome(paths.communityHomeDir) stableJavaExecutable = JdkDownloader.getJavaExecutable(stableJdkHome) } } private fun loadProject(projectHome: Path, kotlinBinaries: KotlinBinaries): JpsModel { val model = JpsElementFactory.getInstance().createModel() val pathVariablesConfiguration = JpsModelSerializationDataService.getOrCreatePathVariablesConfiguration(model.global) if (kotlinBinaries.isCompilerRequired) { kotlinBinaries.loadKotlinJpsPluginToClassPath() val kotlinCompilerHome = kotlinBinaries.kotlinCompilerHome System.setProperty("jps.kotlin.home", kotlinCompilerHome.toFile().absolutePath) pathVariablesConfiguration.addPathVariable("KOTLIN_BUNDLED", kotlinCompilerHome.toString()) } pathVariablesConfiguration.addPathVariable("MAVEN_REPOSITORY", FileUtilRt.toSystemIndependentName( File(SystemProperties.getUserHome(), ".m2/repository").absolutePath)) val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) JpsProjectLoader.loadProject(model.project, pathVariables, projectHome) Span.current().addEvent("project loaded", Attributes.of( AttributeKey.stringKey("project"), projectHome.toString(), AttributeKey.longKey("moduleCount"), model.project.modules.size.toLong(), AttributeKey.longKey("libraryCount"), model.project.libraryCollection.libraries.size.toLong(), )) return model as JpsModel } private fun suppressWarnings(project: JpsProject) { val compilerOptions = JpsJavaExtensionService.getInstance().getCompilerConfiguration(project).currentCompilerOptions compilerOptions.GENERATE_NO_WARNINGS = true compilerOptions.DEPRECATION = false @Suppress("SpellCheckingInspection") compilerOptions.ADDITIONAL_OPTIONS_STRING = compilerOptions.ADDITIONAL_OPTIONS_STRING.replace("-Xlint:unchecked", "") } private fun toCanonicalPath(path: String): String { return FileUtilRt.toSystemIndependentName(File(path).canonicalPath) } private fun <Value : String?> setOutputPath(propOwner: JpsArtifact, outputPath: Value): Value { propOwner.outputPath = outputPath return outputPath } private fun setProjectOutputDirectory0(propOwner: CompilationContextImpl, outputDirectory: String): String { propOwner.setProjectOutputDirectory(outputDirectory) return outputDirectory } private class BuildPathsImpl(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, buildOut: Path, logDir: Path) : BuildPaths(communityHomeDir = communityHome, buildOutputDir = buildOut, logDir = logDir, projectHome = projectHome) { init { artifactDir = buildOutputDir.resolve("artifacts") artifacts = FileUtilRt.toSystemIndependentName(artifactDir.toString()) } } private fun defineJavaSdk(context: CompilationContext) { val homePath = JdkDownloader.getJdkHome(context.paths.communityHomeDir) val jbrHome = toCanonicalPath(homePath.toString()) val jbrVersionName = "11" defineJdk(context.projectModel.global, jbrVersionName, jbrHome, context.messages) readModulesFromReleaseFile(context.projectModel, jbrVersionName, jbrHome) // Validate all modules have proper SDK reference context.projectModel.project.modules .asSequence() .forEach { module -> val sdkName = module.getSdkReference(JpsJavaSdkType.INSTANCE)?.sdkName ?: return@forEach val vendorPrefixEnd = sdkName.indexOf('-') val sdkNameWithoutVendor = if (vendorPrefixEnd == -1) sdkName else sdkName.substring(vendorPrefixEnd + 1) check(sdkNameWithoutVendor == "17") { "Project model at ${context.paths.projectHome} [module ${module.name}] requested SDK $sdkNameWithoutVendor, " + "but only '17' is supported as SDK in intellij project" } } context.projectModel.project.modules .asSequence() .mapNotNull { it.getSdkReference(JpsJavaSdkType.INSTANCE)?.sdkName } .distinct() .forEach { sdkName -> if (context.projectModel.global.libraryCollection.findLibrary(sdkName) == null) { defineJdk(context.projectModel.global, sdkName, jbrHome, context.messages) readModulesFromReleaseFile(context.projectModel, sdkName, jbrHome) } } } private fun readModulesFromReleaseFile(model: JpsModel, sdkName: String, sdkHome: String) { val additionalSdk = model.global.libraryCollection.findLibrary(sdkName) ?: throw IllegalStateException("Sdk '$sdkName' is not found") val urls = additionalSdk.getRoots(JpsOrderRootType.COMPILED).map { it.url } for (it in readModulesFromReleaseFile(Path.of(sdkHome))) { if (!urls.contains(it)) { additionalSdk.addRoot(it, JpsOrderRootType.COMPILED) } } } private fun loadModuleRenamingHistory(projectHome: Path, messages: BuildMessages): Map<String, String> { val modulesXml = projectHome.resolve(".idea/modules.xml") check(Files.exists(modulesXml)) { "Incorrect project home: $modulesXml doesn\'t exist" } return Files.newInputStream(modulesXml).use { readXmlAsModel(it) }.children("component") .find { it.getAttributeValue("name") == "ModuleRenamingHistory" } ?.children("module") ?.associate { it.getAttributeValue("old-name")!! to it.getAttributeValue("new-name")!! } ?: emptyMap() }
apache-2.0
4ee0b62d34451cf94db9f40ac7039248
47.284706
148
0.719786
5.229358
false
false
false
false
omegasoft7/KAndroid
kandroid/src/main/java/com/pawegio/kandroid/KContext.kt
1
7956
package com.pawegio.kandroid import android.accounts.AccountManager import android.app.* import android.app.admin.DevicePolicyManager import android.app.job.JobScheduler import android.appwidget.AppWidgetManager import android.bluetooth.BluetoothManager import android.content.ClipboardManager import android.content.Context import android.content.RestrictionsManager import android.content.SharedPreferences import android.content.pm.LauncherApps import android.hardware.ConsumerIrManager import android.hardware.SensorManager import android.hardware.camera2.CameraManager import android.hardware.display.DisplayManager import android.hardware.input.InputManager import android.hardware.usb.UsbManager import android.location.LocationManager import android.media.AudioManager import android.media.MediaRouter import android.media.projection.MediaProjectionManager import android.media.session.MediaSessionManager import android.media.tv.TvInputManager import android.net.ConnectivityManager import android.net.nsd.NsdManager import android.net.wifi.WifiManager import android.net.wifi.p2p.WifiP2pManager import android.nfc.NfcManager import android.os.* import android.os.storage.StorageManager import android.preference.PreferenceManager import android.print.PrintManager import android.telecom.TelecomManager import android.telephony.TelephonyManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.view.accessibility.AccessibilityManager import android.view.accessibility.CaptioningManager import android.view.inputmethod.InputMethodManager import android.view.textservice.TextServicesManager /** * @author pawegio */ public fun Context.inflateLayout(layoutResId: Int, parent: ViewGroup? = null, attachToRoot: Boolean = false): View = LayoutInflater.from(this).inflate(layoutResId, parent, attachToRoot) public fun Context.getAccessibilityManager(): AccessibilityManager = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager public fun Context.getAccountManager(): AccountManager = getSystemService(Context.ACCOUNT_SERVICE) as AccountManager public fun Context.getActivityManager(): ActivityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager public fun Context.getAlarmManager(): AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager public fun Context.getAppWidgetManager(): AppWidgetManager = getSystemService(Context.APPWIDGET_SERVICE) as AppWidgetManager public fun Context.getAppOpsManager(): AppOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager public fun Context.getAudioManager(): AudioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager public fun Context.getBatteryManager(): BatteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager public fun Context.getBluetoothManager(): BluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager public fun Context.getCameraManager(): CameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager public fun Context.getCaptioningManager(): CaptioningManager = getSystemService(Context.CAPTIONING_SERVICE) as CaptioningManager public fun Context.getClipboardManager(): ClipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager public fun Context.getConnectivityManager(): ConnectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager public fun Context.getConsumerIrManager(): ConsumerIrManager = getSystemService(Context.CONSUMER_IR_SERVICE) as ConsumerIrManager public fun Context.getDevicePolicyManager(): DevicePolicyManager = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager public fun Context.getDisplayManager(): DisplayManager = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager public fun Context.getDownloadManager(): DownloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager public fun Context.getDropBoxManager(): DropBoxManager = getSystemService(Context.DROPBOX_SERVICE) as DropBoxManager public fun Context.getInputMethodManager(): InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager public fun Context.getInputManager(): InputManager = getSystemService(Context.INPUT_SERVICE) as InputManager public fun Context.getJobScheduler(): JobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler public fun Context.getKeyguardManager(): KeyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager public fun Context.getLauncherApps(): LauncherApps = getSystemService(Context.LAUNCHER_APPS_SERVICE) as LauncherApps public fun Context.getLayoutInflater(): LayoutInflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater public fun Context.getLocationManager(): LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager public fun Context.getMediaProjectionManager(): MediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager public fun Context.getMediaRouter(): MediaRouter = getSystemService(Context.MEDIA_ROUTER_SERVICE) as MediaRouter public fun Context.getMediaSessionManager(): MediaSessionManager = getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager public fun Context.getNfcManager(): NfcManager = getSystemService(Context.NFC_SERVICE) as NfcManager public fun Context.getNotificationManager(): NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager public fun Context.getNsdManager(): NsdManager = getSystemService(Context.NSD_SERVICE) as NsdManager public fun Context.getPowerManager(): PowerManager = getSystemService(Context.POWER_SERVICE) as PowerManager public fun Context.getPrintManager(): PrintManager = getSystemService(Context.PRINT_SERVICE) as PrintManager public fun Context.getRestrictionsManager(): RestrictionsManager = getSystemService(Context.RESTRICTIONS_SERVICE) as RestrictionsManager public fun Context.getSearchManager(): SearchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager public fun Context.getSensorManager(): SensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager public fun Context.getStorageManager(): StorageManager = getSystemService(Context.STORAGE_SERVICE) as StorageManager public fun Context.getTelecomManager(): TelecomManager = getSystemService(Context.TELECOM_SERVICE) as TelecomManager public fun Context.getTelephonyManager(): TelephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager public fun Context.getTextServicesManager(): TextServicesManager = getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE) as TextServicesManager public fun Context.getTvInputManager(): TvInputManager = getSystemService(Context.TV_INPUT_SERVICE) as TvInputManager public fun Context.getUiModeManager(): UiModeManager = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager public fun Context.getUsbManager(): UsbManager = getSystemService(Context.USB_SERVICE) as UsbManager public fun Context.getUserManager(): UserManager = getSystemService(Context.USER_SERVICE) as UserManager public fun Context.getVibrator(): Vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator public fun Context.getWallpaperManager(): WallpaperManager = getSystemService(Context.WALLPAPER_SERVICE) as WallpaperManager public fun Context.getWifiP2pManager(): WifiP2pManager = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager public fun Context.getWifiManager(): WifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager public fun Context.getWindowManager(): WindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager public fun Context.getDefaultSharedPreferences(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
apache-2.0
bb2479ebb7b935eb46b1eadd7f86f2cd
52.046667
149
0.853444
5.336016
false
false
false
false