repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Zeyad-37/RxRedux
core/src/main/java/com/zeyad/rxredux/core/view/IBaseActivity.kt
1
785
package com.zeyad.rxredux.core.view import android.os.Bundle import android.os.Parcelable import com.zeyad.rxredux.core.viewmodel.IBaseViewModel interface IBaseActivity<I, R, S : Parcelable, E, VM : IBaseViewModel<I, R, S, E>> : BaseView<I, R, S, E, VM> { fun onCreateImpl(savedInstanceState: Bundle?) { getViewStateFrom<S>(savedInstanceState)?.let { viewState = it } initViewState(savedInstanceState) initialize() setupUI(savedInstanceState == null) activate() } fun onRestoreInstanceStateImpl(savedInstanceState: Bundle) = getViewStateFrom<S>(savedInstanceState)?.let { viewState = it } /** * Setup the UI. * * @param isNew = savedInstanceState == null */ fun setupUI(isNew: Boolean) }
apache-2.0
37b2c3526d3e868df59341fa9de7d357
29.192308
110
0.670064
4.243243
false
false
false
false
akhbulatov/wordkeeper
app/src/main/java/com/akhbulatov/wordkeeper/data/word/WordRepositoryImpl.kt
1
1846
package com.akhbulatov.wordkeeper.data.word import com.akhbulatov.wordkeeper.data.global.local.database.word.WordDao import com.akhbulatov.wordkeeper.data.global.local.preferences.word.WordPreferences import com.akhbulatov.wordkeeper.domain.global.models.Word import com.akhbulatov.wordkeeper.domain.global.repositories.WordRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class WordRepositoryImpl @Inject constructor( private val wordDao: WordDao, private val wordPreferences: WordPreferences, private val wordDatabaseMapper: WordDatabaseMapper ) : WordRepository { override fun getWords(): Flow<List<Word>> { val wordSortMode = wordPreferences.wordSortMode return when (wordSortMode) { Word.SortMode.NAME -> wordDao.getAllWordsSortedByName() Word.SortMode.LAST_MODIFIED -> wordDao.getAllWordsSortedByDescDatetime() } .map { it.map { word -> wordDatabaseMapper.mapFrom(word) } } } override fun getWordsByCategory(category: String): Flow<List<Word>> = wordDao.getWordsByCategory(category) .map { it.map { word -> wordDatabaseMapper.mapFrom(word) } } override suspend fun addWord(word: Word) { val dbModel = wordDatabaseMapper.mapTo(word) wordDao.insetWord(dbModel) } override suspend fun editWord(word: Word) { val dbModel = wordDatabaseMapper.mapTo(word) wordDao.updateWord(dbModel) } override suspend fun deleteWords(words: List<Word>) { val dbModels = words.map { wordDatabaseMapper.mapTo(it) } wordDao.deleteWords(dbModels) } override var wordSortMode: Word.SortMode get() = wordPreferences.wordSortMode set(value) { wordPreferences.wordSortMode = value } }
apache-2.0
55684d2100827c1062ec23dee351b660
35.92
84
0.714518
4.4375
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/App.kt
2
2048
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.causeway.client.kroviz import io.kvision.* import io.kvision.pace.Pace import io.kvision.panel.VPanel import io.kvision.panel.root import org.apache.causeway.client.kroviz.ui.core.RoApp import org.apache.causeway.client.kroviz.ui.core.ViewManager class App : Application() { private val appName = "kroviz" var roApp : RoApp? = null init { Pace.init() require("css/$appName.css") initRoApp() } override fun start() { val r = root(appName, addRow = true) val v = VPanel() v.add(roApp!!) r.add(v) } override fun dispose(): Map<String, Any> { return mapOf() } private fun initRoApp() { roApp = RoApp() ViewManager.app = this } } fun main() { startApplication( ::App, module.hot, BootstrapModule, BootstrapCssModule, FontAwesomeModule, BootstrapSelectModule, BootstrapDatetimeModule, BootstrapSpinnerModule, BootstrapTypeaheadModule, BootstrapUploadModule, RichTextModule, ChartModule, TabulatorModule, CoreModule, panelsCompatibilityMode = true, ) }
apache-2.0
41e4f4dd2d94b17ffcabd090248bfd04
26.306667
64
0.661621
4.079681
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AnnotationConversion.kt
2
4450
// 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.nj2k.conversions import com.intellij.psi.PsiArrayType import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.primaryConstructor import org.jetbrains.kotlin.nj2k.toExpression import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.isArrayType class AnnotationConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKAnnotation) return recurse(element) fixVarargsInvocation(element) for (parameter in element.arguments) { parameter.value = parameter.value.toExpression(symbolProvider) } return recurse(element) } private fun fixVarargsInvocation(annotation: JKAnnotation) { val newParameters = annotation.arguments.withIndex() .flatMap { (index, annotationParameter) -> when { annotationParameter !is JKAnnotationNameParameter && annotation.isVarargsArgument(index) && annotationParameter.value is JKKtAnnotationArrayInitializerExpression -> (annotationParameter.value as JKKtAnnotationArrayInitializerExpression)::initializers .detached() .map { JKAnnotationParameterImpl(it) } annotationParameter is JKAnnotationNameParameter && annotation.isVarargsArgument(annotationParameter.name.value) && annotationParameter.value !is JKKtAnnotationArrayInitializerExpression -> { listOf( JKAnnotationNameParameter( JKKtAnnotationArrayInitializerExpression(annotationParameter::value.detached()), JKNameIdentifier(annotationParameter.name.value) ) ) } annotationParameter is JKAnnotationNameParameter -> listOf( JKAnnotationNameParameter( annotationParameter::value.detached(), annotationParameter::name.detached() ) ) else -> listOf( JKAnnotationParameterImpl( annotationParameter::value.detached() ) ) } } annotation.arguments = newParameters } private fun PsiMethod.isVarArgsAnnotationMethod(isNamedArgument: Boolean) = isVarArgs || returnType is PsiArrayType || name == "value" && !isNamedArgument private fun JKParameter.isVarArgsAnnotationParameter(isNamedArgument: Boolean) = isVarArgs || type.type.isArrayType() || name.value == "value" && !isNamedArgument private fun JKAnnotation.isVarargsArgument(index: Int) = when (val target = classSymbol.target) { is JKClass -> target.primaryConstructor() ?.parameters ?.getOrNull(index) ?.isVarArgsAnnotationParameter(isNamedArgument = false) is PsiClass -> target.methods .getOrNull(index) ?.isVarArgsAnnotationMethod(isNamedArgument = false) else -> false } ?: false private fun JKAnnotation.isVarargsArgument(name: String): Boolean = when (val target = classSymbol.target) { is JKClass -> target.primaryConstructor() ?.parameters ?.firstOrNull { it.name.value == name } ?.isVarArgsAnnotationParameter(isNamedArgument = true) is PsiClass -> target.methods .firstOrNull { it.name == name } ?.isVarArgsAnnotationMethod(isNamedArgument = true) else -> false } ?: false }
apache-2.0
f234472a05341329aeb96fc655313341
46.860215
158
0.576854
6.661677
false
false
false
false
JetBrains/intellij-community
java/java-impl/src/com/intellij/codeInsight/intention/impl/JavaElementActionsFactory.kt
1
7640
// 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 com.intellij.codeInsight.intention.impl import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.daemon.impl.quickfix.ModifierFix import com.intellij.codeInsight.intention.AddAnnotationPsiFix import com.intellij.codeInsight.intention.FileModifier import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.lang.java.JavaLanguage import com.intellij.lang.java.actions.* import com.intellij.lang.jvm.* import com.intellij.lang.jvm.actions.* import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.refactoring.suggested.createSmartPointer import com.intellij.util.asSafely import org.jetbrains.uast.UDeclaration import java.util.* class JavaElementActionsFactory : JvmElementActionsFactory() { override fun createChangeModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> { val declaration = if (target is UDeclaration) target.javaPsi as PsiModifierListOwner else target as PsiModifierListOwner if (declaration.language != JavaLanguage.INSTANCE) return emptyList() return listOf(ChangeModifierFix(declaration, request)) } private class RemoveAnnotationFix(private val fqn: String, element: PsiModifierListOwner) : IntentionAction { val pointer = element.createSmartPointer() override fun startInWriteAction(): Boolean = true override fun getText(): String = QuickFixBundle.message("remove.override.fix.text") override fun getFamilyName(): String = QuickFixBundle.message("remove.override.fix.family") override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = pointer.element != null override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo { PsiTreeUtil.findSameElementInCopy(pointer.element, file)?.deleteAnnotation() return IntentionPreviewInfo.DIFF } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { pointer.element?.deleteAnnotation() } private fun PsiModifierListOwner.deleteAnnotation() { getAnnotation(fqn)?.delete() } } override fun createChangeOverrideActions(target: JvmModifiersOwner, shouldBePresent: Boolean): List<IntentionAction> { val psiElement = target.asSafely<PsiModifierListOwner>() ?: return emptyList() if (psiElement.language != JavaLanguage.INSTANCE) return emptyList() return if (shouldBePresent) { createAddAnnotationActions(target, annotationRequest(CommonClassNames.JAVA_LANG_OVERRIDE)) } else { listOf(RemoveAnnotationFix(CommonClassNames.JAVA_LANG_OVERRIDE, psiElement)) } } internal class ChangeModifierFix(declaration: PsiModifierListOwner, @FileModifier.SafeFieldForPreview val request: ChangeModifierRequest) : ModifierFix(declaration, request.modifier.toPsiModifier(), request.shouldBePresent(), true) { override fun isAvailable(): Boolean = request.isValid && super.isAvailable() override fun isAvailable(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement): Boolean = request.isValid && super.isAvailable(project, file, editor, startElement, endElement) } override fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> { val declaration = target as? PsiModifierListOwner ?: return emptyList() if (declaration.language != JavaLanguage.INSTANCE) return emptyList() if (!AddAnnotationPsiFix.isAvailable(target, request.qualifiedName)) { return emptyList() } return listOf(CreateAnnotationAction(declaration, request)) } override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> { val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList() val constantRequested = request.isConstant || javaClass.isInterface || javaClass.isRecord || request.modifiers.containsAll(constantModifiers) val result = ArrayList<IntentionAction>() if (canCreateEnumConstant(javaClass, request)) { result += CreateEnumConstantAction(javaClass, request) } if (constantRequested || request.fieldName.uppercase(Locale.ENGLISH) == request.fieldName) { result += CreateConstantAction(javaClass, request) } if (!constantRequested) { result += CreateFieldAction(javaClass, request) } return result } override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> { val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList() val requestedModifiers = request.modifiers val staticMethodRequested = JvmModifier.STATIC in requestedModifiers if (staticMethodRequested) { // static method in interfaces are allowed starting with Java 8 if (javaClass.isInterface && !PsiUtil.isLanguageLevel8OrHigher(javaClass)) return emptyList() // static methods in inner classes are disallowed: see JLS 8.1.3 if (javaClass.containingClass != null && !javaClass.hasModifierProperty(PsiModifier.STATIC)) return emptyList() } val result = ArrayList<IntentionAction>() result += CreateMethodAction(javaClass, request, false) if (!staticMethodRequested && javaClass.hasModifierProperty(PsiModifier.ABSTRACT) && !javaClass.isInterface) { result += CreateMethodAction(javaClass, request, true) } if (!javaClass.isInterface) { result += CreatePropertyAction(javaClass, request) result += CreateGetterWithFieldAction(javaClass, request) result += CreateSetterWithFieldAction(javaClass, request) } return result } override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> { val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList() return listOf(CreateConstructorAction(javaClass, request)) } override fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> { val psiMethod = target as? PsiMethod ?: return emptyList() if (psiMethod.language != JavaLanguage.INSTANCE) return emptyList() if (request.expectedParameters.any { it.expectedTypes.isEmpty() || it.semanticNames.isEmpty() }) return emptyList() return listOf(ChangeMethodParameters(psiMethod, request)) } override fun createChangeTypeActions(target: JvmMethod, request: ChangeTypeRequest): List<IntentionAction> { val psiMethod = target as? PsiMethod ?: return emptyList() if (psiMethod.language != JavaLanguage.INSTANCE) return emptyList() val typeElement = psiMethod.returnTypeElement ?: return emptyList() return listOf(ChangeType(typeElement, request)) } override fun createChangeTypeActions(target: JvmParameter, request: ChangeTypeRequest): List<IntentionAction> { val psiParameter = target as? PsiParameter ?: return emptyList() if (psiParameter.language != JavaLanguage.INSTANCE) return emptyList() val typeElement = psiParameter.typeElement ?: return emptyList() return listOf(ChangeType(typeElement, request)) } }
apache-2.0
435b36f9345368fb92491c32d4a130b1
47.35443
158
0.75877
5.158677
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/structural-search-k1/src/org/jetbrains/kotlin/idea/structuralsearch/KotlinStructuralReplaceHandler.kt
1
22658
// 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.structuralsearch import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.impl.source.codeStyle.IndentHelper import com.intellij.psi.util.elementType import com.intellij.structuralsearch.StructuralReplaceHandler import com.intellij.structuralsearch.StructuralSearchUtil import com.intellij.structuralsearch.impl.matcher.MatcherImplUtil import com.intellij.structuralsearch.impl.matcher.PatternTreeContext import com.intellij.structuralsearch.impl.matcher.compiler.PatternCompiler import com.intellij.structuralsearch.plugin.replace.ReplaceOptions import com.intellij.structuralsearch.plugin.replace.ReplacementInfo import com.intellij.util.containers.tail import org.jetbrains.kotlin.idea.base.util.reformatted import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.addTypeParameter import org.jetbrains.kotlin.idea.core.setDefaultValue import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.js.translate.declaration.hasCustomGetter import org.jetbrains.kotlin.js.translate.declaration.hasCustomSetter import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference class KotlinStructuralReplaceHandler(private val project: Project) : StructuralReplaceHandler() { override fun replace(info: ReplacementInfo, options: ReplaceOptions) { val searchTemplate = StructuralSearchUtil.getPresentableElement( PatternCompiler.compilePattern(project, options.matchOptions, true, true).let { it.targetNode ?: it.nodes.current() }) val fileType = options.matchOptions.fileType ?: return val replaceTemplates = MatcherImplUtil.createTreeFromText( info.replacement.fixPattern(), PatternTreeContext.Block, fileType, project ) for (i in 0 until info.matchesCount) { val match = StructuralSearchUtil.getPresentableElement(info.getMatch(i)) ?: break val replacement = replaceTemplates.getOrNull(i) ?: break replacement.structuralReplace(searchTemplate, StructuralSearchUtil.getPresentableElement(info.matchResult.match), options) match.replace(replacement) } var lastElement = info.getMatch(info.matchesCount - 1) ?: return (info.matchesCount until replaceTemplates.size).forEach { i -> val replacement = replaceTemplates[i] if (replacement is PsiErrorElement) return@forEach lastElement.parent.addAfter(replacement, lastElement) lastElement.nextSibling?.let { next -> lastElement = next.reformatted() } } (replaceTemplates.size until info.matchesCount).mapNotNull(info::getMatch).forEach { val parent = it.parent StructuralSearchUtil.getPresentableElement(it).delete() if (parent is KtBlockExpression) { // fix formatting for right braces when deleting parent.rBrace?.reformatted() } } } override fun postProcess(affectedElement: PsiElement, options: ReplaceOptions) { if (options.isToShortenFQN) { ShortenReferences.DEFAULT.process(affectedElement as KtElement) } } private fun String.fixPattern(): String { if (startsWith(".")) return substring(startIndex = 1) // dot qualified expressions without receiver matching normal call return this } private fun PsiElement.structuralReplace(searchTemplate: PsiElement, match: PsiElement, options: ReplaceOptions): PsiElement { if (searchTemplate is KtDeclaration && this is KtDeclaration && match is KtDeclaration) { replaceDeclaration(searchTemplate, match) if (this is KtCallableDeclaration && searchTemplate is KtCallableDeclaration && match is KtCallableDeclaration) { replaceCallableDeclaration(searchTemplate, match) } when { this is KtClassOrObject && searchTemplate is KtClassOrObject && match is KtClassOrObject -> replaceClassOrObject( searchTemplate, match ) this is KtNamedFunction && searchTemplate is KtNamedFunction && match is KtNamedFunction -> replaceNamedFunction( searchTemplate, match ) this is KtProperty && searchTemplate is KtProperty && match is KtProperty -> replaceProperty(searchTemplate, match) } } else { // KtExpression when { this is KtWhenExpression -> replaceWhenExpression() this is KtLambdaExpression && searchTemplate is KtLambdaExpression && match is KtLambdaExpression -> replaceLambdaExpression( searchTemplate, match ) this is KtDotQualifiedExpression && searchTemplate is KtDotQualifiedExpression && match is KtDotQualifiedExpression -> replaceDotQualifiedExpression( searchTemplate, match, options ) this is KtCallExpression && searchTemplate is KtCallExpression && match is KtCallExpression -> replaceCallExpression( searchTemplate, match ) } fixWhiteSpace(match) } return this } private fun KtCallExpression.replaceCallExpression(searchTemplate: KtCallExpression, match: KtCallExpression) { lambdaArguments.firstOrNull()?.getLambdaExpression()?.replaceLambdaExpression( searchTemplate.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return, match.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return ) } private fun KtDotQualifiedExpression.replaceDotQualifiedExpression( searchTemplate: KtDotQualifiedExpression, match: KtDotQualifiedExpression, options: ReplaceOptions ) { // fix parsing for fq selector expression replacement with shorten references if (receiverExpression is KtDotQualifiedExpression && selectorExpression is KtCallExpression && options.isToShortenFQN) { val file = match.containingKtFile val symbols = text.split(".") val psiFactory = KtPsiFactory(project) receiverExpression.replace(psiFactory.createExpression(symbols.first())) val importName = FqName(symbols.tail().joinToString(separator = ".") { it }.substringBefore("(")) file.resolveImportReference(importName).firstOrNull()?.let { importRef -> ImportInsertHelper.getInstance(project).importDescriptor(file, importRef) } file.importList?.let { CodeStyleManager.getInstance(project).reformat(it, true) } } receiverExpression.structuralReplace(searchTemplate.receiverExpression, match.receiverExpression, options) val selectorExpr = selectorExpression val searchSelectorExpr = searchTemplate.selectorExpression val matchSelectorExpr = match.selectorExpression if (selectorExpr != null && searchSelectorExpr != null && matchSelectorExpr != null) { selectorExpr.structuralReplace(searchSelectorExpr, matchSelectorExpr, options) } } private fun KtWhenExpression.replaceWhenExpression() { if (subjectExpression == null) { leftParenthesis?.delete() rightParenthesis?.delete() } } private fun KtLambdaExpression.replaceLambdaExpression(searchTemplate: KtLambdaExpression, match: KtLambdaExpression) { if (valueParameters.isEmpty() && searchTemplate.valueParameters.isEmpty()) { // { $A$ } templates match.functionLiteral.valueParameterList?.let { functionLiteral.addAfter(it, functionLiteral.lBrace) functionLiteral.valueParameterList?.let { vPl -> match.functionLiteral.arrow?.let { mArrow -> functionLiteral.addAfter(mArrow, vPl) } match.functionLiteral.valueParameterList?.let { mVpl -> functionLiteral.addSurroundingWhiteSpace(vPl, mVpl) } } } } if (valueParameters.isEmpty()) { findDescendantOfType<PsiElement> { it.elementType == KtTokens.ARROW }?.let { it.deleteSurroundingWhitespace() it.delete() } } valueParameters.forEachIndexed { i, par -> val searchPar = searchTemplate.valueParameters.getOrElse(i) { return@forEachIndexed } val matchPar = match.valueParameters.getOrElse(i) { return@forEachIndexed } if (par.typeReference == null && searchPar.typeReference == null) { matchPar.typeReference?.let { mTr -> par.typeReference = mTr par.typeReference?.let { pTr -> par.addSurroundingWhiteSpace(pTr, mTr) } } } } } private fun PsiElement.fixWhiteSpace(match: PsiElement) { val indentationLength = IndentHelper.getInstance().getIndent(match.containingFile, match.node, true) collectDescendantsOfType<PsiWhiteSpace> { it.text.contains("\n") }.forEach { val newLineCount = it.text.count { char -> char == '\n' } it.replace(KtPsiFactory(project).createWhiteSpace( "\n".repeat(newLineCount) + " ".repeat(indentationLength + it.text.length - 1)) ) } } private fun KtModifierListOwner.replaceModifier( searchTemplate: KtModifierListOwner, match: KtModifierListOwner, modifier: KtModifierKeywordToken ): KtModifierListOwner { if (!hasModifier(modifier) && match.hasModifier(modifier) && !searchTemplate.hasModifier(modifier)) { addModifier(modifier) modifierList?.getModifier(modifier)?.let { mod -> match.modifierList?.getModifier(modifier)?.let { mMod -> modifierList?.addSurroundingWhiteSpace(mod, mMod) } } } return this } private fun KtModifierListOwner.fixModifierListFormatting(match: KtModifierListOwner): KtModifierListOwner { modifierList?.children?.let { children -> if (children.isNotEmpty() && children.last() is PsiWhiteSpace) children.last().delete() } modifierList?.let { rModL -> match.modifierList?.let { mModL -> addSurroundingWhiteSpace(rModL, mModL) } } return this } private fun KtDeclaration.replaceDeclaration(searchTemplate: KtDeclaration, match: KtDeclaration): KtDeclaration { if (modifierList?.annotationEntries?.isEmpty() == true) { // remove @ symbol for when annotation count filter is equal to 0 val atElement = modifierList?.children?.find { it is PsiErrorElement } atElement?.delete() } val annotationNames = annotationEntries.map { it.shortName } val searchNames = searchTemplate.annotationEntries.map { it.shortName } match.annotationEntries.forEach { matchAnnotation -> val shortName = matchAnnotation.shortName if (!annotationNames.contains(shortName) && !searchNames.contains(shortName)) { addAnnotationEntry(matchAnnotation) } } fun KtDeclaration.replaceVisibilityModifiers(searchTemplate: KtDeclaration, match: KtDeclaration): PsiElement { if (visibilityModifierType() == null && searchTemplate.visibilityModifierType() == null) { match.visibilityModifierType()?.let { addModifier(it) visibilityModifier()?.let { vM -> match.visibilityModifier()?.let { mVm -> modifierList?.addSurroundingWhiteSpace(vM, mVm) } } } } return this } replaceVisibilityModifiers(searchTemplate, match) return this } private fun KtCallableDeclaration.replaceCallableDeclaration( searchTemplate: KtCallableDeclaration, match: KtCallableDeclaration ): KtCallableDeclaration { if (receiverTypeReference == null && searchTemplate.receiverTypeReference == null) { match.receiverTypeReference?.let(this::setReceiverTypeReference) } if (typeReference == null || searchTemplate.typeReference == null) { match.typeReference?.let { matchTr -> typeReference = matchTr typeReference?.let { addSurroundingWhiteSpace(it, matchTr) } colon?.let { c -> match.colon?.let { mC -> addSurroundingWhiteSpace(c, mC) } } } } val searchParam = searchTemplate.valueParameterList val matchParam = match.valueParameterList if (searchParam != null && matchParam != null) valueParameterList?.replaceParameterList(searchParam, matchParam) if (typeParameterList == null && searchTemplate.typeParameterList == null) match.typeParameters.forEach { addTypeParameter(it) } return this } private fun KtClassOrObject.replaceClassOrObject(searchTemplate: KtClassOrObject, match: KtClassOrObject): KtClassOrObject { if (getSuperTypeList()?.findDescendantOfType<PsiErrorElement>() != null) { getSuperTypeList()?.delete() } if (typeParameters.isEmpty()) typeParameterList?.delete() // for count filter equals to 0 inside <> CLASS_MODIFIERS.forEach { replaceModifier(searchTemplate, match, it) } fixModifierListFormatting(match) if (primaryConstructor == null && searchTemplate.primaryConstructor == null) { match.primaryConstructor?.let { addFormatted(it) } } if (primaryConstructorModifierList == null && searchTemplate.primaryConstructorModifierList == null) { match.primaryConstructorModifierList?.let { matchModList -> matchModList.visibilityModifierType()?.let { primaryConstructor?.addModifier(it) } primaryConstructor?.let { pC -> match.primaryConstructor?.let { mPc -> addSurroundingWhiteSpace(pC, mPc) } } } } val searchParamList = searchTemplate.getPrimaryConstructorParameterList() val matchParamList = match.getPrimaryConstructorParameterList() if (searchParamList != null && matchParamList != null) getPrimaryConstructorParameterList()?.replaceParameterList( searchParamList, matchParamList ) if (getSuperTypeList() == null && searchTemplate.getSuperTypeList() == null) { // replace all entries match.superTypeListEntries.forEach { val superTypeEntry = addSuperTypeListEntry(it) getSuperTypeList()?.addSurroundingWhiteSpace(superTypeEntry, it) } // format commas val matchCommas = match.getSuperTypeList()?.node?.children()?.filter { it.elementType == KtTokens.COMMA }?.map { it.psi }?.toList() getSuperTypeList()?.node?.children()?.filter { it.elementType == KtTokens.COMMA }?.forEachIndexed { index, element -> matchCommas?.get(index)?.let { mC -> getSuperTypeList()?.addSurroundingWhiteSpace(element.psi, mC) } } // format semi colon if (superTypeListEntries.isNotEmpty() && match.superTypeListEntries.isNotEmpty()) { getColon()?.let { replaceColon -> match.getColon()?.let { matchColon -> addSurroundingWhiteSpace(replaceColon, matchColon) } } } } getSuperTypeList()?.node?.lastChildNode?.psi?.let { if (it is PsiWhiteSpace) it.delete() } if (body == null && searchTemplate.body == null) match.body?.let { matchBody -> addFormatted(matchBody) } return this } private fun KtNamedFunction.replaceNamedFunction(searchTemplate: KtNamedFunction, match: KtNamedFunction): KtNamedFunction { FUN_MODIFIERS.forEach { replaceModifier(searchTemplate, match, it) } fixModifierListFormatting(match) if (receiverTypeReference?.findDescendantOfType<PsiErrorElement> { true } != null) { findDescendantOfType<PsiElement> { it.elementType == KtTokens.DOT }?.delete() } if (!hasBody() && !searchTemplate.hasBody()) { match.equalsToken?.let { addFormatted(it) } match.bodyExpression?.let { addFormatted(it) } } if (lastChild !is PsiComment && searchTemplate.lastChild !is PsiComment && match.lastChild is PsiComment) { match.lastChild?.let { addFormatted(it) } } return this } private fun KtProperty.replaceProperty(searchTemplate: KtProperty, match: KtProperty): KtProperty { if (initializer == null) equalsToken?.let { // when count filter = 0 on the initializer it.deleteSurroundingWhitespace() it.delete() } PROPERTY_MODIFIERS.forEach { replaceModifier(searchTemplate, match, it) } fixModifierListFormatting(match) if (!hasDelegate() && !hasInitializer()) { if (!searchTemplate.hasInitializer()) { match.equalsToken?.let { addFormatted(it) } match.initializer?.let { addFormatted(it) } } if (!searchTemplate.hasDelegate()) match.delegate?.let { addFormatted(it) } } if (!hasCustomGetter() && !searchTemplate.hasCustomGetter()) match.getter?.let { addFormatted(it) } if (!hasCustomSetter() && !searchTemplate.hasCustomSetter()) match.setter?.let { addFormatted(it) } return this } private fun KtParameterList.replaceParameterList( searchTemplate: KtParameterList, match: KtParameterList ): KtParameterList { parameters.forEachIndexed { i, param -> val searchParam = searchTemplate.parameters.getOrNull(i) val matchParam = match.parameters.getOrNull(i) ?: return@forEachIndexed if (searchParam == null) { // count filter addSurroundingWhiteSpace(param, matchParam) } if (param.valOrVarKeyword == null && searchParam?.valOrVarKeyword == null) { matchParam.valOrVarKeyword?.let { mVal -> param.addBefore(mVal, param.nameIdentifier) param.valOrVarKeyword?.let { param.addSurroundingWhiteSpace(it, mVal) } } } if (param.typeReference == null && searchParam?.typeReference == null) { matchParam.typeReference?.let { param.typeReference = it param.colon?.let { pColon -> matchParam.colon?.let { mColon -> param.addSurroundingWhiteSpace(pColon, mColon) } } } } if (!param.hasDefaultValue() && searchParam?.hasDefaultValue() != true) { matchParam.defaultValue?.let { param.setDefaultValue(it) param.equalsToken?.let { pEq -> matchParam.equalsToken?.let { mEq -> param.addSurroundingWhiteSpace(pEq, mEq) } } } } } return this } private fun PsiElement.addFormatted(match: PsiElement) = addSurroundingWhiteSpace(add(match), match) private fun PsiElement.addSurroundingWhiteSpace(anchor: PsiElement, match: PsiElement) { val nextAnchor = anchor.nextSibling val prevAnchor = anchor.prevSibling val nextElement = match.nextSibling val prevElement = match.prevSibling if (prevElement is PsiWhiteSpace) { if (prevAnchor is PsiWhiteSpace) prevAnchor.replace(prevElement) else addBefore(prevElement, anchor) } if (nextElement is PsiWhiteSpace) { if (nextAnchor is PsiWhiteSpace) nextAnchor.replace(nextElement) else addAfter(nextElement, anchor) } } private fun PsiElement.deleteSurroundingWhitespace() { val nextAnchor = nextSibling val prevAnchor = prevSibling if (nextAnchor is PsiWhiteSpace) nextAnchor.delete() if (prevAnchor is PsiWhiteSpace) prevAnchor.delete() } companion object { private val CLASS_MODIFIERS = arrayOf( KtTokens.ABSTRACT_KEYWORD, KtTokens.ENUM_KEYWORD, KtTokens.OPEN_KEYWORD, KtTokens.INNER_KEYWORD, KtTokens.FINAL_KEYWORD, KtTokens.COMPANION_KEYWORD, KtTokens.SEALED_KEYWORD, KtTokens.DATA_KEYWORD, KtTokens.INLINE_KEYWORD, KtTokens.EXTERNAL_KEYWORD, KtTokens.ANNOTATION_KEYWORD, KtTokens.CROSSINLINE_KEYWORD, KtTokens.HEADER_KEYWORD, KtTokens.IMPL_KEYWORD, KtTokens.EXPECT_KEYWORD, KtTokens.ACTUAL_KEYWORD ) private val FUN_MODIFIERS = arrayOf( KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD, KtTokens.INNER_KEYWORD, KtTokens.OVERRIDE_KEYWORD, KtTokens.FINAL_KEYWORD, KtTokens.INLINE_KEYWORD, KtTokens.TAILREC_KEYWORD, KtTokens.EXTERNAL_KEYWORD, KtTokens.OPERATOR_KEYWORD, KtTokens.INFIX_KEYWORD, KtTokens.SUSPEND_KEYWORD, KtTokens.HEADER_KEYWORD, KtTokens.IMPL_KEYWORD, KtTokens.EXPECT_KEYWORD, KtTokens.ACTUAL_KEYWORD ) private val PROPERTY_MODIFIERS = arrayOf( KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD, KtTokens.OVERRIDE_KEYWORD, KtTokens.FINAL_KEYWORD, KtTokens.LATEINIT_KEYWORD, KtTokens.EXTERNAL_KEYWORD, KtTokens.CONST_KEYWORD, KtTokens.HEADER_KEYWORD, KtTokens.IMPL_KEYWORD, KtTokens.EXPECT_KEYWORD, KtTokens.ACTUAL_KEYWORD ) } }
apache-2.0
8e94d84ce36bfeb8c1c43e7b60908edd
47.520343
165
0.650057
5.641932
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/dependencies/ScriptDependenciesResolveScopeProvider.kt
1
3800
// 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.core.script.dependencies import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.ResolveScopeProvider import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.NonClasspathDirectoriesScope import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptDependenciesInfo import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.ucache.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * @see KotlinScriptResolveScopeProvider */ class ScriptDependenciesResolveScopeProvider : ResolveScopeProvider() { /** * @param file is a file belonging to dependencies of a script being analysed */ override fun getResolveScope(file: VirtualFile, project: Project): GlobalSearchScope? { /* Unfortunately, we cannot limit the scope to the concrete script dependencies. There is no way to say, what .kts is being analysed. Some facts to consider: - dependencies are analysed first, .kts file itself goes last - multiple editors can be opened (selected is only one of them) */ if (getAllScriptsDependenciesClassFiles(project).isEmpty()) return null if (file !in getAllScriptsDependenciesClassFilesScope(project) && file !in getAllScriptDependenciesSourcesScope(project) ) { return null } if (scriptsAsEntities) { val scripts = file.findUsedInScripts(project) ?: return null val dependencies = scripts.flatMap { it.listDependencies(KotlinScriptLibraryRootTypeId.COMPILED) }.distinct() var searchScope = GlobalSearchScope.union( arrayOf( GlobalSearchScope.fileScope(project, file), KotlinSourceFilterScope.libraryClasses(NonClasspathDirectoriesScope.compose(dependencies), project) ) ) ScriptConfigurationManager.getInstance(project).getFirstScriptsSdk()?.let { searchScope = searchScope.uniteWith(SdkInfo(project, it).contentScope) } return searchScope } val scope = GlobalSearchScope.union( arrayOf( GlobalSearchScope.fileScope(project, file), *ScriptDependenciesInfo.ForProject(project).dependencies().map { it.contentScope }.toTypedArray() ) ) return KotlinScriptSearchScope(project, scope) } } private fun VirtualFile?.findUsedInScripts(project: Project): List<KotlinScriptEntity>? { val index = WorkspaceModel.getInstance(project).entityStorage.current.getVirtualFileUrlIndex() val fileUrlManager = VirtualFileUrlManager.getInstance(project) var currentFile = this @Suppress("SENSELESS_COMPARISON") while (currentFile != null) { val entities = index.findEntitiesByUrl(fileUrlManager.fromUrl(currentFile.url)) if (entities.none()) { currentFile = currentFile.parent continue } return entities .mapNotNull { it.first.safeAs<KotlinScriptLibraryEntity>() } .map { it.kotlinScript } .toList() } return null }
apache-2.0
ec6ea7385240db520aed4c82a860e809
40.304348
158
0.710263
5.156038
false
false
false
false
java-graphics/assimp
src/main/kotlin/assimp/format/ply/PlyLoader.kt
2
30190
package assimp.format.ply import glm_.* import glm_.vec3.Vec3 import assimp.* import java.io.IOException import java.nio.ByteOrder /** * Created by elect on 10/12/2016. */ class PlyLoader : BaseImporter() { override val info = AiImporterDesc( name = "Stanford Polygon Library (PLY) Importer", flags = AiImporterFlags.SupportBinaryFlavour or AiImporterFlags.SupportTextFlavour, fileExtensions = listOf("ply")) /** Document object model representation extracted from the file */ lateinit var pcDom: DOM // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. override fun canRead(file: String, ioSystem: IOSystem, checkSig: Boolean): Boolean { val extension = file.substring(file.lastIndexOf('.') + 1) if (extension == "ply") return true return false } // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. override fun internReadFile(file: String, ioSystem: IOSystem, scene: AiScene) { // allocate storage and copy the contents of the file to a memory buffer val buffer = ioSystem.open(file).readBytes() // the beginning of the file must be PLY - magic, magic if (buffer.nextWord().toLowerCase() != "ply") throw Exception("Invalid .ply file: Magic number 'ply' is no there") buffer.skipSpacesAndLineEnd() // determine the format of the file data val sPlyDom = DOM() if (buffer.nextWord() == "format") { val format = buffer.nextWord() if (format == "ascii") { buffer.skipLine() if (!DOM.parseInstance(buffer, sPlyDom)) throw Exception("Invalid .ply file: Unable to build DOM (#1)") } else { // revert ascii buffer.position(buffer.position() - format.length) if (buffer.startsWith("binary_")) { val bIsBE = buffer.get(buffer.position()) == 'b'.b || buffer.get(buffer.position()) == 'B'.b buffer.order(if (bIsBE) ByteOrder.BIG_ENDIAN else ByteOrder.LITTLE_ENDIAN) // skip the line, parse the rest of the header and build the DOM buffer.skipLine() if (!DOM.parseInstanceBinary(buffer, sPlyDom)) throw Exception("Invalid .ply file: Unable to build DOM (#2)") } else throw Exception("Invalid .ply file: Unknown file format") } } else throw Exception("Invalid .ply file: Missing format specification") pcDom = sPlyDom // now load a list of vertices. This must be successfully in order to procedure val avPositions = ArrayList<AiVector3D>() loadVertices(avPositions, false) // now load a list of normals. val avNormals = ArrayList<AiVector3D>() loadVertices(avNormals, true) // load the face list val avFaces = ArrayList<Face>() loadFaces(avFaces) // if no face list is existing we assume that the vertex list is containing a list of triangles if (avFaces.isEmpty()) { if (avPositions.size < 3) throw Exception("Invalid .ply file: Not enough vertices to build a proper face list.") val iNum = avPositions.size / 3 repeat(iNum) { val sFace = Face() sFace.mIndices[0] = it * 3 sFace.mIndices[1] = it * 3 + 1 sFace.mIndices[2] = it * 3 + 2 avFaces.add(sFace) } } // now load a list of all materials val avMaterials = ArrayList<AiMaterial>() loadMaterial(avMaterials) // now load a list of all vertex color channels val avColors = ArrayList<AiColor4D>() loadVertexColor(avColors) // now try to load texture coordinates val avTexCoords = ArrayList<AiVector2D>() loadTextureCoordinates(avTexCoords) // now replace the default material in all faces and validate all material indices replaceDefaultMaterial(avFaces, avMaterials) // now convert this to a list of aiMesh instances val avMeshes = ArrayList<AiMesh>() convertMeshes(avFaces, avPositions, avNormals, avColors, avTexCoords, avMaterials, avMeshes) if (avMeshes.isEmpty()) throw Exception("Invalid .ply file: Unable to extract mesh data ") // now generate the output scene object. Fill the material list scene.numMaterials = avMaterials.size scene.materials.addAll(avMaterials) // fill the mesh list scene.numMeshes = avMeshes.size scene.meshes.addAll(avMeshes) // generate a simple node structure scene.rootNode = AiNode() scene.rootNode.numMeshes = scene.numMeshes scene.rootNode.meshes = IntArray(scene.rootNode.numMeshes, { it }) } /** Try to extract vertices from the PLY DOM. */ private fun loadVertices(pvOut: ArrayList<AiVector3D>, p_bNormals: Boolean) { val aiPositions = intArrayOf(0xFFFFFFFF.i, 0xFFFFFFFF.i, 0xFFFFFFFF.i) val aiTypes = arrayListOf(EDataType.Char, EDataType.Char, EDataType.Char) var pcList: ElementInstanceList? = null var cnt = 0 // search in the DOM for a vertex entry for (element in pcDom.alElements) { val i = pcDom.alElements.indexOf(element) if (element.eSemantic == EElementSemantic.Vertex) { pcList = pcDom.alElementData[i] // load normal vectors? if (p_bNormals) // now check whether which normal components are available for (property in element.alProperties) { if (property.bIsList) continue val a = element.alProperties.indexOf(property) if (property.semantic == ESemantic.XNormal) { cnt++ aiPositions[0] = a aiTypes[0] = property.eType } if (property.semantic == ESemantic.YNormal) { cnt++ aiPositions[1] = a aiTypes[1] = property.eType } if (property.semantic == ESemantic.ZNormal) { cnt++ aiPositions[2] = a aiTypes[2] = property.eType } } // load vertex coordinates else // now check whether which coordinate sets are available for (property in element.alProperties) { if (property.bIsList) continue val a = element.alProperties.indexOf(property) if (property.semantic == ESemantic.XCoord) { cnt++ aiPositions[0] = a aiTypes[0] = property.eType } if (property.semantic == ESemantic.YCoord) { cnt++ aiPositions[1] = a aiTypes[1] = property.eType } if (property.semantic == ESemantic.ZCoord) { cnt++ aiPositions[2] = a aiTypes[2] = property.eType } if (cnt == 3) break } break } } // check whether we have a valid source for the vertex data if (pcList != null && cnt != 0) for (instance in pcList.alInstances) { // convert the vertices to sp floats val vOut = AiVector3D() if (aiPositions[0] != 0xFFFFFFFF.i) vOut.x = instance.alProperties[aiPositions[0]].avList[0].f if (aiPositions[1] != 0xFFFFFFFF.i) vOut.y = instance.alProperties[aiPositions[1]].avList[0].f if (aiPositions[2] != 0xFFFFFFFF.i) vOut.z = instance.alProperties[aiPositions[2]].avList[0].f // and add them to our nice list pvOut.add(vOut) } } /** Try to extract proper faces from the PLY DOM. */ fun loadFaces(pvOut: ArrayList<Face>) { var pcList: ElementInstanceList? = null var bOne = false // index of the vertex index list var iProperty = 0xFFFFFFFF.i var eType = EDataType.Char var bIsTriStrip = false // index of the material index property var iMaterialIndex = 0xFFFFFFFF.i var eType2 = EDataType.Char // search in the DOM for a face entry for (element in pcDom.alElements) { val i = pcDom.alElements.indexOf(element) // face = unique number of vertex indices if (element.eSemantic == EElementSemantic.Face) { pcList = pcDom.alElementData[i] for (property in element.alProperties) { val a = element.alProperties.indexOf(property) if (property.semantic == ESemantic.VertexIndex) { // must be a dynamic list! if (!property.bIsList) continue iProperty = a bOne = true eType = property.eType } else if (property.semantic == ESemantic.MaterialIndex) { if (property.bIsList) continue iMaterialIndex = a bOne = true eType = property.eType } } break } // triangle strip // TODO: triangle strip and material index support??? else if (element.eSemantic == EElementSemantic.TriStrip) { // find a list property in this ... pcList = pcDom.alElementData[i] for (property in element.alProperties) { val a = element.alProperties.indexOf(property) // must be a dynamic list! if (!property.bIsList) continue iProperty = a bOne = true bIsTriStrip = true eType = property.eType break } break } } // check whether we have at least one per-face information set if (pcList != null && bOne) if (!bIsTriStrip) { for (instance in pcList.alInstances) { val sFace = Face() // parse the list of vertex indices if (iProperty != 0xFFFFFFFF.i) { val iNum = instance.alProperties[iProperty].avList.size sFace.mIndices = IntArray(iNum, { 0 }) val p = instance.alProperties[iProperty].avList repeat(iNum) { sFace.mIndices[it] = p[it].ui.v } } // parse the material index if (iMaterialIndex != 0xFFFFFFFF.i) sFace.iMaterialIndex = instance.alProperties[iMaterialIndex].avList[0].ui.v pvOut.add(sFace) } } // triangle strips else { // normally we have only one triangle strip instance where a value of -1 indicates a restart of the strip var flip = false for (instance in pcList.alInstances) { val quak = instance.alProperties[iProperty].avList val aiTable = intArrayOf(-1, -1) for (number in quak) { val p = number.i if (p == -1) { // restart the strip ... aiTable[0] = -1 aiTable[1] = -1 flip = false continue } if (aiTable[0] == -1) { aiTable[0] = p continue } if (aiTable[1] == -1) { aiTable[1] = p continue } pvOut.add(Face()) val sFace = pvOut.last() sFace.mIndices[0] = aiTable[0] sFace.mIndices[1] = aiTable[1] sFace.mIndices[2] = p flip = !flip if (flip) { val t = sFace.mIndices[0] sFace.mIndices[0] = sFace.mIndices[1] sFace.mIndices[1] = t } aiTable[0] = aiTable[1] aiTable[1] = p } } } } /** Extract a material from the PLY DOM */ fun loadMaterial(pvOut: ArrayList<AiMaterial>) { // diffuse[4], specular[4], ambient[4] // rgba order val aaiPositions = Array(3, { IntArray(4, { 0xFFFFFFFF.i }) }) val aaiTypes = Array(3, { Array(4, { EDataType.Char }) }) var pcList: ElementInstanceList? = null var iPhong = 0xFFFFFFFF.i var ePhong = EDataType.Char var iOpacity = 0xFFFFFFFF.i var eOpacity = EDataType.Char // search in the DOM for a vertex entry for (element in pcDom.alElements) { val i = pcDom.alElements.indexOf(element) if (element.eSemantic == EElementSemantic.Material) { pcList = pcDom.alElementData[i] // now check whether which coordinate sets are available for (property in element.alProperties) { if (property.bIsList) continue val a = element.alProperties.indexOf(property) when (property.semantic) { // pohng specularity ----------------------------------- ESemantic.PhongPower -> { iPhong = a ePhong = property.eType } // general opacity ----------------------------------- ESemantic.Opacity -> { iOpacity = a eOpacity = property.eType } // diffuse color channels ----------------------------------- ESemantic.DiffuseRed -> { aaiPositions[0][0] = a aaiTypes[0][0] = property.eType } ESemantic.DiffuseGreen -> { aaiPositions[0][1] = a aaiTypes[0][1] = property.eType } ESemantic.DiffuseBlue -> { aaiPositions[0][2] = a aaiTypes[0][2] = property.eType } ESemantic.DiffuseAlpha -> { aaiPositions[0][3] = a aaiTypes[0][3] = property.eType } // specular color channels ----------------------------------- ESemantic.SpecularRed -> { aaiPositions[1][0] = a aaiTypes[1][0] = property.eType } ESemantic.SpecularGreen -> { aaiPositions[1][1] = a aaiTypes[1][1] = property.eType } ESemantic.SpecularBlue -> { aaiPositions[1][2] = a aaiTypes[1][2] = property.eType } ESemantic.SpecularAlpha -> { aaiPositions[1][3] = a aaiTypes[1][3] = property.eType } // ambient color channels ----------------------------------- ESemantic.AmbientRed -> { aaiPositions[2][0] = a aaiTypes[2][0] = property.eType } ESemantic.AmbientGreen -> { aaiPositions[2][1] = a aaiTypes[2][1] = property.eType } ESemantic.AmbientBlue -> { aaiPositions[2][2] = a aaiTypes[2][2] = property.eType } ESemantic.AmbientAlpha -> { aaiPositions[2][3] = a aaiTypes[2][3] = property.eType } } break } } } // check whether we have a valid source for the material data if (pcList != null) for (elementInstance in pcList.alInstances) { val clrOut = AiColor4D() val material = AiMaterial(color = AiMaterial.Color()) // build the diffuse material color getMaterialColor(elementInstance.alProperties, aaiPositions[0], aaiTypes[0], clrOut) material.color!!.diffuse = Vec3(clrOut) // build the specular material color getMaterialColor(elementInstance.alProperties, aaiPositions[1], aaiTypes[1], clrOut) material.color!!.specular = Vec3(clrOut) // build the ambient material color getMaterialColor(elementInstance.alProperties, aaiPositions[1], aaiTypes[1], clrOut) material.color!!.ambient = Vec3(clrOut) // handle phong power and shading mode var iMode = AiShadingMode.gouraud if (iPhong != 0xFFFFFFFF.i) { var fSpec = elementInstance.alProperties[iPhong].avList[0].f // if shininess is 0 (and the pow() calculation would therefore always become 1, not depending on the angle), use gouraud lighting if (fSpec != 0f) { // scale this with 15 ... hopefully this is correct fSpec *= 15 material.shininess = fSpec iMode = AiShadingMode.phong } } material.shadingModel = iMode // handle opacity if (iOpacity != 0xFFFFFFFF.i) { val fOpacity = elementInstance.alProperties[iPhong].avList[0].f material.opacity = fOpacity } // The face order is absolutely undefined for PLY, so we have to use two-sided rendering to be sure it's ok. material.twoSided = true // add the newly created material instance to the list pvOut.add(material) } } /** Get a RGBA color in [0...1] range */ fun getMaterialColor(avList: ArrayList<PropertyInstance>, aiPosition: IntArray, aiTypes: Array<EDataType>, clrOut: AiColor4D) { clrOut.r = if (aiPosition[0] == 0xFFFFFFFF.i) 0f else normalizeColorValue(avList[aiPosition[0]].avList[0], aiTypes[0]) clrOut.g = if (aiPosition[1] == 0xFFFFFFFF.i) 0f else normalizeColorValue(avList[aiPosition[1]].avList[0], aiTypes[1]) clrOut.b = if (aiPosition[2] == 0xFFFFFFFF.i) 0f else normalizeColorValue(avList[aiPosition[2]].avList[0], aiTypes[2]) // assume 1.0 for the alpha channel ifit is not set clrOut.a = if (aiPosition[3] == 0xFFFFFFFF.i) 1f else normalizeColorValue(avList[aiPosition[3]].avList[0], aiTypes[3]) } /** Convert a color component to [0...1] */ fun normalizeColorValue(value: Number, eType: EDataType) = when (eType) { EDataType.Float, EDataType.Double -> value.f EDataType.UChar -> value.ub.f EDataType.Char -> value.f EDataType.UShort -> value.us.f EDataType.Short -> value.f EDataType.UInt -> value.ui.f EDataType.Int -> value.f else -> 0f } /** Try to extract proper vertex colors from the PLY DOM */ fun loadVertexColor(pvOut: ArrayList<AiColor4D>) { val aiPositions = IntArray(4, { 0xFFFFFFFF.i }) val aiTypes = Array(4, { EDataType.Char }) var cnt = 0 var pcList: ElementInstanceList? = null // search in the DOM for a vertex entry for (element in pcDom.alElements) { val i = pcDom.alElements.indexOf(element) if (element.eSemantic == EElementSemantic.Vertex) { pcList = pcDom.alElementData[i] // now check whether which coordinate sets are available for (property in element.alProperties) { if (property.bIsList) continue val a = element.alProperties.indexOf(property) if (property.semantic == ESemantic.Red) { cnt++ aiPositions[0] = a aiTypes[0] = property.eType } if (property.semantic == ESemantic.Green) { cnt++ aiPositions[1] = a aiTypes[1] = property.eType } if (property.semantic == ESemantic.Blue) { cnt++ aiPositions[2] = a aiTypes[2] = property.eType } if (property.semantic == ESemantic.Alpha) { cnt++ aiPositions[3] = a aiTypes[3] = property.eType } if (cnt == 4) break } break } } // check whether we have a valid source for the vertex data if (pcList != null && cnt != 0) for (elementInstance in pcList.alInstances) { // convert the vertices to sp floats val vOut = AiColor4D() if (aiPositions[0] != 0xFFFFFFFF.i) vOut.r = normalizeColorValue(elementInstance.alProperties[aiPositions[0]].avList[0], aiTypes[0]) if (aiPositions[1] != 0xFFFFFFFF.i) vOut.g = normalizeColorValue(elementInstance.alProperties[aiPositions[1]].avList[0], aiTypes[1]) if (aiPositions[2] != 0xFFFFFFFF.i) vOut.b = normalizeColorValue(elementInstance.alProperties[aiPositions[2]].avList[0], aiTypes[2]) if (aiPositions[3] != 0xFFFFFFFF.i) vOut.a = 1f else vOut.a = normalizeColorValue(elementInstance.alProperties[aiPositions[3]].avList[0], aiTypes[3]) // and add them to our nice list pvOut.add(vOut) } } fun loadTextureCoordinates(pvOut: ArrayList<AiVector2D>) { val aiPosition = IntArray(2, { 0xFFFFFFFF.i }) val aiTypes = Array(2, { EDataType.Char }) var pcList: ElementInstanceList? = null var cnt = 0 // search in the DOM for a vertex entry for (element in pcDom.alElements) { val i = pcDom.alElements.indexOf(element) if (element.eSemantic == EElementSemantic.Vertex) { pcList = pcDom.alElementData[i] // now check whether which normal components are available for (property in element.alProperties) { if (property.bIsList) continue val a = element.alProperties.indexOf(property) if (property.semantic == ESemantic.UTextureCoord) { cnt++ aiPosition[0] = a aiTypes[0] = property.eType } else if (property.semantic == ESemantic.VTextureCoord) { cnt++ aiPosition[1] = a aiTypes[1] = property.eType } } } } // check whether we have a valid source for the texture coordinates data if (pcList != null && cnt != 0) for (elementInstance in pcList.alInstances) { // convert the vertices to sp floats val vOut = AiVector2D() if (aiPosition[0] != 0xFFFFFFFF.i) vOut.x = elementInstance.alProperties[aiPosition[0]].avList[0].f if (aiPosition[1] != 0xFFFFFFFF.i) vOut.y = elementInstance.alProperties[aiPosition[1]].avList[0].f // and add them to our nice list pvOut.add(vOut) } } /** Generate a default material if none was specified and apply it to all vanilla faces */ fun replaceDefaultMaterial(avFaces: ArrayList<Face>, avMaterials: ArrayList<AiMaterial>) { var bNeedDefaultMat = false avFaces.forEach { if (it.iMaterialIndex == 0xFFFFFFFF.i) { bNeedDefaultMat = true it.iMaterialIndex = avMaterials.size } else if (it.iMaterialIndex >= avMaterials.size) // clamp the index it.iMaterialIndex = avMaterials.size - 1 } if (bNeedDefaultMat) // generate a default material avMaterials.add(AiMaterial( // fill in a default material shadingModel = AiShadingMode.gouraud, color = AiMaterial.Color( diffuse = AiColor3D(.6f), specular = AiColor3D(.6f), ambient = AiColor3D(.05f)), // The face order is absolutely undefined for PLY, so we have to use two-sided rendering to be sure it's ok. twoSided = true)) } /** Split meshes by material IDs */ fun convertMeshes(avFaces: ArrayList<Face>, avPositions: ArrayList<AiVector3D>, avNormals: ArrayList<AiVector3D>, avColors: ArrayList<AiColor4D>, avTexCoords: ArrayList<AiVector2D>, avMaterials: ArrayList<AiMaterial>, avOut: ArrayList<AiMesh>) { // split by materials val aiSplit = Array(avMaterials.size, { ArrayList<Int>() }) var iNum = 0 avFaces.forEach { aiSplit[it.iMaterialIndex].add(iNum) iNum++ } // now generate sub-meshes for (p in 0 until avMaterials.size) if (aiSplit[p].isNotEmpty()) { // allocate the mesh object val p_pcOut = AiMesh() p_pcOut.materialIndex = p p_pcOut.numFaces = aiSplit[p].size p_pcOut.faces = MutableList(aiSplit[p].size, { ArrayList<Int>() }) // at first we need to determine the size of the output vector array iNum = (0 until aiSplit[p].size).sumBy { avFaces[aiSplit[p][it]].mIndices.size } p_pcOut.numVertices = iNum if (iNum == 0) // nothing to do return // cleanup p_pcOut.vertices = MutableList(iNum, { AiVector3D() }) if (avColors.isNotEmpty()) p_pcOut.colors[0] = ArrayList() if (avTexCoords.isNotEmpty()) p_pcOut.textureCoords = mutableListOf(MutableList(iNum, { floatArrayOf(0f, 0f) })) if (avNormals.isNotEmpty()) p_pcOut.normals = MutableList(iNum, { AiVector3D() }) // add all faces iNum = 0 var iVertex = 0 for (i in 0 until aiSplit[p].size) { p_pcOut.faces[iNum] = MutableList(avFaces[i].mIndices.size, { 0 }) // build an unique set of vertices/colors for this face for (q in 0 until p_pcOut.faces[iNum].size) { p_pcOut.faces[iNum][q] = iVertex val idx = avFaces[i].mIndices[q] if (idx >= avPositions.size) // out of border continue p_pcOut.vertices[iVertex] put avPositions[idx] if (avColors.isNotEmpty()) p_pcOut.colors[0][iVertex] put avColors[idx] if (avTexCoords.isNotEmpty()) { val vec = avTexCoords[idx] p_pcOut.textureCoords[0][iVertex] = floatArrayOf(vec.x, vec.y) } if (avNormals.isNotEmpty()) p_pcOut.normals[iVertex] put avNormals[idx] iVertex++ } iNum++ } // add the mesh to the output list avOut.add(p_pcOut) } } }
bsd-3-clause
f7c957dde45510cef9d5205bab9b1be7
37.508929
150
0.479662
5.349043
false
false
false
false
mikepenz/Android-Iconics
iconics-core/src/main/java/com/mikepenz/iconics/utils/IconicsExtensions.kt
1
4915
/* * Copyright 2020 Mike Penz * * 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.mikepenz.iconics.utils import android.content.Context import android.content.ContextWrapper import android.os.Build import android.text.Spanned import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.View import android.widget.Button import android.widget.TextView import androidx.annotation.MenuRes import androidx.appcompat.app.AppCompatDelegate import androidx.core.view.LayoutInflaterCompat import com.mikepenz.iconics.Iconics import com.mikepenz.iconics.IconicsArrayBuilder import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.context.IconicsContextWrapper import com.mikepenz.iconics.context.IconicsLayoutInflater import com.mikepenz.iconics.context.IconicsLayoutInflater2 /** Adaptation for [IconicsContextWrapper] */ fun Context.wrapByIconics(): ContextWrapper = IconicsContextWrapper.wrap(this) /** * Compatible adaptation for setting IconicsLayoutInflater * @see IconicsLayoutInflater * @see IconicsLayoutInflater2 * */ @Suppress("DEPRECATION") fun LayoutInflater.setIconicsFactory(appCompatDelegate: AppCompatDelegate) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { LayoutInflaterCompat.setFactory2(this, IconicsLayoutInflater2(appCompatDelegate)) } else { LayoutInflaterCompat.setFactory(this, IconicsLayoutInflater(appCompatDelegate)) } } /** Adaptation for [IconicsMenuInflaterUtil.inflate] */ @JvmOverloads fun MenuInflater.inflateWithIconics( context: Context, menuId: Int, menu: Menu, checkSubMenu: Boolean = false ) { IconicsMenuInflaterUtil.inflate(this, context, menuId, menu, checkSubMenu) } /** Adaptation for [Iconics.Builder] with auto-executing [Iconics.BuilderString.build] */ fun Spanned.buildIconics(block: Iconics.Builder.() -> Unit = {}): Spanned { return Iconics.Builder().also(block).on(this).build() } /** Adaptation for [Iconics.Builder] with auto-executing [Iconics.BuilderString.build] */ fun String.buildIconics(block: Iconics.Builder.() -> Unit = {}): Spanned { return Iconics.Builder().also(block).on(this).build() } /** Adaptation for [Iconics.Builder] with auto-executing [Iconics.BuilderString.build] */ fun CharSequence.buildIconics(block: Iconics.Builder.() -> Unit = {}): Spanned { return Iconics.Builder().also(block).on(this).build() } /** Adaptation for [Iconics.Builder] with auto-executing [Iconics.BuilderString.build] */ fun StringBuilder.buildIconics(block: Iconics.Builder.() -> Unit = {}): Spanned { return Iconics.Builder().also(block).on(this).build() } /** Adaptation for [Iconics.Builder] with auto-executing [Iconics.BuilderView.build] */ fun TextView.buildIconics(block: Iconics.Builder.() -> Unit = {}) { Iconics.Builder().also(block).on(this).build() } /** Adaptation for [Iconics.Builder] with auto-executing [Iconics.BuilderView.build] */ fun Button.buildIconics(block: Iconics.Builder.() -> Unit = {}) { Iconics.Builder().also(block).on(this).build() } /** Adaptation for [IconicsArrayBuilder] with auto-executing [IconicsArrayBuilder.build] */ fun IconicsDrawable.createArray( block: IconicsArrayBuilder.() -> IconicsArrayBuilder ): Array<IconicsDrawable> { val builder = IconicsArrayBuilder(this) return block(builder).build() } /** * Uses the styleable tags to get the iconics data of menu items. Useful for set icons into * `BottomNavigationView` * * * By default, menus don't show icons for sub menus, but this can be enabled via reflection * So use this function if you want that sub menu icons are checked as well */ @JvmOverloads fun Menu.parseXmlAndSetIconicsDrawables( context: Context, @MenuRes menuId: Int, checkSubMenu: Boolean = false ) { IconicsMenuInflaterUtil.parseXmlAndSetIconicsDrawables(context, menuId, this, checkSubMenu) } /** Returns icon prefix (first 3 chars) */ val String.iconPrefix get() = substring(0, 3) /** Returns cleared icon name (all hyphens are replaced with underscores) */ val String.clearedIconName get() = (this as CharSequence).clearedIconName /** Returns cleared icon name (all hyphens are replaced with underscores) */ val CharSequence.clearedIconName: String get() = replace("-".toRegex(), "_") fun View.enableShadowSupport() { IconicsUtils.enableShadowSupport(this) }
apache-2.0
535eb2026f027ce74b1ad94d446dce4c
35.147059
95
0.755849
4.226139
false
false
false
false
mikepenz/Android-Iconics
iconics-views/src/main/java/com/mikepenz/iconics/view/IconicsImageView.kt
1
1491
/* * Copyright (c) 2019 Mike Penz * * 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.mikepenz.iconics.view import android.content.Context import android.util.AttributeSet import android.widget.ImageView import androidx.appcompat.widget.AppCompatImageView import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.animation.tryToEnableIconicsAnimation import com.mikepenz.iconics.internal.IconicsViewsAttrsApplier open class IconicsImageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : AppCompatImageView(context, attrs, defStyle) { var icon: IconicsDrawable? get() = drawable as? IconicsDrawable set(icon) = setImageDrawable(tryToEnableIconicsAnimation(icon)) init { //set the scale type for this view scaleType = ImageView.ScaleType.CENTER_INSIDE icon = IconicsViewsAttrsApplier.getIconicsImageViewDrawable(context, attrs) } }
apache-2.0
7578d807056a7ce25f5ea3d2aa5effa5
33.674419
83
0.755198
4.504532
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/RHRE3Application.kt
2
29733
package io.github.chrislo27.rhre3 import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.Preferences import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Graphics import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Colors import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator import com.badlogic.gdx.math.Matrix4 import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.analytics.AnalyticsHandler import io.github.chrislo27.rhre3.discord.DiscordHelper import io.github.chrislo27.rhre3.discord.PresenceState import io.github.chrislo27.rhre3.init.DefaultAssetLoader import io.github.chrislo27.rhre3.lc.LC import io.github.chrislo27.rhre3.midi.MidiHandler import io.github.chrislo27.rhre3.modding.ModdingGame import io.github.chrislo27.rhre3.modding.ModdingUtils import io.github.chrislo27.rhre3.news.ThumbnailFetcher import io.github.chrislo27.rhre3.patternstorage.PatternStorage import io.github.chrislo27.rhre3.playalong.Playalong import io.github.chrislo27.rhre3.screen.* import io.github.chrislo27.rhre3.screen.info.InfoScreen import io.github.chrislo27.rhre3.sfxdb.GameMetadata import io.github.chrislo27.rhre3.sfxdb.SFXDatabase import io.github.chrislo27.rhre3.soundsystem.BeadsSoundSystem import io.github.chrislo27.rhre3.soundsystem.SoundCache import io.github.chrislo27.rhre3.soundsystem.SoundStretch import io.github.chrislo27.rhre3.stage.GenericStage import io.github.chrislo27.rhre3.stage.LoadingIcon import io.github.chrislo27.rhre3.stage.bg.Background import io.github.chrislo27.rhre3.theme.LoadedThemes import io.github.chrislo27.rhre3.theme.Themes import io.github.chrislo27.rhre3.track.Remix import io.github.chrislo27.rhre3.util.JsonHandler import io.github.chrislo27.rhre3.util.ReleaseObject import io.github.chrislo27.rhre3.util.Semitones import io.github.chrislo27.toolboks.ResizeAction import io.github.chrislo27.toolboks.Toolboks import io.github.chrislo27.toolboks.ToolboksGame import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.font.FreeTypeFont import io.github.chrislo27.toolboks.i18n.Localization import io.github.chrislo27.toolboks.logging.Logger import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.registry.ScreenRegistry import io.github.chrislo27.toolboks.transition.TransitionScreen import io.github.chrislo27.toolboks.ui.UIPalette import io.github.chrislo27.toolboks.util.CloseListener import io.github.chrislo27.toolboks.util.MathHelper import io.github.chrislo27.toolboks.util.gdxutils.* import io.github.chrislo27.toolboks.version.Version import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.asynchttpclient.AsyncHttpClient import org.asynchttpclient.DefaultAsyncHttpClientConfig import org.asynchttpclient.Dsl.asyncHttpClient import org.lwjgl.glfw.GLFW import java.io.File import java.io.PrintWriter import java.io.StringWriter import java.util.* import javax.sound.sampled.AudioSystem import javax.sound.sampled.Mixer import kotlin.concurrent.thread import kotlin.system.measureNanoTime class RHRE3Application(logger: Logger, logToFile: File?) : ToolboksGame(logger, logToFile, RHRE3.VERSION, RHRE3.DEFAULT_SIZE, ResizeAction.KEEP_ASPECT_RATIO, RHRE3.MINIMUM_SIZE), CloseListener { companion object { lateinit var instance: RHRE3Application private set var disableCloseWarning: Boolean = false val httpClient: AsyncHttpClient = asyncHttpClient(DefaultAsyncHttpClientConfig.Builder() .setThreadFactory { Thread(it).apply { isDaemon = true } } .setFollowRedirect(true) .setCompressionEnforced(true)) private val TMP_MATRIX = Matrix4() private const val RAINBOW_STR = "RAINBOW" init { Colors.put("X", Color.CLEAR) Colors.put("PICOSONG", Color.valueOf("26AB57")) } } override var targetFramerate: Int get() = RHRE3.targetFramerate set(value) { RHRE3.targetFramerate = value } val defaultFontLargeKey = "default_font_large" val defaultFontMediumKey = "default_font_medium" val defaultBorderedFontLargeKey = "default_bordered_font_large" val timeSignatureFontKey = "time_signature" val defaultFontFTF: FreeTypeFont get() = fonts[defaultFontKey] val defaultBorderedFontFTF: FreeTypeFont get() = fonts[defaultBorderedFontKey] val defaultFontLargeFTF: FreeTypeFont get() = fonts[defaultFontLargeKey] val defaultFontMediumFTF: FreeTypeFont get() = fonts[defaultFontMediumKey] val defaultBorderedFontLargeFTF: FreeTypeFont get() = fonts[defaultBorderedFontLargeKey] val timeSignatureFontFTF: FreeTypeFont get() = fonts[timeSignatureFontKey] val defaultFontLarge: BitmapFont get() = defaultFontLargeFTF.font!! val defaultFontMedium: BitmapFont get() = defaultFontMediumFTF.font!! val defaultBorderedFontLarge: BitmapFont get() = defaultBorderedFontLargeFTF.font!! val timeSignatureFont: BitmapFont get() = timeSignatureFontFTF.font!! private val fontFileHandle: FileHandle by lazy { Gdx.files.internal("fonts/rodin_lat_cy_ja_ko_spec.ttf") } private val fontAfterLoadFunction: FreeTypeFont.() -> Unit = { this.font!!.apply { setFixedWidthGlyphs("1234567890") data.setLineHeight(lineHeight * 0.9f) setUseIntegerPositions(true) data.markupEnabled = true data.missingGlyph = data.getGlyph('☒') } } val uiPalette: UIPalette by lazy { UIPalette(defaultFontFTF, defaultFontLargeFTF, 1f, Color(1f, 1f, 1f, 1f), Color(0f, 0f, 0f, 0.75f), Color(0.25f, 0.25f, 0.25f, 0.75f), Color(0f, 0.5f, 0.5f, 0.75f)) } @Volatile lateinit var preferences: Preferences private set var versionTextWidth: Float = -1f private set @Volatile var githubVersion: Version = Version.RETRIEVING private set var secondsElapsed: Float = 0f private set @Volatile var liveUsers: Int = -1 private set val settings: Settings = Settings(this) private var lastWindowed: Pair<Int, Int> = RHRE3.DEFAULT_SIZE.copy() private val rainbowColor: Color = Color(1f, 1f, 1f, 1f) lateinit var hueBar: Texture private set override val programLaunchArguments: List<String> get() = RHRE3.launchArguments override fun getTitle(): String = "${RHRE3.TITLE} $versionString" override fun create() { super.create() Toolboks.LOGGER.info("${RHRE3.TITLE} $versionString is starting...") if (RHRE3.portableMode) { Toolboks.LOGGER.info("Running in portable mode") } val javaVersion = System.getProperty("java.version").trim() Toolboks.LOGGER.info("Running on JRE $javaVersion") instance = this val windowHandle = (Gdx.graphics as Lwjgl3Graphics).window.windowHandle GLFW.glfwSetWindowAspectRatio(windowHandle, 16, 9) // localization stuff run { Localization.loadBundlesFromLangFile() if (RHRE3.logMissingLocalizations) { Localization.logMissingLocalizations() } } // font stuff run { fonts[defaultFontLargeKey] = createDefaultLargeFont() fonts[defaultFontMediumKey] = createDefaultMediumFont() fonts[defaultBorderedFontLargeKey] = createDefaultLargeBorderedFont() fonts[timeSignatureFontKey] = FreeTypeFont(fontFileHandle, emulatedSize, createDefaultTTFParameter().apply { size *= 6 characters = "0123456789-" incremental = false }).setAfterLoad { this.font!!.apply { setFixedWidthGlyphs("0123456789") } } fonts.loadUnloaded(defaultCamera.viewportWidth, defaultCamera.viewportHeight) Toolboks.LOGGER.info("Loaded fonts (initial)") } // Copy over SoundStretch executables RHRE3.SOUNDSTRETCH_FOLDER.mkdirs() val currentOS = SoundStretch.currentOS if (currentOS != SoundStretch.OS.UNSUPPORTED) { Gdx.files.internal("soundstretch/${currentOS.executableName}").copyTo(RHRE3.SOUNDSTRETCH_FOLDER) RHRE3.SOUNDSTRETCH_FOLDER.child(currentOS.executableName).file().apply { setReadable(true) setExecutable(true) } Toolboks.LOGGER.info("Copied SoundStretch executables successfully") } // Generate hue bar run { val pixmap = Pixmap(360, 1, Pixmap.Format.RGBA8888) val tmpColor = Color(1f, 1f, 1f, 1f) for (i in 0 until 360) { tmpColor.fromHsv(i.toFloat(), 1f, 1f) pixmap.setColor(tmpColor) pixmap.drawPixel(i, 0) } hueBar = Texture(pixmap).apply { this.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear) } Toolboks.LOGGER.info("Generated hue bar texture") } // preferences preferences = Gdx.app.getPreferences("RHRE3") Toolboks.LOGGER.info("Loaded preferences") GlobalScope.launch { Toolboks.LOGGER.info("Starting analytics") val nano = measureNanoTime { AnalyticsHandler.initAndIdentify(Gdx.app.getPreferences("RHRE3-analytics")) } Toolboks.LOGGER.info("Analytics started successfully in ${nano / 1000000.0} ms") } GameMetadata.setPreferencesInstance(preferences) val lastVersion = Version.fromStringOrNull(preferences.getString(PreferenceKeys.LAST_VERSION, null) ?: "") if (lastVersion != RHRE3.VERSION) { preferences.putInteger(PreferenceKeys.TIMES_SKIPPED_UPDATE, 0) } settings.load() Toolboks.LOGGER.info("Loaded settings instance") val backgroundPref = preferences.getString(PreferenceKeys.BACKGROUND, Background.defaultBackground.id) GenericStage.backgroundImpl = Background.backgroundMap[backgroundPref] ?: Background.defaultBackground Toolboks.LOGGER.info("Set background pref") ModdingUtils.currentGame = ModdingGame.VALUES.find { it.id == preferences.getString(PreferenceKeys.ADVOPT_REF_RH_GAME, ModdingGame.DEFAULT_GAME.id) } ?: ModdingGame.DEFAULT_GAME Toolboks.LOGGER.info("Set modding utils current game") LoadingIcon.usePaddlerAnimation = preferences.getBoolean(PreferenceKeys.PADDLER_LOADING_ICON, false) Toolboks.LOGGER.info("Set loading icon pref") Semitones.pitchStyle = Semitones.PitchStyle.VALUES.find { it.name == preferences.getString(PreferenceKeys.ADVOPT_PITCH_STYLE, "") } ?: Semitones.pitchStyle Toolboks.LOGGER.info("Loaded semitones pitch style from prefs") val mixerName = preferences.getString(PreferenceKeys.SETTINGS_AUDIO_MIXER, "") val mixer: Mixer? = BeadsSoundSystem.supportedMixers.firstOrNull { it.mixerInfo.name == mixerName } BeadsSoundSystem.regenerateAudioContexts(mixer ?: BeadsSoundSystem.getDefaultMixer()) Toolboks.LOGGER.info("Loaded audio mixer from prefs: name=$mixerName, mixer found?=${mixer != null}") Toolboks.LOGGER.info("Loaded persistent data from preferences") val discordRpcEnabled = preferences.getBoolean(PreferenceKeys.SETTINGS_DISCORD_RPC_ENABLED, true) GlobalScope.launch { Toolboks.LOGGER.info("Starting Discord RPC") val nano = measureNanoTime { DiscordHelper.init(enabled = discordRpcEnabled) DiscordHelper.updatePresence(PresenceState.Loading) } Toolboks.LOGGER.info("Discord RPC started successfully in ${nano / 1000000.0} ms") } preferences.flush() // Asset registry AssetRegistry.addAssetLoader(DefaultAssetLoader()) // screens run { ScreenRegistry += "assetLoad" to AssetRegistryLoadingScreen(this) fun addOtherScreens() { ScreenRegistry += "databaseUpdate" to GitUpdateScreen(this) ScreenRegistry += "sfxdbLoad" to SFXDBLoadingScreen(this) ScreenRegistry += "editor" to EditorScreen(this) ScreenRegistry += "musicSelect" to MusicSelectScreen(this) ScreenRegistry += "info" to InfoScreen(this) ScreenRegistry += "newRemix" to NewRemixScreen(this) ScreenRegistry += "saveRemix" to SaveRemixScreen(this) ScreenRegistry += "openRemix" to OpenRemixScreen(this) ScreenRegistry += "recoverRemix" to RecoverRemixScreen(this) ScreenRegistry += "editorVersion" to EditorVersionScreen(this) ScreenRegistry += "news" to NewsScreen(this) ScreenRegistry += "partners" to PartnersScreen(this) ScreenRegistry += "advancedOptions" to AdvancedOptionsScreen(this) } val nextScreenLambda: (() -> ToolboksScreen<*, *>?) = nextScreenLambda@{ defaultCamera.viewportWidth = RHRE3.WIDTH.toFloat() defaultCamera.viewportHeight = RHRE3.HEIGHT.toFloat() defaultCamera.update() // Slower json parsing happens here Playalong.loadFromPrefs(preferences) Toolboks.LOGGER.info("Loaded playalong prefs") LoadedThemes.reloadThemes(preferences, true) PatternStorage.load() Toolboks.LOGGER.info("Loaded pattern storage") addOtherScreens() loadWindowSettings() dontShowResizeInfo = false val nextScreen = ScreenRegistry[if (RHRE3.skipGitScreen) "sfxdbLoad" else "databaseUpdate"] // if (preferences.getString(PreferenceKeys.LAST_VERSION, null) == null) { // Gdx.net.openURI("https://rhre.readthedocs.io/en/latest/") // } return@nextScreenLambda nextScreen } setScreen(ScreenRegistry.getNonNullAsType<AssetRegistryLoadingScreen>("assetLoad") .setNextScreen(nextScreenLambda)) RemixRecovery.addSelfToShutdownHooks() Toolboks.LOGGER.info( "Can recover last remix: ${RemixRecovery.canBeRecovered()}; Should recover: ${RemixRecovery.shouldBeRecovered()}") } thread(isDaemon = true, name = "Live User Count") { Thread.sleep(2500L) var failures = 0 fun failed() { failures++ this.liveUsers = -1 } do { try { val req = httpClient.prepareGet("https://api.rhre.dev:10443/rhre3/live") .addHeader("User-Agent", "RHRE ${RHRE3.VERSION}") .addHeader("X-Analytics-ID", AnalyticsHandler.getUUID()) .addHeader("X-D-ID", DiscordHelper.currentUser?.userId ?: "null") .addHeader("X-D-U", DiscordHelper.currentUser?.let { "${it.username}#${it.discriminator}" } ?: "null") .execute().get() if (req.statusCode == 200) { val liveUsers = req.responseBody?.trim()?.toIntOrNull() if (liveUsers != null) { failures = 0 if (!RHRE3.noOnlineCounter) this.liveUsers = liveUsers.coerceAtLeast(0) } else { Toolboks.LOGGER.warn("Got no integer for return value (got ${req.responseBody})") failed() } } else { Toolboks.LOGGER.warn("Request status code is not 200, got ${req.statusCode}") failed() } } catch (e: Exception) { e.printStackTrace() failed() } Thread.sleep(60_000L * (failures + 1)) } while (!Thread.interrupted() && !RHRE3.noOnlineCounter) if (RHRE3.noOnlineCounter) { this.liveUsers = 0 Toolboks.LOGGER.info("No online counter by request from launch args") } } GlobalScope.launch { try { fetchGithubVersion() val v = githubVersion if (!v.isUnknown) { if (v > RHRE3.VERSION) { preferences.putInteger(PreferenceKeys.TIMES_SKIPPED_UPDATE, preferences.getInteger(PreferenceKeys.TIMES_SKIPPED_UPDATE, 0) + 1) } else { preferences.putInteger(PreferenceKeys.TIMES_SKIPPED_UPDATE, 0) } } } catch (e: Exception) { e.printStackTrace() } } LC(this).all() } fun fetchGithubVersion() { githubVersion = Version.RETRIEVING val nano = System.nanoTime() val obj = JsonHandler.fromJson<ReleaseObject>(httpClient.prepareGet(RHRE3.RELEASE_API_URL).execute().get().responseBody) val ghVer = Version.fromStringOrNull(obj.tag_name!!) ?: Version.UNKNOWN githubVersion = ghVer Toolboks.LOGGER.info("Fetched editor version from GitHub in ${(System.nanoTime() - nano) / 1_000_000f} ms, is $githubVersion") } override fun exceptionHandler(t: Throwable) { val currentScreen = this.screen AnalyticsHandler.track("Render Crash", mapOf( "throwable" to t::class.java.canonicalName.take(1000), "stackTrace" to StringWriter().apply { val pw = PrintWriter(this) t.printStackTrace(pw) pw.flush() }.toString().take(1000), "currentScreen" to (currentScreen?.javaClass?.canonicalName ?: "null").take(1000) )) thread(start = true, isDaemon = true, name = "Crash Report Analytics Flusher") { AnalyticsHandler.flush() } if (currentScreen !is CrashScreen) { thread(start = true, isDaemon = true, name = "Crash Remix Recovery") { RemixRecovery.saveRemixInRecovery() } setScreen(CrashScreen(this, t, currentScreen)) } else { super.exceptionHandler(t) Gdx.app.exit() } } override fun preRender() { secondsElapsed += Gdx.graphics.deltaTime rainbowColor.fromHsv(MathHelper.getSawtoothWave(2f) * 360f, 0.8f, 0.8f) Colors.put(RAINBOW_STR, rainbowColor) super.preRender() } private var timeSinceResize: Float = 2f private var dontShowResizeInfo = true override fun postRender() { val screen = screen TMP_MATRIX.set(batch.projectionMatrix) batch.projectionMatrix = defaultCamera.combined batch.begin() if ((screen !is HidesVersionText || !screen.hidesVersionText) && screen !is TransitionScreen<*>) { val font = defaultBorderedFont font.data.setScale(0.5f) if (!githubVersion.isUnknown && githubVersion > RHRE3.VERSION) { font.color = Color.ORANGE } else { font.setColor(1f, 1f, 1f, 1f) } val layout = font.draw(batch, RHRE3.VERSION.toString(), 0f, (font.capHeight) + (2f / RHRE3.HEIGHT) * defaultCamera.viewportHeight, defaultCamera.viewportWidth, Align.right, false) versionTextWidth = layout.width font.setColor(1f, 1f, 1f, 1f) font.data.setScale(1f) } @Suppress("ConstantConditionIf") if (RHRE3.enableEarlyAccessMessage) { val font = defaultBorderedFont val height = 0.9f val alpha = if (defaultCamera.getInputY() / defaultCamera.viewportHeight in (height - font.capHeight / defaultCamera.viewportHeight)..(height)) 0.6f else 1f font.scaleMul(0.85f) font.setColor(1f, 1f, 1f, alpha) font.drawCompressed(batch, "Early-access version. Do not redistribute; do not publish video recordings. (Licensed to ${AnalyticsHandler.getUUID().takeUnless { it.isEmpty() }?.run { substring(24) }})", 0f, height * defaultCamera.viewportHeight, defaultCamera.viewportWidth, Align.center) font.setColor(1f, 1f, 1f, 1f) font.data.setScale(1f) } if (timeSinceResize < 1.5f && !dontShowResizeInfo) { val font = defaultBorderedFont font.setColor(1f, 1f, 1f, 1f) font.draw(batch, "${Gdx.graphics.width}x${Gdx.graphics.height}", 0f, defaultCamera.viewportHeight * 0.5f + font.capHeight, defaultCamera.viewportWidth, Align.center, false) } timeSinceResize += Gdx.graphics.deltaTime batch.end() batch.projectionMatrix = TMP_MATRIX super.postRender() } override fun dispose() { super.dispose() preferences.putString(PreferenceKeys.LAST_VERSION, RHRE3.VERSION.toString()) preferences.putString(PreferenceKeys.MIDI_NOTE, preferences.getString(PreferenceKeys.MIDI_NOTE, Remix.DEFAULT_MIDI_NOTE)) preferences.putString(PreferenceKeys.PLAYALONG_CONTROLS, JsonHandler.toJson(Playalong.playalongControls)) preferences.putString(PreferenceKeys.PLAYALONG_CONTROLLER_MAPPINGS, JsonHandler.toJson(Playalong.playalongControllerMappings)) preferences.flush() settings.persist() try { SFXDatabase.dispose() } catch (e: Exception) { e.printStackTrace() } Themes.dispose() ThumbnailFetcher.dispose() persistWindowSettings() RHRE3.tmpMusic.emptyDirectory() BeadsSoundSystem.dispose() AnalyticsHandler.track("Close Program", mapOf("durationSeconds" to ((System.currentTimeMillis() - startTimeMillis) / 1000L))) AnalyticsHandler.dispose() MidiHandler.dispose() SoundCache.unloadAll() httpClient.close() } override fun attemptClose(): Boolean { val screenRequestedStop = (screen as? CloseListener)?.attemptClose() == false return if (screenRequestedStop) { false } else { // Close warning only if the editor screen has been entered at least once and if the preferences say so if (!disableCloseWarning && EditorScreen.enteredEditor && preferences.getBoolean(PreferenceKeys.SETTINGS_CLOSE_WARNING, true) && this.screen !is CloseWarningScreen && this.screen !is CrashScreen && this.screen !is AutoUpdaterScreen) { Gdx.app.postRunnable { setScreen(CloseWarningScreen(this, this.screen)) } false } else { true } } } fun persistWindowSettings() { val isFullscreen = Gdx.graphics.isFullscreen if (isFullscreen) { preferences.putString(PreferenceKeys.WINDOW_STATE, "fs") } else { // preferences.putString(PreferenceKeys.WINDOW_STATE, // "${(Gdx.graphics.width / Display.getPixelScaleFactor()).toInt()}x${(Gdx.graphics.height / Display.getPixelScaleFactor()).toInt()}") // FIXME add pixel scale factor preferences.putString(PreferenceKeys.WINDOW_STATE, "${Gdx.graphics.width}x${Gdx.graphics.height}") } Toolboks.LOGGER.info("Persisting window settings as ${preferences.getString(PreferenceKeys.WINDOW_STATE)}") preferences.flush() } fun loadWindowSettings() { val str: String = preferences.getString(PreferenceKeys.WINDOW_STATE, "${RHRE3.WIDTH}x${RHRE3.HEIGHT}").toLowerCase(Locale.ROOT) if (str == "fs") { Gdx.graphics.setFullscreenMode(Gdx.graphics.displayMode) } else { val width: Int val height: Int if (!str.matches("\\d+x\\d+".toRegex())) { width = RHRE3.WIDTH height = RHRE3.HEIGHT } else { width = str.substringBefore('x').toIntOrNull()?.coerceAtLeast(160) ?: RHRE3.WIDTH height = str.substringAfter('x').toIntOrNull()?.coerceAtLeast(90) ?: RHRE3.HEIGHT } Gdx.graphics.setWindowedMode(width, height) } } fun attemptFullscreen() { lastWindowed = Gdx.graphics.width to Gdx.graphics.height Gdx.graphics.setFullscreenMode(Gdx.graphics.displayMode) } fun attemptEndFullscreen() { val last = lastWindowed Gdx.graphics.setWindowedMode(last.first, last.second) } fun attemptResetWindow() { Gdx.graphics.setWindowedMode(RHRE3.DEFAULT_SIZE.first, RHRE3.DEFAULT_SIZE.second) } override fun keyDown(keycode: Int): Boolean { val res = super.keyDown(keycode) if (!res) { if (!Gdx.input.isControlDown() && !Gdx.input.isAltDown()) { if (keycode == Input.Keys.F11) { if (!Gdx.input.isShiftDown()) { if (Gdx.graphics.isFullscreen) { attemptEndFullscreen() } else { attemptFullscreen() } } else { attemptResetWindow() } persistWindowSettings() return true } } } return res } override fun resize(width: Int, height: Int) { super.resize(width, height) if (!dontShowResizeInfo) timeSinceResize = 0f } private fun createDefaultTTFParameter(): FreeTypeFontGenerator.FreeTypeFontParameter { return FreeTypeFontGenerator.FreeTypeFontParameter().apply { magFilter = Texture.TextureFilter.Linear minFilter = Texture.TextureFilter.Linear genMipMaps = false incremental = true size = 24 color = Color(1f, 1f, 1f, 1f) borderColor = Color(0f, 0f, 0f, 1f) characters = "" hinting = FreeTypeFontGenerator.Hinting.AutoFull } } override fun createDefaultFont(): FreeTypeFont { return FreeTypeFont(fontFileHandle, emulatedSize, createDefaultTTFParameter()) .setAfterLoad(fontAfterLoadFunction) } override fun createDefaultBorderedFont(): FreeTypeFont { return FreeTypeFont(fontFileHandle, emulatedSize, createDefaultTTFParameter() .apply { borderWidth = 1.5f }) .setAfterLoad(fontAfterLoadFunction) } private fun createDefaultLargeFont(): FreeTypeFont { return FreeTypeFont(fontFileHandle, emulatedSize, createDefaultTTFParameter() .apply { size *= 4 borderWidth *= 4 }) .setAfterLoad(fontAfterLoadFunction) } private fun createDefaultMediumFont(): FreeTypeFont { return FreeTypeFont(fontFileHandle, emulatedSize, createDefaultTTFParameter() .apply { size *= 2 borderWidth *= 2 }) .setAfterLoad(fontAfterLoadFunction) } private fun createDefaultLargeBorderedFont(): FreeTypeFont { return FreeTypeFont(fontFileHandle, emulatedSize, createDefaultTTFParameter() .apply { borderWidth = 1.5f size *= 4 borderWidth *= 4 }) .setAfterLoad(fontAfterLoadFunction) } }
gpl-3.0
38c7dd1910a773123c3f80499d51d0c2
42.341108
246
0.597323
4.951041
false
false
false
false
ttomsu/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/admin/HydrateQueueCommandTest.kt
1
15239
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.admin import com.netflix.spinnaker.orca.TaskResolver import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.ORCHESTRATION import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.api.test.pipeline import com.netflix.spinnaker.orca.api.test.stage import com.netflix.spinnaker.orca.api.test.task import com.netflix.spinnaker.orca.ext.beforeStages import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository.ExecutionCriteria import com.netflix.spinnaker.orca.q.CompleteExecution import com.netflix.spinnaker.orca.q.CompleteStage import com.netflix.spinnaker.orca.q.DummyTask import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.StartStage import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.orca.q.handler.plan import com.netflix.spinnaker.orca.q.stageWithSyntheticAfter import com.netflix.spinnaker.orca.q.stageWithSyntheticBefore import com.netflix.spinnaker.q.Message import com.netflix.spinnaker.q.Queue import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.check import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.isA import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import com.nhaarman.mockito_kotlin.verifyZeroInteractions import com.nhaarman.mockito_kotlin.whenever import java.time.Instant import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.api.lifecycle.CachingMode import org.jetbrains.spek.subject.SubjectSpek import rx.Observable object HydrateQueueCommandTest : SubjectSpek<HydrateQueueCommand>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val taskResolver = TaskResolver(emptyList()) subject(CachingMode.GROUP) { HydrateQueueCommand(queue, repository, taskResolver) } fun resetMocks() = reset(queue, repository) describe("hydrating a queue with no valid executions") { given("no running executions") { beforeGroup { whenever(repository.retrieve(any(), any<ExecutionCriteria>())) doReturn Observable.empty() } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(dryRun = false)) it("does nothing") { verifyZeroInteractions(queue) } } } given("running executions outside time window filter") { val oldPipeline = pipeline { status = RUNNING application = "whatever" startTime = 1500001000 stage { refId = "1" type = "whatever" status = RUNNING } } val newPipeline = pipeline { status = RUNNING application = "whatever" startTime = 1500005000 stage { refId = "1" type = "whatever" status = RUNNING } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(oldPipeline, newPipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput( start = Instant.ofEpochMilli(1500002000), end = Instant.ofEpochMilli(1500004000), dryRun = false )) it("does nothing") { verifyZeroInteractions(queue) } } } given("running executions not matching execution id filter") { val pipeline = pipeline { id = "1" status = NOT_STARTED application = "whatever" stage { refId = "1" type = "whatever" status = RUNNING } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(executionId = "2", dryRun = false)) it("does nothing") { verifyZeroInteractions(queue) } } } } describe("hydrating a queue with running executions") { given("no running stages") { val pipeline = pipeline { status = RUNNING application = "whatever" stage { refId = "1" type = "whatever" status = NOT_STARTED } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(dryRun = false)) it("adds messages to the queue") { verify(queue, times(1)).push(check<StartStage> { assertThat(it.stageId).isEqualTo(pipeline.stageByRef("1").id) }) verifyNoMoreInteractions(queue) } } } given("all stages are complete") { val pipeline = pipeline { status = RUNNING application = "whatever" stage { refId = "1" type = "whatever" status = SUCCEEDED } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(dryRun = false)) it("adds messages to the queue") { verify(queue, times(1)).push(isA<CompleteExecution>()) verifyNoMoreInteractions(queue) } } } given("synthetic before stages") { val pipeline = pipeline { status = RUNNING application = "whatever" stage { refId = "1" type = stageWithSyntheticBefore.type status = RUNNING stageWithSyntheticBefore.plan(this) beforeStages().first().run { status = RUNNING task { id = "t1" implementingClass = DummyTask::class.java.name status = RUNNING } } } stage { refId = "2" type = stageWithSyntheticBefore.type status = NOT_STARTED stageWithSyntheticBefore.plan(this) } stage { refId = "3" type = "whatever" status = NOT_STARTED requisiteStageRefIds = listOf("1") } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(dryRun = false)) it("adds messages to the queue") { argumentCaptor<Message>().let { verify(queue, times(2)).push(it.capture()) assertType<RunTask>(it.firstValue) { assertThat(it.stageId).isEqualTo(pipeline.stageByRef("1<1").id) assertThat(it.taskId).isEqualTo(pipeline.stageByRef("1<1").tasks[0].id) } assertType<StartStage>(it.secondValue) { assertThat(it.stageId).isEqualTo(pipeline.stageByRef("2").id) } } verifyNoMoreInteractions(queue) } } } given("synthetic after stages") { val pipeline = pipeline { status = RUNNING application = "whatever" stage { refId = "1" type = stageWithSyntheticAfter.type status = RUNNING stageWithSyntheticAfter.plan(this) } } pipeline.stageByRef("1").tasks.first().status = SUCCEEDED beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(dryRun = false)) it("adds messages to the queue") { argumentCaptor<CompleteStage>().let { verify(queue, times(1)).push(it.capture()) assertThat(it.firstValue.stageId).isEqualTo(pipeline.stageByRef("1").id) } verifyNoMoreInteractions(queue) } } } given("stage task running") { val pipeline = pipeline { status = RUNNING application = "whatever" stage { refId = "1" type = "stage1" status = RUNNING task { id = "t1" implementingClass = DummyTask::class.java.name status = SUCCEEDED } task { id = "t2" implementingClass = DummyTask::class.java.name status = RUNNING } } stage { refId = "2" type = "stage2" status = NOT_STARTED task { id = "t1" implementingClass = DummyTask::class.java.name status = NOT_STARTED } } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(dryRun = false)) it("adds messages to the queue") { argumentCaptor<Message>().let { verify(queue, times(2)).push(it.capture()) assertType<RunTask>(it.firstValue) { assertThat(it.stageId).isEqualTo(pipeline.stageByRef("1").id) assertThat(it.taskId).isEqualTo(pipeline.stageByRef("1").taskById("t2").id) } assertType<StartStage>(it.secondValue) { assertThat(it.stageId).isEqualTo(pipeline.stageByRef("2").id) } } verifyNoMoreInteractions(queue) } } } given("stage task not started") { val pipeline = pipeline { status = RUNNING application = "whatever" stage { refId = "1" type = "" status = RUNNING task { id = "t1" status = NOT_STARTED } } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(dryRun = false)) it("adds messages to the queue") { verify(queue, times(1)).push(check<StartTask> { assertThat(it.stageId).isEqualTo(pipeline.stageByRef("1").id) assertThat(it.taskId).isEqualTo(pipeline.stageByRef("1").taskById("t1").id) }) verifyNoMoreInteractions(queue) } } } given("stage tasks complete") { val pipeline = pipeline { status = RUNNING application = "whatever" stage { refId = "1" type = "whatever" status = RUNNING task { id = "t1" status = SUCCEEDED } } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { subject.invoke(HydrateQueueInput(dryRun = false)) it("adds messages to the queue") { verify(queue, times(1)).push(check<CompleteStage> { assertThat(it.stageId).isEqualTo(pipeline.stageByRef("1").id) }) verifyNoMoreInteractions(queue) } } } } describe("dry running hydration") { given("running executions") { val pipeline = pipeline { status = RUNNING application = "whatever" stage { refId = "1" type = "whatever" status = NOT_STARTED } } beforeGroup { whenever(repository.retrieve(eq(ORCHESTRATION), any<ExecutionCriteria>())) doReturn Observable.empty() whenever(repository.retrieve(eq(PIPELINE), any<ExecutionCriteria>())) doReturn Observable.just(pipeline) } afterGroup(::resetMocks) on("invoking") { val output = subject.invoke(HydrateQueueInput(dryRun = true)) it("does not interact with queue") { verifyZeroInteractions(queue) } it("emits dry run output") { assertThat(output.dryRun).isTrue() assertThat(output.executions).isNotEmpty assertThat(output.executions[pipeline.id]!!.actions).hasOnlyOneElementSatisfying { assertThat(it.message).isNotNull() assertThat(it.message).isInstanceOf(StartStage::class.java) assertThat(it.description).contains("Stage is not started") } } } } } }) private inline fun <reified T> assertType(subject: Any, assertions: (T) -> Unit) { assertThat(subject).isInstanceOf(T::class.java) if (subject is T) { assertions(subject) } }
apache-2.0
a3b5eb9abe578380f46ea876d7ca383d
30.681913
128
0.624516
4.763676
false
false
false
false
square/okio
okio/src/commonTest/kotlin/okio/util.kt
1
2809
/* * Copyright (C) 2019 Square, 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 okio import kotlin.random.Random fun segmentSizes(buffer: Buffer): List<Int> { var segment = buffer.head ?: return emptyList() val sizes = mutableListOf(segment.limit - segment.pos) segment = segment.next!! while (segment !== buffer.head) { sizes.add(segment.limit - segment.pos) segment = segment.next!! } return sizes } fun bufferWithRandomSegmentLayout(dice: Random, data: ByteArray): Buffer { val result = Buffer() // Writing to result directly will yield packed segments. Instead, write to // other buffers, then write those buffers to result. var pos = 0 var byteCount: Int while (pos < data.size) { byteCount = Segment.SIZE / 2 + dice.nextInt(Segment.SIZE / 2) if (byteCount > data.size - pos) byteCount = data.size - pos val offset = dice.nextInt(Segment.SIZE - byteCount) val segment = Buffer() segment.write(ByteArray(offset)) segment.write(data, pos, byteCount) segment.skip(offset.toLong()) result.write(segment, byteCount.toLong()) pos += byteCount } return result } fun bufferWithSegments(vararg segments: String): Buffer { val result = Buffer() for (s in segments) { val offsetInSegment = if (s.length < Segment.SIZE) (Segment.SIZE - s.length) / 2 else 0 val buffer = Buffer() buffer.writeUtf8('_'.repeat(offsetInSegment)) buffer.writeUtf8(s) buffer.skip(offsetInSegment.toLong()) result.write(buffer.copyTo(Buffer()), buffer.size) } return result } fun makeSegments(source: ByteString): ByteString { val buffer = Buffer() for (i in 0 until source.size) { val segment = buffer.writableSegment(Segment.SIZE) segment.data[segment.pos] = source[i] segment.limit++ buffer.size++ } return buffer.snapshot() } /** * Returns a string with all '\' slashes replaced with '/' slashes. This is useful for test * assertions that intend to ignore slashes. */ fun Path.withUnixSlashes(): String { return toString().replace('\\', '/') } expect fun assertRelativeTo( a: Path, b: Path, bRelativeToA: Path, sameAsNio: Boolean = true, ) expect fun assertRelativeToFails( a: Path, b: Path, sameAsNio: Boolean = true, ): IllegalArgumentException
apache-2.0
bab228759249e177ce4a69bd64b7dcd1
27.373737
91
0.697401
3.842681
false
false
false
false
allotria/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt
1
13223
// 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. @file:Suppress("HardCodedStringLiteral") package org.jetbrains.builtInWebServer import com.github.benmanes.caffeine.cache.Caffeine import com.google.common.net.InetAddresses import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationType import com.intellij.notification.SingletonNotificationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.ide.SpecialConfigFiles.USER_WEB_TOKEN import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.endsWithName import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.io.* import com.intellij.util.io.DigestUtil.randomToken import com.intellij.util.net.NetUtils import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.* import io.netty.handler.codec.http.cookie.DefaultCookie import io.netty.handler.codec.http.cookie.ServerCookieDecoder import io.netty.handler.codec.http.cookie.ServerCookieEncoder import org.jetbrains.ide.BuiltInServerBundle import org.jetbrains.ide.BuiltInServerManagerImpl import org.jetbrains.ide.HttpRequestHandler import org.jetbrains.ide.orInSafeMode import org.jetbrains.io.send import java.awt.datatransfer.StringSelection import java.io.IOException import java.net.InetAddress import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.attribute.PosixFileAttributeView import java.nio.file.attribute.PosixFilePermission import java.util.* import java.util.concurrent.TimeUnit import javax.swing.SwingUtilities internal val LOG = logger<BuiltInWebServer>() private val notificationManager by lazy { SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP.value, NotificationType.INFORMATION, null) } class BuiltInWebServer : HttpRequestHandler() { override fun isAccessible(request: HttpRequest): Boolean { return BuiltInServerOptions.getInstance().builtInServerAvailableExternally || request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true) } override fun isSupported(request: FullHttpRequest): Boolean = super.isSupported(request) || request.method() == HttpMethod.POST override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean { var hostName = getHostName(request) ?: return false val projectName: String? val isIpv6 = hostName[0] == '[' && hostName.length > 2 && hostName[hostName.length - 1] == ']' if (isIpv6) { hostName = hostName.substring(1, hostName.length - 1) } if (isIpv6 || InetAddresses.isInetAddress(hostName) || isOwnHostName(hostName) || hostName.endsWith(".ngrok.io")) { if (urlDecoder.path().length < 2) { return false } projectName = null } else { if (hostName.endsWith(".localhost")) { projectName = hostName.substring(0, hostName.lastIndexOf('.')) } else { projectName = hostName } } return doProcess(urlDecoder, request, context, projectName) } } internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false) const val TOKEN_PARAM_NAME = "_ijt" const val TOKEN_HEADER_NAME = "x-ijt" private val STANDARD_COOKIE by lazy { val productName = ApplicationNamesInfo.getInstance().lowercaseProductName val configPath = PathManager.getConfigPath() val file = Paths.get(configPath, USER_WEB_TOKEN) var token: String? = null if (file.exists()) { try { token = UUID.fromString(file.readText()).toString() } catch (e: Exception) { LOG.warn(e) } } if (token == null) { token = UUID.randomUUID().toString() file.write(token!!) Files.getFileAttributeView(file, PosixFileAttributeView::class.java) ?.setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)) } // explicit setting domain cookie on localhost doesn't work for chrome // http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!) cookie.isHttpOnly = true cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10)) cookie.setPath("/") cookie } // expire after access because we reuse tokens private val tokens = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>() fun acquireToken(): String { var token = tokens.asMap().keys.firstOrNull() if (token == null) { token = randomToken() tokens.put(token, java.lang.Boolean.TRUE) } return token } private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean { val decodedPath = urlDecoder.path() var offset: Int var isEmptyPath: Boolean val isCustomHost = projectNameAsHost != null var projectName: String if (isCustomHost) { projectName = projectNameAsHost!! // host mapped to us offset = 0 isEmptyPath = decodedPath.isEmpty() } else { offset = decodedPath.indexOf('/', 1) projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset) isEmptyPath = offset == -1 } var candidateByDirectoryName: Project? = null val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean { if (project.isDisposed) { return false } val name = project.name if (isCustomHost) { // domain name is case-insensitive if (projectName.equals(name, ignoreCase = true)) { if (!SystemInfo.isFileSystemCaseSensitive) { // may be passed path is not correct projectName = name } return true } } else { // WEB-17839 Internal web server reports 404 when serving files from project with slashes in name if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfo.isFileSystemCaseSensitive)) { val isEmptyPathCandidate = decodedPath.length == (name.length + 1) if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') { projectName = name offset = name.length + 1 isEmptyPath = isEmptyPathCandidate return true } } } if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) { candidateByDirectoryName = project } return false }) ?: candidateByDirectoryName ?: return false if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) { notificationManager.notify(BuiltInServerBundle.message("notification.content.built.in.web.server.is.deactivated"), null) return false } if (isEmptyPath) { // we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work redirectToDirectory(request, context.channel(), projectName, null) return true } val path = toIdeaPath(decodedPath, offset) if (path == null) { HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request) return true } for (pathHandler in WebServerPathHandler.EP_NAME.extensionList) { LOG.runAndLogException { if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) { return true } } } return false } fun HttpRequest.isSignedRequest(): Boolean { if (BuiltInServerOptions.getInstance().allowUnsignedRequests) { return true } // we must check referrer - if html cached, browser will send request without query val token = headers().get(TOKEN_HEADER_NAME) ?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() ?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() } // we don't invalidate token - allow to make subsequent requests using it (it is required for our javadoc DocumentationComponent) return token != null && tokens.getIfPresent(token) != null } fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean): HttpHeaders? { if (BuiltInServerOptions.getInstance().allowUnsignedRequests) { return EmptyHttpHeaders.INSTANCE } request.headers().get(HttpHeaderNames.COOKIE)?.let { for (cookie in ServerCookieDecoder.STRICT.decode(it)) { if (cookie.name() == STANDARD_COOKIE.name()) { if (cookie.value() == STANDARD_COOKIE.value()) { return EmptyHttpHeaders.INSTANCE } break } } } if (isSignedRequest) { return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict") } val urlDecoder = QueryStringDecoder(request.uri()) if (!urlDecoder.path().endsWith("/favicon.ico")) { val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}" SwingUtilities.invokeAndWait { ProjectUtil.focusProjectWindow(null, true) if (MessageDialogBuilder .yesNo("", BuiltInServerBundle.message("dialog.message.page", StringUtil.trimMiddle(url, 50))) .icon(Messages.getWarningIcon()) .yesText(BuiltInServerBundle.message("dialog.button.copy.authorization.url.to.clipboard")) .guessWindowAndAsk()) { CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken())) } } } HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return null } private fun toIdeaPath(decodedPath: String, offset: Int): String? { // must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize val path = decodedPath.substring(offset) if (!path.startsWith('/')) { return null } return FileUtil.toCanonicalPath(path, '/').substring(1) } fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean { val basePath = project.basePath return basePath != null && endsWithName(basePath, projectName) } fun findIndexFile(basedir: VirtualFile): VirtualFile? { val children = basedir.children if (children == null || children.isEmpty()) { return null } for (indexNamePrefix in arrayOf("index.", "default.")) { var index: VirtualFile? = null val preferredName = indexNamePrefix + "html" for (child in children) { if (!child.isDirectory) { val name = child.name //noinspection IfStatementWithIdenticalBranches if (name == preferredName) { return child } else if (index == null && name.startsWith(indexNamePrefix)) { index = child } } } if (index != null) { return index } } return null } fun findIndexFile(basedir: Path): Path? { val children = basedir.directoryStreamIfExists({ val name = it.fileName.toString() name.startsWith("index.") || name.startsWith("default.") }) { it.toList() } ?: return null for (indexNamePrefix in arrayOf("index.", "default.")) { var index: Path? = null val preferredName = "${indexNamePrefix}html" for (child in children) { if (!child.isDirectory()) { val name = child.fileName.toString() if (name == preferredName) { return child } else if (index == null && name.startsWith(indexNamePrefix)) { index = child } } } if (index != null) { return index } } return null } // is host loopback/any or network interface address (i.e. not custom domain) // must be not used to check is host on local machine internal fun isOwnHostName(host: String): Boolean { if (NetUtils.isLocalhost(host)) { return true } try { val address = InetAddress.getByName(host) if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) { return true } val localHostName = InetAddress.getLocalHost().hostName // WEB-8889 // develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name) return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true)) } catch (ignored: IOException) { return false } }
apache-2.0
7c0567e5b6570ce0c5a4991edcc9cbb8
35.131148
165
0.715193
4.537749
false
false
false
false
Raizlabs/DBFlow
paging/src/main/kotlin/com/dbflow5/paging/QueryDataSource.kt
1
3626
package com.dbflow5.paging import androidx.paging.DataSource import androidx.paging.PositionalDataSource import com.dbflow5.config.DBFlowDatabase import com.dbflow5.config.FlowManager import com.dbflow5.observing.OnTableChangedObserver import com.dbflow5.query.ModelQueriable import com.dbflow5.query.Select import com.dbflow5.query.Transformable import com.dbflow5.query.WhereBase import com.dbflow5.query.extractFrom import com.dbflow5.query.selectCountOf /** * Bridges the [ModelQueriable] into a [PositionalDataSource] that loads a [ModelQueriable]. */ class QueryDataSource<T : Any, TQuery> internal constructor(private val transformable: TQuery, private val database: DBFlowDatabase) : PositionalDataSource<T>() where TQuery : Transformable<T>, TQuery : ModelQueriable<T> { private val associatedTables: Set<Class<*>> = transformable.extractFrom()?.associatedTables ?: setOf(transformable.table) private val onTableChangedObserver = object : OnTableChangedObserver(associatedTables.toList()) { override fun onChanged(tables: Set<Class<*>>) { if (tables.isNotEmpty()) { invalidate() } } } init { if (transformable is WhereBase<*> && transformable.queryBuilderBase !is Select) { throw IllegalArgumentException("Cannot pass a non-SELECT cursor into this data source.") } val db = FlowManager.getDatabaseForTable(associatedTables.first()) // force initialize the db db.writableDatabase val observer = db.tableObserver // From could be part of many joins, so we register for all affected tables here. observer.addOnTableChangedObserver(onTableChangedObserver) } override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<T>) { database.beginTransactionAsync { db -> transformable.constrain(params.startPosition.toLong(), params.loadSize.toLong()) .queryList(db) }.execute { _, list -> callback.onResult(list) } } override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<T>) { database.beginTransactionAsync { db -> selectCountOf().from(transformable).longValue(db) } .execute { _, count -> val max = when { params.requestedLoadSize >= count - 1 -> count.toInt() else -> params.requestedLoadSize } database.beginTransactionAsync { db -> transformable.constrain(params.requestedStartPosition.toLong(), max.toLong()).queryList(db) }.execute { _, list -> callback.onResult(list, params.requestedStartPosition, count.toInt()) } } } class Factory<T : Any, TQuery> internal constructor(private val transformable: TQuery, private val database: DBFlowDatabase) : DataSource.Factory<Int, T>() where TQuery : Transformable<T>, TQuery : ModelQueriable<T> { override fun create(): DataSource<Int, T> = QueryDataSource(transformable, database) } companion object { @JvmStatic fun <T : Any, TQuery> newFactory(transformable: TQuery, database: DBFlowDatabase) where TQuery : Transformable<T>, TQuery : ModelQueriable<T> = Factory(transformable, database) } } fun <T : Any, TQuery> TQuery.toDataSourceFactory(database: DBFlowDatabase) where TQuery : Transformable<T>, TQuery : ModelQueriable<T> = QueryDataSource.newFactory(this, database)
mit
433d6acb5cbb4a2ede9671c61a647ac2
40.215909
111
0.669057
5.036111
false
false
false
false
leafclick/intellij-community
plugins/git4idea/tests/git4idea/tests/GitDirtyScopeTest.kt
1
5554
// 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 git4idea.tests import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vcs.BaseChangeListsTest import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vcs.changes.VcsDirtyScopeVfsListener import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.DocumentUtil import com.intellij.vcsUtil.VcsUtil import git4idea.test.GitSingleRepoTest import git4idea.test.commit import org.junit.Assume.assumeFalse class GitDirtyScopeTest : GitSingleRepoTest() { private lateinit var dirtyScopeManager: VcsDirtyScopeManager private lateinit var fileDocumentManager: FileDocumentManager private lateinit var undoManager: UndoManager override fun setUp() { super.setUp() dirtyScopeManager = VcsDirtyScopeManager.getInstance(project) fileDocumentManager = FileDocumentManager.getInstance() undoManager = UndoManager.getInstance(project) } fun testRevertingUnsavedChanges() { val file = repo.root.createFile("file.txt", "initial") git("add .") commit("initial") dirtyScopeManager.markEverythingDirty() changeListManager.waitUntilRefreshed() editDocument(file, "new content") changeListManager.waitUntilRefreshed() assertChanges { modified("file.txt") } editDocument(file, "initial") changeListManager.waitUntilRefreshed() assertChanges { modified("file.txt") } saveDocument(file) // Usually, should be triggered by LST changeListManager.waitUntilRefreshed() assertNoChanges() } fun testUndoingUnsavedChanges() { val file = repo.root.createFile("file.txt", "initial") git("add .") commit("initial") dirtyScopeManager.markEverythingDirty() changeListManager.waitUntilRefreshed() editDocument(file, "new content") changeListManager.waitUntilRefreshed() assertChanges { modified("file.txt") } undoChanges(file) changeListManager.waitUntilRefreshed() assertNoChanges() editDocument(file, "new content") changeListManager.waitUntilRefreshed() assertChanges { modified("file.txt") } } fun testTypingDoesNotMarkDirty() { val file = repo.root.createFile("file.txt", "initial") git("add .") commit("initial") dirtyScopeManager.markEverythingDirty() changeListManager.waitUntilRefreshed() editDocument(file, "new content") changeListManager.waitUntilRefreshed() assertChanges { modified("file.txt") } assertFalse(isDirtyPath(file)) editDocument(file, "new better content") assertFalse(isDirtyPath(file)) } fun testEmptyBulkModeDoesNotMarkDirty() { val file = repo.root.createFile("file.txt", "initial") git("add .") commit("initial") dirtyScopeManager.markEverythingDirty() changeListManager.waitUntilRefreshed() editDocument(file, "new content") saveDocument(file) changeListManager.waitUntilRefreshed() assertChanges { modified("file.txt") } assertFalse(isDirtyPath(file)) writeAction { DocumentUtil.executeInBulk(file.document, true) { // do nothing } } assertFalse(isDirtyPath(file)) } fun testCaseOnlyRename() { assumeFalse(SystemInfo.isFileSystemCaseSensitive) val file = repo.root.createFile("file.txt", "initial") git("add .") commit("initial") editDocument(file, "initial") saveDocument(file) dirtyScopeManager.markEverythingDirty() changeListManager.waitUntilRefreshed() changeListManager.forceStopInTestMode() writeAction { val parent = file.parent file.delete(this) parent.createFile("FILE.txt", "initial") } git("add .") VcsDirtyScopeVfsListener.getInstance(project).waitForAsyncTaskCompletion() changeListManager.forceGoInTestMode() changeListManager.waitUntilRefreshed() assertChanges { rename("file.txt", "FILE.txt") } assertFalse(isDirtyPath(file)) } private fun editDocument(file: VirtualFile, newContent: String) { runInEdtAndWait { WriteCommandAction.runWriteCommandAction(project) { val document = file.document document.replaceString(0, document.textLength, newContent) } } } private fun undoChanges(file: VirtualFile) { runInEdtAndWait { val fileEditor = BaseChangeListsTest.createMockFileEditor(file.document) undoManager.undo(fileEditor) } } private fun saveDocument(file: VirtualFile) { runInEdtAndWait { fileDocumentManager.saveDocument(file.document) } } private fun writeAction(task: () -> Unit) { runInEdtAndWait { WriteCommandAction.runWriteCommandAction(project) { task() } } } private fun isDirtyPath(file: VirtualFile): Boolean { return isDirtyPath(VcsUtil.getFilePath(file)) } private fun isDirtyPath(filePath: FilePath): Boolean { val dirtyPaths = dirtyScopeManager.whatFilesDirty(listOf(filePath)) return dirtyPaths.contains(filePath) } private val VirtualFile.document: Document get() = fileDocumentManager.getDocument(this)!! }
apache-2.0
7ecf540385505a0d0d02a4db22bfb2d4
26.097561
140
0.727044
4.936889
false
true
false
false
leafclick/intellij-community
platform/projectModel-impl/src/com/intellij/configurationStore/scheme-impl.kt
1
5896
// 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.configurationStore import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtil import com.intellij.project.isDirectoryBased import com.intellij.util.SmartList import com.intellij.util.io.DigestUtil import com.intellij.util.io.sanitizeFileName import com.intellij.util.isEmpty import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.xmlb.annotations.Attribute import org.jdom.Element import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.io.OutputStream import java.security.MessageDigest import java.util.concurrent.atomic.AtomicReference import java.util.function.Function typealias SchemeNameToFileName = (name: String) -> String val OLD_NAME_CONVERTER: SchemeNameToFileName = { FileUtil.sanitizeFileName(it, true) } val CURRENT_NAME_CONVERTER: SchemeNameToFileName = { FileUtil.sanitizeFileName(it, false) } val MODERN_NAME_CONVERTER: SchemeNameToFileName = { sanitizeFileName(it) } interface SchemeDataHolder<in T> { /** * You should call updateDigest() after read on init. */ fun read(): Element fun updateDigest(scheme: T) = Unit fun updateDigest(data: Element?) = Unit } /** * A scheme processor can implement this interface to provide a file extension different from default .xml. * @see SchemeProcessor */ interface SchemeExtensionProvider { /** * @return The scheme file extension **with a leading dot**, for example ".ext". */ val schemeExtension: String } // applicable only for LazySchemeProcessor interface SchemeContentChangedHandler<MUTABLE_SCHEME> { fun schemeContentChanged(scheme: MUTABLE_SCHEME, name: String, dataHolder: SchemeDataHolder<MUTABLE_SCHEME>) } abstract class LazySchemeProcessor<SCHEME : Any, MUTABLE_SCHEME : SCHEME>(private val nameAttribute: String = "name") : SchemeProcessor<SCHEME, MUTABLE_SCHEME>() { open fun getSchemeKey(attributeProvider: Function<String, String?>, fileNameWithoutExtension: String): String? { return attributeProvider.apply(nameAttribute) } abstract fun createScheme(dataHolder: SchemeDataHolder<MUTABLE_SCHEME>, name: String, attributeProvider: Function<in String, String?>, isBundled: Boolean = false): MUTABLE_SCHEME override fun writeScheme(scheme: MUTABLE_SCHEME): Element? = (scheme as SerializableScheme).writeScheme() open fun isSchemeFile(name: CharSequence) = true open fun isSchemeDefault(scheme: MUTABLE_SCHEME, digest: ByteArray) = false open fun isSchemeEqualToBundled(scheme: MUTABLE_SCHEME) = false } private class DigestOutputStream(private val digest: MessageDigest) : OutputStream() { override fun write(b: Int) { digest.update(b.toByte()) } override fun write(b: ByteArray, off: Int, len: Int) { digest.update(b, off, len) } override fun write(b: ByteArray) { digest.update(b) } override fun toString() = "[Digest Output Stream] $digest" fun digest(): ByteArray = digest.digest() } private val sha1MessageDigestThreadLocal = ThreadLocal.withInitial { DigestUtil.sha1() } // sha-1 is enough, sha-256 is slower, see https://www.nayuki.io/page/native-hash-functions-for-java fun createDataDigest(): MessageDigest { val digest = sha1MessageDigestThreadLocal.get() digest.reset() return digest } @JvmOverloads fun Element.digest(messageDigest: MessageDigest = createDataDigest()): ByteArray { val digestOut = DigestOutputStream(messageDigest) serializeElementToBinary(this, digestOut) return digestOut.digest() } abstract class SchemeWrapper<out T>(name: String) : ExternalizableSchemeAdapter(), SerializableScheme { protected abstract val lazyScheme: Lazy<T> val scheme: T get() = lazyScheme.value override fun getSchemeState(): SchemeState = if (lazyScheme.isInitialized()) SchemeState.POSSIBLY_CHANGED else SchemeState.UNCHANGED init { this.name = name } } abstract class LazySchemeWrapper<T>(name: String, dataHolder: SchemeDataHolder<SchemeWrapper<T>>, protected val writer: (scheme: T) -> Element) : SchemeWrapper<T>(name) { protected val dataHolder: AtomicReference<SchemeDataHolder<SchemeWrapper<T>>> = AtomicReference(dataHolder) final override fun writeScheme(): Element { val dataHolder = dataHolder.get() @Suppress("IfThenToElvis") return if (dataHolder == null) writer(scheme) else dataHolder.read() } } class InitializedSchemeWrapper<out T : Scheme>(scheme: T, private val writer: (scheme: T) -> Element) : SchemeWrapper<T>(scheme.name) { override val lazyScheme: Lazy<T> = lazyOf(scheme) override fun writeScheme() = writer(scheme) } fun unwrapState(element: Element, project: Project, iprAdapter: SchemeManagerIprProvider?, schemeManager: SchemeManager<*>): Element? { val data = if (project.isDirectoryBased) element.getChild("settings") else element iprAdapter?.let { it.load(data) schemeManager.reload() } return data } fun wrapState(element: Element, project: Project): Element { if (element.isEmpty() || !project.isDirectoryBased) { element.name = "state" return element } val wrapper = Element("state") wrapper.addContent(element) return wrapper } class BundledSchemeEP : AbstractExtensionPointBean() { @Attribute("path") var path: String? = null } fun SchemeManager<*>.save() { val errors = SmartList<Throwable>() save(errors) CompoundRuntimeException.throwIfNotEmpty(errors) } @ApiStatus.Internal @TestOnly val LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE = Key.create<Boolean>("LISTEN_VFS_CHANGES_IN_TEST_MODE")
apache-2.0
2fe5618f7a9c00ec345a1051dba9420e
33.48538
170
0.753053
4.354505
false
false
false
false
leafclick/intellij-community
plugins/filePrediction/src/com/intellij/filePrediction/history/FilePredictionHistoryState.kt
1
6779
// 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.filePrediction.history import com.intellij.util.xmlb.XmlSerializer import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Property import com.intellij.util.xmlb.annotations.Tag import gnu.trove.TIntIntHashMap import gnu.trove.TIntObjectHashMap import org.jdom.Element import kotlin.math.max class FilePredictionHistoryState { @get:Property(surroundWithTag = true) var recentFiles: MutableList<RecentFileEntry> = ArrayList() @get:Attribute(value = "prevFile") var prevFile: Int? = null @get:Attribute(value = "nextCode") var nextFileCode: Int = 0 @Transient val root: NGramMapNode = NGramMapNode() fun serialize(): Element { val serialized = XmlSerializer.serialize(this) val sequences = Element("sequences") sequences.setAttribute("count", root.count.toString()) root.usages.forEachEntry { code, node -> val child = Element("usage") child.setAttribute("code", code.toString()) child.setAttribute("count", node.count.toString()) val keys = node.usages.keys().joinToString(separator = ",") child.setAttribute("keys", keys) val values = node.usages.values.joinToString(separator = ",") child.setAttribute("values", values) sequences.addContent(child) return@forEachEntry true } serialized.addContent(sequences) return serialized } fun deserialize(element: Element): FilePredictionHistoryState { XmlSerializer.deserializeInto(this, element) val sequences = element.getChild("sequences") if (sequences == null) { return this } root.count = sequences.getIntAttribute("count") val usages = sequences.getChildren("usage") for (usage in usages) { val code = usage.getIntAttribute("code") val node = root.getOrCreate(code) node.count = usage.getIntAttribute("count") val keys = usage.getIntListAttribute("keys") val values = usage.getIntListAttribute("values") if (keys != null && values != null && keys.size == values.size) { for ((index, key) in keys.withIndex()) { node.setNode(key, values[index]) } } } return this } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FilePredictionHistoryState if (recentFiles != other.recentFiles) return false if (prevFile != other.prevFile) return false if (nextFileCode != other.nextFileCode) return false if (root != other.root) return false return true } override fun hashCode(): Int { var result = recentFiles.hashCode() result = 31 * result + (prevFile ?: 0) result = 31 * result + nextFileCode result = 31 * result + root.hashCode() return result } } @Tag("recent-file") class RecentFileEntry { @get:Attribute(value = "url") var fileUrl: String? = null @get:Attribute(value = "code") var code: Int = -1 override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RecentFileEntry if (fileUrl != other.fileUrl) return false if (code != other.code) return false return true } override fun hashCode(): Int { var result = fileUrl?.hashCode() ?: 0 result = 31 * result + code return result } } abstract class NGramModelNode<T> { var count: Int = 0 abstract fun addOrIncrement(code: Int) abstract fun getOrCreate(code: Int): T abstract fun getNode(code: Int): T? abstract fun findMinMax(): Pair<Int, Int> } class NGramMapNode: NGramModelNode<NGramListNode>() { val usages: TIntObjectHashMap<NGramListNode> = TIntObjectHashMap() override fun addOrIncrement(code: Int) { usages.getOrPut(code).count++ } override fun getOrCreate(code: Int): NGramListNode { return usages.getOrPut(code) } override fun getNode(code: Int): NGramListNode? { return usages[code] } fun clear() { usages.clear() } override fun findMinMax(): Pair<Int, Int> { var minCount: Int = -1 var maxCount: Int = -1 usages.forEachValue { listNode -> val count = listNode.count if (minCount < 0 || minCount > count) { minCount = count } if (maxCount < 0 || maxCount < count) { maxCount = count } true } return max(minCount, 0) to max(maxCount, 0) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as NGramMapNode if (count != other.count) return false if (usages != other.usages) return false return true } override fun hashCode(): Int { var result = count result = 31 * result + usages.hashCode() return result } } class NGramListNode: NGramModelNode<Int>() { val usages: TIntIntHashMap = TIntIntHashMap() override fun addOrIncrement(code: Int) { val current = usages.getOrPut(code) usages.put(code, current + 1) } override fun getOrCreate(code: Int): Int { return usages.getOrPut(code) } override fun getNode(code: Int): Int? { return usages.get(code) } fun setNode(code: Int, count: Int) { usages.put(code, count) } override fun findMinMax(): Pair<Int, Int> { var minCount: Int = -1 var maxCount: Int = -1 usages.forEachValue { count -> if (minCount < 0 || minCount > count) { minCount = count } if (maxCount < 0 || maxCount < count) { maxCount = count } true } return max(minCount, 0) to max(maxCount, 0) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as NGramListNode if (count != other.count) return false if (usages != other.usages) return false return true } override fun hashCode(): Int { var result = count result = 31 * result + usages.hashCode() return result } } private fun Element.getIntAttribute(name: String): Int { return getAttributeValue(name)?.toIntOrNull() ?: 0 } private fun Element.getIntListAttribute(name: String): IntArray? { return getAttributeValue(name)?.split(',')?.mapNotNull { it.toIntOrNull() }?.toIntArray() } private fun TIntIntHashMap.getOrPut(code: Int): Int { if (!this.containsKey(code)) { this.put(code, 0) } return this.get(code) } private fun TIntObjectHashMap<NGramListNode>.getOrPut(code: Int): NGramListNode { if (!this.containsKey(code)) { this.put(code, NGramListNode()) } return this.get(code) }
apache-2.0
490276fcdb679f96fc6af69c62d536aa
25.073077
140
0.664405
4.103511
false
false
false
false
MGaetan89/Kolumbus
kolumbus/src/main/kotlin/io/kolumbus/extension/StringExtensions.kt
1
1195
/* * Copyright (C) 2016 MGaetan89 * * 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 io.kolumbus.extension import java.util.regex.Pattern private val ACCESSOR_PREFIXES = Pattern.compile("^(get|is)").toRegex() private val CAMEL_CASE = Pattern.compile("([a-z])([A-Z])").toRegex() fun String.prettify(): String = this.removeAccessorPrefixes().toCamelCase() internal fun String.removeAccessorPrefixes(): String = ACCESSOR_PREFIXES.replaceFirst(this, "") internal fun String.toCamelCase(): String { val camelCased = CAMEL_CASE.replace(this, "$1 $2") return when { camelCased.isEmpty() -> camelCased else -> camelCased.first().toUpperCase() + camelCased.drop(1) } }
apache-2.0
e1c233d2e0ed859da689cc19a38d9df1
33.142857
95
0.732218
3.830128
false
false
false
false
AndroidX/androidx
compose/material/material/icons/generator/src/test/kotlin/androidx/compose/material/icons/generator/ImageVectorGeneratorTest.kt
3
3954
/* * 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.material.icons.generator import androidx.compose.material.icons.generator.PackageNames.MaterialIconsPackage import androidx.compose.material.icons.generator.vector.FillType import androidx.compose.material.icons.generator.vector.PathNode import androidx.compose.material.icons.generator.vector.Vector import androidx.compose.material.icons.generator.vector.VectorNode import com.google.common.truth.Truth import org.intellij.lang.annotations.Language import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 /** * Test for [ImageVectorGenerator]. */ @RunWith(JUnit4::class) class ImageVectorGeneratorTest { @Test fun generateFileSpec() { val iconName = "TestVector" val theme = IconTheme.Filled val generator = ImageVectorGenerator( iconName = iconName, iconTheme = theme, vector = TestVector ) val fileSpec = generator.createFileSpec() Truth.assertThat(fileSpec.name).isEqualTo(iconName) val expectedPackageName = MaterialIconsPackage.packageName + "." + theme.themePackageName Truth.assertThat(fileSpec.packageName).isEqualTo(expectedPackageName) val fileContent = StringBuilder().run { fileSpec.writeTo(this) toString() } Truth.assertThat(fileContent).isEqualTo(ExpectedFile) } } @Language("kotlin") private val ExpectedFile = """ package androidx.compose.material.icons.filled import androidx.compose.material.icons.Icons import androidx.compose.material.icons.materialIcon import androidx.compose.material.icons.materialPath import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.group public val Icons.Filled.TestVector: ImageVector get() { if (_testVector != null) { return _testVector!! } _testVector = materialIcon(name = "Filled.TestVector") { materialPath(fillAlpha = 0.8f) { moveTo(20.0f, 10.0f) lineToRelative(0.0f, 10.0f) lineToRelative(-10.0f, 0.0f) close() } group { materialPath(pathFillType = EvenOdd) { moveTo(0.0f, 10.0f) lineToRelative(-10.0f, 0.0f) close() } } } return _testVector!! } private var _testVector: ImageVector? = null """.trimIndent() private val path1 = VectorNode.Path( strokeAlpha = 1f, fillAlpha = 0.8f, fillType = FillType.NonZero, nodes = listOf( PathNode.MoveTo(20f, 10f), PathNode.RelativeLineTo(0f, 10f), PathNode.RelativeLineTo(-10f, 0f), PathNode.Close ) ) private val path2 = VectorNode.Path( strokeAlpha = 1f, fillAlpha = 1f, fillType = FillType.EvenOdd, nodes = listOf( PathNode.MoveTo(0f, 10f), PathNode.RelativeLineTo(-10f, 0f), PathNode.Close ) ) private val group = VectorNode.Group(mutableListOf(path2)) private val TestVector = Vector(listOf(path1, group))
apache-2.0
b104860d0f40ea229340c3e808a370df
30.133858
97
0.655033
4.412946
false
true
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/persistence/sudoku/sudokuTypes/SetOfPermutationPropertiesBE.kt
2
1444
package de.sudoq.persistence.sudoku.sudokuTypes import de.sudoq.model.sudoku.sudokuTypes.PermutationProperties import de.sudoq.persistence.XmlAttribute import de.sudoq.persistence.XmlTree import de.sudoq.persistence.Xmlable class SetOfPermutationPropertiesBE : ArrayList<PermutationProperties>, Xmlable { constructor() : super() constructor(initialCapacity: Int) : super(initialCapacity) constructor(elements: Collection<PermutationProperties>) : super(elements) override fun toXmlTree(): XmlTree { val representation = XmlTree(SET_OF_PERMUTATION_PROPERTIES) for (p in this) { val xt = XmlTree(PERMUTATION_PROPERTY) xt.addAttribute(XmlAttribute(TAG_PROPERTY_NR, "" + p.ordinal)) representation.addChild(xt) } return representation } @Throws(IllegalArgumentException::class) override fun fillFromXml(xmlTreeRepresentation: XmlTree) { for (sub in xmlTreeRepresentation) { if (sub.name == PERMUTATION_PROPERTY) { add( PermutationProperties.values()[sub.getAttributeValue(TAG_PROPERTY_NR)!!.toInt()] ) } } } companion object { const val SET_OF_PERMUTATION_PROPERTIES = "SetOfPermutationProperties" private const val PERMUTATION_PROPERTY = "PermutationProperty" private const val TAG_PROPERTY_NR = "permutationNr" } }
gpl-3.0
ab3fbf446c012ecd16e220f46f6d00fc
33.404762
100
0.680055
4.861953
false
false
false
false
smmribeiro/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/AnnotatedApiUsageUtil.kt
12
7292
// 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.codeInspection import com.intellij.codeInsight.AnnotationUtil import com.intellij.codeInspection.deprecation.DeprecationInspection import com.intellij.lang.findUsages.LanguageFindUsages import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.UClass import org.jetbrains.uast.UDeclaration import org.jetbrains.uast.UField import org.jetbrains.uast.UMethod /** * Container of several values representing annotation search result. * * - [target] — starting API element of which annotation was searched. * - [containingDeclaration] — annotated declaration containing [target]. May be equal [target] if the [target] is annotated itself. * Otherwise it is the [target]'s containing class or package. * - [psiAnnotation] — annotation with which [containingDeclaration] is marked. */ @ApiStatus.Internal data class AnnotatedContainingDeclaration( val target: PsiModifierListOwner, val containingDeclaration: PsiModifierListOwner, val psiAnnotation: PsiAnnotation ) { val isOwnAnnotation: Boolean get() = target == containingDeclaration val targetName: String get() = DeprecationInspection.getPresentableName(target) val targetType: String get() = LanguageFindUsages.getType(target) val containingDeclarationName: String get() = DeprecationInspection.getPresentableName(containingDeclaration) val containingDeclarationType: String get() = LanguageFindUsages.getType(containingDeclaration) val presentableAnnotationName: String? get() { val qualifiedName = psiAnnotation.qualifiedName ?: return null return qualifiedName.split('.') .takeLastWhile { it.isNotEmpty() && it.first().isUpperCase() } .joinToString(separator = ".") .takeIf { it.isNotEmpty() } ?: qualifiedName } } /** * Utility functions for [UnstableApiUsageInspection] and [UnstableTypeUsedInSignatureInspection]. */ @ApiStatus.Internal internal object AnnotatedApiUsageUtil { /** * Returns `true` iff the annotation with qualified name [annotationFqn] can be referenced from file [psiFile]. * It may be used to check whether it is necessary to run for the given file an inspection that checks usages of some annotations. */ fun canAnnotationBeUsedInFile(annotationFqn: String, psiFile: PsiFile): Boolean = JavaPsiFacade.getInstance(psiFile.project).findClass(annotationFqn, psiFile.resolveScope) != null /** * Searches for an annotation on a [target] or its enclosing declaration (containing class or package). * * If a [target] is marked with annotation, it is returned immediately. * If containing class of [target] is marked with annotation, the class and its annotation is returned. * If the package, to which the [target] belongs, is marked with annotation, the package and its annotation is returned. */ fun findAnnotatedContainingDeclaration( target: PsiModifierListOwner, annotationNames: Collection<String>, includeExternalAnnotations: Boolean, containingDeclaration: PsiModifierListOwner = target ): AnnotatedContainingDeclaration? { val annotation = AnnotationUtil.findAnnotation(containingDeclaration, annotationNames, !includeExternalAnnotations) if (annotation != null) { return AnnotatedContainingDeclaration(target, containingDeclaration, annotation) } if (containingDeclaration is PsiMember) { val containingClass = containingDeclaration.containingClass if (containingClass != null) { return findAnnotatedContainingDeclaration(target, annotationNames, includeExternalAnnotations, containingClass) } } val packageName = (containingDeclaration.containingFile as? PsiClassOwner)?.packageName ?: return null val psiPackage = JavaPsiFacade.getInstance(containingDeclaration.project).findPackage(packageName) ?: return null return findAnnotatedContainingDeclaration(target, annotationNames, includeExternalAnnotations, psiPackage) } /** * Searches for an annotated type that is part of the signature of the given declaration. * * * For classes, annotated type parameter is returned: * * `class Foo<T extends Bar>` -> `Bar` is returned if it is annotated. * * * For methods, annotated return type, parameter type or type parameter is returned: * * `public <T extends Baz> Foo method(Bar bar)` -> `Baz`, `Foo` or `Bar` is returned, whichever is annotated. * * * For fields, annotated field type is returned: * * `public Foo field` -> `Foo` is returned if it is annotated. */ fun findAnnotatedTypeUsedInDeclarationSignature( declaration: UDeclaration, annotations: Collection<String> ): AnnotatedContainingDeclaration? { when (declaration) { is UClass -> { return findAnnotatedTypeParameter(declaration.javaPsi, annotations) } is UMethod -> { for (uastParameter in declaration.uastParameters) { val annotatedParamType = findAnnotatedTypePart(uastParameter.type.deepComponentType, annotations) if (annotatedParamType != null) { return annotatedParamType } } val returnType = declaration.returnType if (returnType != null) { val annotatedReturnType = findAnnotatedTypePart(returnType.deepComponentType, annotations) if (annotatedReturnType != null) { return annotatedReturnType } } return findAnnotatedTypeParameter(declaration.javaPsi, annotations) } is UField -> { return findAnnotatedTypePart(declaration.type.deepComponentType, annotations) } else -> return null } } private fun findAnnotatedTypeParameter( typeParameterListOwner: PsiTypeParameterListOwner, annotations: Collection<String> ): AnnotatedContainingDeclaration? { for (typeParameter in typeParameterListOwner.typeParameters) { for (referencedType in typeParameter.extendsList.referencedTypes) { val annotatedContainingDeclaration = findAnnotatedTypePart(referencedType.deepComponentType, annotations) if (annotatedContainingDeclaration != null) { return annotatedContainingDeclaration } } } return null } private fun findAnnotatedTypePart( psiType: PsiType, annotations: Collection<String> ): AnnotatedContainingDeclaration? { if (psiType is PsiClassType) { val psiClass = psiType.resolve() if (psiClass != null) { val containingDeclaration = findAnnotatedContainingDeclaration(psiClass, annotations, false) if (containingDeclaration != null) { return containingDeclaration } } for (parameterType in psiType.parameters) { val parameterResult = findAnnotatedTypePart(parameterType, annotations) if (parameterResult != null) { return parameterResult } } } if (psiType is PsiWildcardType) { return findAnnotatedTypePart(psiType.extendsBound, annotations) ?: findAnnotatedTypePart(psiType.superBound, annotations) } return null } }
apache-2.0
4880db0e63661aefc9914637f2be343d
39.938202
140
0.728246
5.401038
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/NonModalAmendCommitHandler.kt
5
4761
// 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 com.intellij.vcs.commit import com.intellij.openapi.application.runInEdt import com.intellij.openapi.util.Key import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsListener import com.intellij.openapi.vcs.VcsRoot import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.CommitResultHandler import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.VcsUser import com.intellij.vcs.log.util.VcsUserUtil.isSamePerson import org.jetbrains.concurrency.CancellablePromise import kotlin.properties.Delegates.observable private val AMEND_AUTHOR_DATA_KEY = Key.create<AmendAuthorData>("Vcs.Commit.AmendAuthorData") private var CommitContext.amendAuthorData: AmendAuthorData? by commitProperty(AMEND_AUTHOR_DATA_KEY, null) private class AmendAuthorData(val beforeAmendAuthor: VcsUser?, val amendAuthor: VcsUser) class NonModalAmendCommitHandler(private val workflowHandler: NonModalCommitWorkflowHandler<*, *>) : AmendCommitHandlerImpl(workflowHandler) { private var amendRoot by observable<VcsRoot?>(null) { _, oldValue, newValue -> if (oldValue == newValue) return@observable updateAmendCommitState() } private var amendDetailsGetter: CancellablePromise<EditedCommitDetails>? = null private var _isLoading: Boolean by observable(false) { _, oldValue, newValue -> if (oldValue == newValue) return@observable workflowHandler.updateDefaultCommitActionEnabled() } init { workflowHandler.workflow.addCommitListener(EditedCommitCleaner(), workflowHandler) amendRoot = getSingleRoot() project.messageBus.connect(workflowHandler).subscribe(VCS_CONFIGURATION_CHANGED, VcsListener { runInEdt { amendRoot = getSingleRoot() } }) } val isLoading: Boolean get() = _isLoading internal fun isAmendWithoutChangesAllowed(): Boolean = isAmendCommitMode && amendRoot != null override fun amendCommitModeToggled() { val root = amendRoot?.path ?: return super.amendCommitModeToggled() val amendAware = amendRoot?.vcs?.checkinEnvironment as? AmendCommitAware ?: return super.amendCommitModeToggled() fireAmendCommitModeToggled() workflowHandler.updateDefaultCommitActionName() updateAmendCommitState() if (isAmendCommitMode) loadAmendDetails(amendAware, root) else restoreAmendDetails() } private fun updateAmendCommitState() { commitContext.commitWithoutChangesRoots = if (isAmendCommitMode) listOfNotNull(amendRoot) else emptyList() } private fun loadAmendDetails(amendAware: AmendCommitAware, root: VirtualFile) { _isLoading = true amendDetailsGetter = amendAware.getAmendCommitDetails(root) amendDetailsGetter?.run { onSuccess { setAmendDetails(it) } onProcessed { _isLoading = false amendDetailsGetter = null } } } private fun restoreAmendDetails() { amendDetailsGetter?.cancel() workflowHandler.updateDefaultCommitActionEnabled() restoreAmendAuthor() restoreBeforeAmendMessage() setEditedCommit(null) } private fun setAmendDetails(amendDetails: EditedCommitDetails) { setAmendAuthor(amendDetails.currentUser, amendDetails.commit.author) setAmendMessage(workflowHandler.getCommitMessage(), amendDetails.commit.fullMessage) setEditedCommit(amendDetails) } private fun setEditedCommit(amendDetails: EditedCommitDetails?) { workflowHandler.ui.editedCommit = amendDetails } private fun setAmendAuthor(currentUser: VcsUser?, amendAuthor: VcsUser) { val beforeAmendAuthor = workflowHandler.ui.commitAuthor if (beforeAmendAuthor != null && isSamePerson(beforeAmendAuthor, amendAuthor)) return if (beforeAmendAuthor == null && currentUser != null && isSamePerson(currentUser, amendAuthor)) return workflowHandler.ui.commitAuthor = amendAuthor commitContext.amendAuthorData = AmendAuthorData(beforeAmendAuthor, amendAuthor) } private fun restoreAmendAuthor() { val amendAuthorData = commitContext.amendAuthorData ?: return commitContext.amendAuthorData = null val author = workflowHandler.ui.commitAuthor if (author == null || !isSamePerson(author, amendAuthorData.amendAuthor)) return workflowHandler.ui.commitAuthor = amendAuthorData.beforeAmendAuthor } private inner class EditedCommitCleaner : CommitResultHandler { override fun onSuccess(commitMessage: String) = setEditedCommit(null) override fun onCancel() = Unit override fun onFailure(errors: MutableList<VcsException>) = setEditedCommit(null) } }
apache-2.0
fe1a8aa58ce6d757a29f30f0110234d7
39.355932
140
0.781558
4.954214
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/style/GrUnnecessarySealingModifierInspection.kt
7
1244
// 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.plugins.groovy.codeInspection.style import com.intellij.psi.PsiElement import com.intellij.psi.PsiModifierListOwner import com.intellij.psi.util.parentOfType import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition sealed class GrUnnecessarySealingModifierInspection(val sealingModifier: String) : GrUnnecessaryModifierInspection(sealingModifier) { override fun isRedundant(element: PsiElement): Boolean { val modifierList = element.parent as? GrModifierList ?: return false val owner = modifierList.parentOfType<PsiModifierListOwner>()?.takeIf { it.modifierList === modifierList } ?: return false return owner !is GrTypeDefinition } } class GrUnnecessarySealedModifierInspection : GrUnnecessarySealingModifierInspection(GrModifier.SEALED) class GrUnnecessaryNonSealedModifierInspection : GrUnnecessarySealingModifierInspection(GrModifier.NON_SEALED)
apache-2.0
1e02e3158d61327e7206084247737bee
58.238095
158
0.834405
4.803089
false
false
false
false
jotomo/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStartWithSpeed.kt
1
1087
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.logging.LTag class MsgBolusStartWithSpeed( injector: HasAndroidInjector, private var amount: Double, speed: Int ) : MessageBase(injector) { init { SetCommand(0x0104) // HARDCODED LIMIT amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() AddParamInt((amount * 100).toInt()) AddParamByte(speed.toByte()) aapsLogger.debug(LTag.PUMPBTCOMM, "Bolus start : $amount speed: $speed") } override fun handleMessage(bytes: ByteArray) { val errorCode = intFromBuff(bytes, 0, 1) if (errorCode != 2) { failed = true aapsLogger.debug(LTag.PUMPBTCOMM, "Messsage response: $errorCode FAILED!!") } else { failed = false aapsLogger.debug(LTag.PUMPBTCOMM, "Messsage response: $errorCode OK") } danaPump.bolusStartErrorCode = errorCode } }
agpl-3.0
8671e6982215e0f26b7256e770d97674
31.969697
87
0.670653
4.586498
false
false
false
false
alibaba/p3c
idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/standalone/AliAccessStaticViaInstanceInspection.kt
2
5814
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.p3c.idea.inspection.standalone import com.alibaba.p3c.idea.config.P3cConfig import com.alibaba.p3c.idea.i18n.P3cBundle import com.alibaba.p3c.idea.inspection.AliBaseInspection import com.alibaba.p3c.idea.util.HighlightDisplayLevels import com.alibaba.smartfox.idea.common.util.getService import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.codeInsight.daemon.impl.analysis.HighlightMessageUtil import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil import com.intellij.codeInsight.daemon.impl.quickfix.AccessStaticViaInstanceFix import com.intellij.codeInsight.daemon.impl.quickfix.RemoveUnusedVariableUtil import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.accessStaticViaInstance.AccessStaticViaInstance import com.intellij.psi.JavaElementVisitor import com.intellij.psi.JavaResolveResult import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiMember import com.intellij.psi.PsiModifier import com.intellij.psi.PsiPackage import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.PsiSubstitutor import java.util.ArrayList /** * @author caikang * @date 2016/12/08 */ class AliAccessStaticViaInstanceInspection : AccessStaticViaInstance, AliBaseInspection { val messageKey = "com.alibaba.p3c.idea.inspection.standalone.AliAccessStaticViaInstanceInspection" constructor() /** * For Javassist */ constructor(any: Any?) : this() override fun getDisplayName(): String { return P3cBundle.getMessage("$messageKey.message") } override fun getStaticDescription(): String? { return P3cBundle.getMessage("$messageKey.desc") } override fun ruleName(): String { return "AvoidAccessStaticViaInstanceRule" } override fun getShortName(): String { return "AliAccessStaticViaInstance" } override fun createAccessStaticViaInstanceFix(expr: PsiReferenceExpression, onTheFly: Boolean, result: JavaResolveResult): AccessStaticViaInstanceFix { return object : AccessStaticViaInstanceFix(expr, result, onTheFly) { val fixKey = "com.alibaba.p3c.idea.quickfix.standalone.AliAccessStaticViaInstanceInspection" internal val text = calcText(result.element as PsiMember, result.substitutor) override fun getText(): String { return text } private fun calcText(member: PsiMember, substitutor: PsiSubstitutor): String { val aClass = member.containingClass ?: return "" val p3cConfig = P3cConfig::class.java.getService() return when (p3cConfig.locale) { P3cConfig.localeZh -> String.format(P3cBundle.getMessage(fixKey), HighlightUtil.formatClass(aClass, false), HighlightUtil.formatClass(aClass), HighlightMessageUtil.getSymbolName(member, substitutor)) else -> String.format(P3cBundle.getMessage(fixKey), HighlightUtil.formatClass(aClass), HighlightMessageUtil.getSymbolName(member, substitutor), HighlightUtil.formatClass(aClass, false)) } } } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : JavaElementVisitor() { override fun visitReferenceExpression(expression: PsiReferenceExpression) { checkAccessStaticMemberViaInstanceReference(expression, holder, isOnTheFly) } } } override fun getDefaultLevel(): HighlightDisplayLevel { return HighlightDisplayLevels.BLOCKER } private fun checkAccessStaticMemberViaInstanceReference(expr: PsiReferenceExpression, holder: ProblemsHolder, onTheFly: Boolean) { val result = expr.advancedResolve(false) val resolved = result.element as? PsiMember ?: return val qualifierExpression = expr.qualifierExpression ?: return if (qualifierExpression is PsiReferenceExpression) { val qualifierResolved = qualifierExpression.resolve() if (qualifierResolved is PsiClass || qualifierResolved is PsiPackage) { return } } if (!resolved.hasModifierProperty(PsiModifier.STATIC)) { return } val description = String.format(P3cBundle.getMessage( "$messageKey.errMsg"), "${JavaHighlightUtil.formatType(qualifierExpression.type)}.${HighlightMessageUtil.getSymbolName( resolved, result.substitutor)}") if (!onTheFly) { if (RemoveUnusedVariableUtil.checkSideEffects(qualifierExpression, null, ArrayList<PsiElement>())) { holder.registerProblem(expr, description) return } } holder.registerProblem(expr, description, createAccessStaticViaInstanceFix(expr, onTheFly, result)) } }
apache-2.0
c605bc03a8fcf4fe6fce32b6d6905983
40.528571
119
0.70571
5.154255
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUnderscoreWithParameterNameIntention.kt
2
4585
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.builtins.extractParameterNameFromFunctionTypeArgument import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.callUtil.getParentResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ReplaceUnderscoreWithParameterNameIntention : SelfTargetingOffsetIndependentIntention<KtCallableDeclaration>( KtCallableDeclaration::class.java, KotlinBundle.lazyMessage("replace.with.parameter.name") ) { override fun isApplicableTo(element: KtCallableDeclaration) = element.name == "_" && (element is KtDestructuringDeclarationEntry || element is KtParameter) override fun applyTo(element: KtCallableDeclaration, editor: Editor?) { val suggestedParameterName = suggestedParameterName(element) val validator = CollectingNameValidator( filter = NewDeclarationNameValidator(element.parent.parent, null, NewDeclarationNameValidator.Target.VARIABLES) ) val name = suggestedParameterName?.let { KotlinNameSuggester.suggestNameByName(it, validator) } ?: run { val elementDescriptor = element.resolveToDescriptorIfAny() as? CallableDescriptor elementDescriptor?.returnType?.let { KotlinNameSuggester.suggestNamesByType(it, validator).firstOrNull() } } ?: return element.setName(name) } private fun suggestedParameterName(element: KtCallableDeclaration) = when (element) { is KtDestructuringDeclarationEntry -> dataClassParameterName(element) is KtParameter -> lambdaParameterName(element) else -> null } private fun lambdaParameterName(element: KtParameter): String? { val functionLiteral = element.getParentOfType<KtFunctionLiteral>(strict = true) ?: return null val idx = functionLiteral.valueParameters.indexOf(element) if (idx == -1) return null val context = functionLiteral.analyze(BodyResolveMode.PARTIAL) val resolvedCall = element.getParentResolvedCall(context) val lambdaArgument = functionLiteral.getParentOfType<KtLambdaArgument>(strict = true) ?: return null val lambdaParam = resolvedCall?.getParameterForArgument(lambdaArgument) ?: return null return lambdaParam.type.arguments.getOrNull(idx)?.type?.extractParameterNameFromFunctionTypeArgument()?.asString() } private fun dataClassParameterName(declarationEntry: KtDestructuringDeclarationEntry): String? { val context = declarationEntry.analyze() val componentResolvedCall = context[BindingContext.COMPONENT_RESOLVED_CALL, declarationEntry] ?: return null val receiver = componentResolvedCall.dispatchReceiver ?: componentResolvedCall.extensionReceiver ?: return null val classDescriptor = receiver.type.constructor.declarationDescriptor as? ClassDescriptor ?: return null return when { classDescriptor.isData -> { val primaryParameters = classDescriptor.unsubstitutedPrimaryConstructor?.valueParameters primaryParameters?.getOrNull(declarationEntry.entryIndex())?.name?.asString() } DescriptorUtils.isSubclass(classDescriptor, classDescriptor.builtIns.mapEntry) -> { listOf("key", "value").getOrNull(declarationEntry.entryIndex()) } else -> null } } private fun KtDestructuringDeclarationEntry.entryIndex() = parent.getChildrenOfType<KtDestructuringDeclarationEntry>().indexOf(this) }
apache-2.0
ccb62a0e723b91f09edbe9a450e00bff
54.253012
158
0.767067
5.639606
false
false
false
false
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/editor/images/ImageUtils.kt
3
1982
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.images import com.intellij.lang.html.HTMLLanguage import com.intellij.openapi.util.text.HtmlChunk import com.intellij.psi.PsiElement import com.intellij.psi.XmlElementFactory import com.intellij.psi.XmlElementFactoryImpl import com.intellij.psi.xml.XmlTag import com.intellij.util.IncorrectOperationException import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.util.hasType internal object ImageUtils { @JvmStatic fun createMarkdownImageText(description: String = "", path: String, title: String = ""): String { val actualTitle = when { title.isNotEmpty() -> " ${XmlElementFactoryImpl.quoteValue(title)}" else -> title } return "![$description]($path${actualTitle})" } @JvmStatic fun createHtmlImageText(imageData: MarkdownImageData): String { val (path, width, height, title, description) = imageData val element = HtmlChunk.tag("img") .nonEmptyAttribute("src", path) .nonEmptyAttribute("width", width) .nonEmptyAttribute("height", height) .nonEmptyAttribute("title", title) .nonEmptyAttribute("alt", description) return element.toString() } private fun HtmlChunk.Element.nonEmptyAttribute(name: String, value: String): HtmlChunk.Element { return when { value.isNotEmpty() -> attr(name, value) else -> this } } @JvmStatic fun createImageTagFromText(element: PsiElement): XmlTag? { if (!element.hasType(MarkdownTokenTypes.HTML_TAG)) { return null } try { val tag = XmlElementFactory.getInstance(element.project).createTagFromText(element.text, HTMLLanguage.INSTANCE) return tag.takeIf { it.name == "img" } } catch (exception: IncorrectOperationException) { return null } } }
apache-2.0
d31f351149d3e86023bb02711ebc566d
35.036364
158
0.726034
4.384956
false
false
false
false
siosio/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/DeclarationAndUsagesLesson.kt
1
5622
// 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 training.learn.lesson.general.navigation import com.intellij.codeInsight.TargetElementUtil import com.intellij.find.FindBundle import com.intellij.find.FindSettings import com.intellij.openapi.actionSystem.impl.ActionMenuItem import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.impl.content.BaseLabel import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.ui.UIBundle import com.intellij.ui.table.JBTable import training.dsl.LessonContext import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.dsl.TaskRuntimeContext import training.dsl.checkToolWindowState import training.dsl.closeAllFindTabs import training.learn.LessonsBundle import training.learn.course.KLesson abstract class DeclarationAndUsagesLesson : KLesson("Declaration and usages", LessonsBundle.message("declaration.and.usages.lesson.name")) { abstract fun LessonContext.setInitialPosition() abstract override val existedFile: String abstract val entityName: String override val lessonContent: LessonContext.() -> Unit get() = { setInitialPosition() prepareRuntimeTask { val focusManager = IdeFocusManager.getInstance(project) if (focusManager.focusOwner != editor.contentComponent) { focusManager.requestFocus(editor.contentComponent, true) } } task("GotoDeclaration") { text(LessonsBundle.message("declaration.and.usages.jump.to.declaration", action(it))) trigger(it, { state() }) { before, _ -> before != null && !isInsidePsi(before.target.navigationElement, before.position) } restoreIfModifiedOrMoved() test { actions(it) } } task("GotoDeclaration") { text(LessonsBundle.message("declaration.and.usages.show.usages", action(it))) trigger(it, { state() }) l@{ before, now -> if (before == null || now == null) { return@l false } val navigationElement = before.target.navigationElement return@l navigationElement == now.target.navigationElement && isInsidePsi(navigationElement, before.position) && !isInsidePsi(navigationElement, now.position) } restoreIfModifiedOrMoved() test { actions(it) ideFrame { waitComponent(JBTable::class.java, "ShowUsagesTable") invokeActionViaShortcut("ENTER") } } } task("FindUsages") { before { closeAllFindTabs() } text(LessonsBundle.message("declaration.and.usages.find.usages", action(it))) triggerByUiComponentAndHighlight { ui: BaseLabel -> ui.javaClass.simpleName == "ContentTabLabel" && (ui.text?.contains(entityName) ?: false) } restoreIfModifiedOrMoved() test { actions(it) } } val pinTabText = UIBundle.message("tabbed.pane.pin.tab.action.name") task { test { ideFrame { previous.ui?.let { usagesTab -> jComponent(usagesTab).rightClick() } } } triggerByUiComponentAndHighlight(highlightInside = false) { ui: ActionMenuItem -> ui.text?.contains(pinTabText) ?: false } restoreByUi() text(LessonsBundle.message("declaration.and.usages.pin.motivation", strong(UIBundle.message("tool.window.name.find")))) text(LessonsBundle.message("declaration.and.usages.right.click.tab", strong(FindBundle.message("find.usages.of.element.in.scope.panel.title", entityName, FindSettings.getInstance().defaultScopeName)))) } task("PinToolwindowTab") { trigger(it) restoreByUi() text(LessonsBundle.message("declaration.and.usages.select.pin.item", strong(pinTabText))) test { ideFrame { jComponent(previous.ui!!).click() } } } task("HideActiveWindow") { text(LessonsBundle.message("declaration.and.usages.hide.view", action(it))) checkToolWindowState("Find", false) test { actions(it) } } actionTask("ActivateFindToolWindow") { LessonsBundle.message("declaration.and.usages.open.find.view", action(it), strong(UIBundle.message("tool.window.name.find"))) } } private fun TaskRuntimeContext.state(): MyInfo? { val flags = TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED val currentEditor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null val target = TargetElementUtil.findTargetElement(currentEditor, flags) ?: return null val file = PsiDocumentManager.getInstance(project).getPsiFile(currentEditor.document) ?: return null val position = MyPosition(file, currentEditor.caretModel.offset) return MyInfo(target, position) } private fun isInsidePsi(psi: PsiElement, position: MyPosition): Boolean { return psi.containingFile == position.file && psi.textRange.contains(position.offset) } private data class MyInfo(val target: PsiElement, val position: MyPosition) private data class MyPosition(val file: PsiFile, val offset: Int) }
apache-2.0
36c2ee17046fd0aad8d19b931ab66ea1
36.986486
140
0.668979
4.854922
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/compose-2.kt
1
1791
package alraune import vgrechka.* import alraune.Al.* import pieces100.* fun composePageHeader(text: String, block: () -> Unit = {}): Renderable = div().style("position: relative;").with { oo(h3().className("page-header").style("margin-top: 15px; margin-bottom: 10px;").with { oo(span(text)) }) block() Spaghetti.the.maybePluck(ShitIntoPageHeader::class)?.block?.invoke() } class DetailsRow : RenderableRelatingItsCreationStackToRendering() { private var content: Renderable? = null private var highlightRanges = listOf<IntRange>(); fun highlightRanges(x: List<IntRange>) = run {highlightRanges = x; this} private var title = t("Details", "Детали"); fun title(x: String) = run {title = x; this} private var amendCol: ((Col) -> Unit)? = null; fun amendCol(x: ((Col) -> Unit)?) = run {amendCol = x; this} private var noMarginBottom = false; fun noMarginBottom() = run {noMarginBottom = true; this} fun content(x: Renderable?): DetailsRow = run {content = x; this} fun content(x: String?): DetailsRow = run {content(if (x.isNullOrBlank()) null else span(x!!)); this} override fun compose(): Renderable { if (content == null) return div() val row = Row() if (noMarginBottom) row.marginBottom("") return row.with { oo(Col(12).title(title).amend(amendCol).contentStyle("white-space: pre-wrap;").with { // TODO:vgrechka Highlighting oo(content); }) } } } fun detailsWithUnderlinedTitle(title: String, value: String): Renderable { return DetailsRow() .title(title) .content(value) .amendCol {it.labelStyle("text-decoration: underline;")} }
apache-2.0
b783224469200ac934041025c4c4bca2
25.25
126
0.616246
3.940397
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir-fe10-binding/src/org/jetbrains/kotlin/idea/fir/fe10/binding/ToDescriptorBindingContextValueProviders.kt
1
3731
// 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.fir.fe10.binding import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.fir.fe10.* import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice import org.jetbrains.kotlin.utils.addToStdlib.safeAs internal class ToDescriptorBindingContextValueProviders(bindingContext: KtSymbolBasedBindingContext) { private val context = bindingContext.context private val declarationToDescriptorGetters = mutableListOf<(PsiElement) -> DeclarationDescriptor?>() private inline fun <reified K : PsiElement, V : DeclarationDescriptor> KtSymbolBasedBindingContext.registerDeclarationToDescriptorByKey( slice: ReadOnlySlice<K, V>, crossinline getter: (K) -> V? ) { declarationToDescriptorGetters.add { if (it is K) getter(it) else null } registerGetterByKey(slice, { getter(it) }) } init { bindingContext.registerDeclarationToDescriptorByKey(BindingContext.CLASS, this::getClass) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.TYPE_PARAMETER, this::getTypeParameter) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.FUNCTION, this::getFunction) bindingContext.registerDeclarationToDescriptorByKey(BindingContext.CONSTRUCTOR, this::getConstructor) bindingContext.registerGetterByKey(BindingContext.DECLARATION_TO_DESCRIPTOR, this::getDeclarationToDescriptor) } private inline fun <reified T : Any> PsiElement.getKtSymbolOfTypeOrNull(): T? = this@ToDescriptorBindingContextValueProviders.context.withAnalysisSession { [email protected]<KtDeclaration>()?.getSymbol().safeAs<T>() } private fun getClass(key: PsiElement): ClassDescriptor? { val ktClassSymbol = key.getKtSymbolOfTypeOrNull<KtNamedClassOrObjectSymbol>() ?: return null return KtSymbolBasedClassDescriptor(ktClassSymbol, context) } private fun getTypeParameter(key: KtTypeParameter): TypeParameterDescriptor { val ktTypeParameterSymbol = context.withAnalysisSession { key.getTypeParameterSymbol() } return KtSymbolBasedTypeParameterDescriptor(ktTypeParameterSymbol, context) } private fun getFunction(key: PsiElement): SimpleFunctionDescriptor? { val ktFunctionLikeSymbol = key.getKtSymbolOfTypeOrNull<KtFunctionLikeSymbol>() ?: return null return ktFunctionLikeSymbol.toDeclarationDescriptor(context) as? SimpleFunctionDescriptor } private fun getConstructor(key: PsiElement): ConstructorDescriptor? { val ktConstructorSymbol = key.getKtSymbolOfTypeOrNull<KtConstructorSymbol>() ?: return null val containerClass = context.withAnalysisSession { ktConstructorSymbol.getContainingSymbol() } check(containerClass is KtNamedClassOrObjectSymbol) { "Unexpected contained for Constructor symbol: $containerClass, ktConstructorSymbol = $ktConstructorSymbol" } return KtSymbolBasedConstructorDescriptor(ktConstructorSymbol, KtSymbolBasedClassDescriptor(containerClass, context)) } private fun getDeclarationToDescriptor(key: PsiElement): DeclarationDescriptor? { for (getter in declarationToDescriptorGetters) { getter(key)?.let { return it } } return null } }
apache-2.0
05a4f400df050d1a7748e6989abf4126
48.092105
158
0.766551
5.894155
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/codeInspection/incorrectFormatting/CheckingScope.kt
1
8242
// 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.codeInspection.incorrectFormatting; import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.formatting.virtualFormattingListener import com.intellij.lang.LangBundle import com.intellij.lang.LanguageFormatting import com.intellij.openapi.editor.Document import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import kotlin.math.abs class CheckingScope(val file: PsiFile, val document: Document, val manager: InspectionManager, val isOnTheFly: Boolean) { fun createAllReports(changes: List<FormattingChange>): Array<ProblemDescriptor>? { if (changes.isEmpty()) return null // TODO: move to LangBundle.properties // inspection.incorrect.formatting.notification.title=New code style inspection // inspection.incorrect.formatting.notification.contents=It can help you maintain a consistent code style in your codebase in any language // inspection.incorrect.formatting.notification.action.enable=Enable inspection // inspection.incorrect.formatting.notification.action.dont.show=Don’t show again // TODO: move to reformat action //if (silentMode && notificationShown.compareAndSet(false, true)) { // NotificationGroupManager.getInstance() // .getNotificationGroup("Incorrect Formatting") // .createNotification( // LangBundle.message("inspection.incorrect.formatting.notification.title"), // LangBundle.message("inspection.incorrect.formatting.notification.contents"), // NotificationType.INFORMATION // ) // .setImportantSuggestion(false) // .setSuggestionType(true) // .addAction( // createSimpleExpiring(LangBundle.message("inspection.incorrect.formatting.notification.action.enable")) { // InspectionProjectProfileManager // .getInstance(file.project) // .currentProfile // .modifyToolSettings(INSPECTION_KEY, file) { inspection -> // inspection.silentMode = false // } // } // ) // .addAction( // createSimpleExpiring(LangBundle.message("inspection.incorrect.formatting.notification.action.dont.show")) { // InspectionProjectProfileManager // .getInstance(file.project) // .currentProfile // .modifyToolSettings(INSPECTION_KEY, file) { inspection -> // inspection.suppressNotification = true // } // } // ) // .notify(file.project) // // return emptyList() //} val result = arrayListOf<ProblemDescriptor>() // CPP-28543: Disable inspection in case of ShiftIndentChanges // They interfere with WhitespaceReplaces //result += shiftIndentDescriptors(changes) if (changes.any { it is ShiftIndentChange }) { return null } val (indentChanges, inLineChanges) = classifyReplaceChanges(changes) result += indentChangeDescriptors(indentChanges) result += inLineChangeDescriptors(inLineChanges) return result .takeIf { it.isNotEmpty() } ?.toTypedArray() } // Collect all formatting changes for the file fun getChanges(): List<FormattingChange> { if (!LanguageFormatting.INSTANCE.isAutoFormatAllowed(file)) { return emptyList() } val document = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return emptyList() val changeCollector = ChangeCollectingListener(file, document.text) try { file.virtualFormattingListener = changeCollector CodeStyleManager.getInstance(file.project).reformat(file, true) } finally { file.virtualFormattingListener = null } return changeCollector.getChanges() } fun createGlobalReport() = manager.createProblemDescriptor( file, LangBundle.message("inspection.incorrect.formatting.global.problem.descriptor", file.name), arrayOf(ReformatQuickFix, ShowDetailedReportIntention), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, false ) // Shift indent changes, added as is private fun CheckingScope.shiftIndentDescriptors(changes: List<FormattingChange>) = changes .filterIsInstance<ShiftIndentChange>() .mapNotNull { it.toProblemDescriptor(manager, isOnTheFly) } // Distinguish between indent changes and others (aka in-line) private fun CheckingScope.classifyReplaceChanges(changes: List<FormattingChange>): Pair<List<ReplaceChange>, List<ReplaceChange>> { val replaceChange = changes .filterIsInstance<ReplaceChange>() .groupBy { it.isIndentChange(document) } return Pair( replaceChange[true] ?: emptyList(), replaceChange[false] ?: emptyList() ) } // Start line changes, "indents", grouped by consequent lines fun indentChangeDescriptors(indentChanges: List<ReplaceChange>) = sequence { val currentBlock = arrayListOf<ReplaceChange>() indentChanges.forEach { change -> currentBlock.lastOrNull()?.let { prev -> if (!document.areRangesAdjacent(prev.range, change.range)) { yieldAll(createIndentProblemDescriptors(currentBlock)) currentBlock.clear() } } currentBlock.add(change) } yieldAll(createIndentProblemDescriptors(currentBlock)) } fun createIndentProblemDescriptors(changes: ArrayList<ReplaceChange>) = sequence<ProblemDescriptor> { val blockFix = ReplaceQuickFix(changes.map { document.createRangeMarker(it.range) to it.replacement }) changes.forEach { yield( createProblemDescriptor( it.range.excludeLeadingLinefeed(document), it.message(), blockFix, ReformatQuickFix, HideDetailedReportIntention ) ) } } // In-line changes, grouped by line fun inLineChangeDescriptors(inLineChanges: List<ReplaceChange>) = sequence { yieldAll( inLineChanges .groupBy { document.getLineNumber(it.range.startOffset) } .flatMap { (lineNumber, changes) -> val commonFix = ReplaceQuickFix(changes.map { document.createRangeMarker(it.range) to it.replacement }) changes.map { createProblemDescriptor( it.range, it.message(), commonFix, ReformatQuickFix, HideDetailedReportIntention ) } } ) } fun createProblemDescriptor(range: TextRange, message: String, vararg fixes: LocalQuickFix): ProblemDescriptor { val element = file.findElementAt(range.startOffset) val targetElement = element ?: file val targetRange = element ?.textRange ?.intersection(range) ?.shiftLeft(element.textRange.startOffset) // relative range ?: range // original range if no element return manager.createProblemDescriptor( targetElement, targetRange, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, *fixes ) } } private fun Document.areRangesAdjacent(first: TextRange, second: TextRange): Boolean { if (abs(getLineNumber(first.startOffset) - getLineNumber(second.endOffset - 1)) < 2) return true if (abs(getLineNumber(second.startOffset) - getLineNumber(first.endOffset - 1)) < 2) return true return false } private fun TextRange.excludeLeadingLinefeed(document: Document): TextRange { val originalText = substring(document.text) if (originalText.startsWith("\n\r") || originalText.startsWith("\r\n")) { return TextRange(startOffset + 2, endOffset) } if (originalText.startsWith("\n") || originalText.startsWith("\r")) { return TextRange(startOffset + 1, endOffset) } return this }
apache-2.0
f17d469a244d5c7fb462069be826b5c1
35.950673
142
0.684587
4.975845
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KotlinCacheServiceImpl.kt
1
32050
// 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.caches.resolve import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ProjectRootModificationTracker import com.intellij.openapi.util.ModificationTracker import com.intellij.psi.PsiCodeFragment import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.containers.SLRUCache import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForLibrariesName import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForModulesName import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForScriptDependenciesName import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForSdkName import org.jetbrains.kotlin.analyzer.ResolverForProject.Companion.resolverForSpecialInfoName import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.caches.resolve.PlatformAnalysisSettings import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.context.GlobalContext import org.jetbrains.kotlin.context.GlobalContextImpl import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.projectStructure.IDELanguageSettingsProvider import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.useCompositeAnalysis import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibrarySourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.NotUnderContentRootModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptDependenciesInfo import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptDependenciesSourceInfo import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptModuleInfo import org.jetbrains.kotlin.idea.caches.project.* import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.caches.resolve.util.GlobalFacadeModuleFilters import org.jetbrains.kotlin.idea.caches.resolve.util.contextWithCompositeExceptionTracker import org.jetbrains.kotlin.idea.caches.trackers.outOfBlockModificationCount import org.jetbrains.kotlin.idea.core.script.ScriptDependenciesModificationTracker import org.jetbrains.kotlin.idea.core.script.dependencies.ScriptAdditionalIdeaDependenciesProvider import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.hasSuppressAnnotation import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.contains import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.diagnostics.KotlinSuppressCache import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.sumByLong internal val LOG = Logger.getInstance(KotlinCacheService::class.java) data class PlatformAnalysisSettingsImpl( val platform: TargetPlatform, val sdk: Sdk?, val isAdditionalBuiltInFeaturesSupported: Boolean, ) : PlatformAnalysisSettings object CompositeAnalysisSettings : PlatformAnalysisSettings fun createPlatformAnalysisSettings( project: Project, platform: TargetPlatform, sdk: Sdk?, isAdditionalBuiltInFeaturesSupported: Boolean ): PlatformAnalysisSettings { return if (project.useCompositeAnalysis) { CompositeAnalysisSettings } else { PlatformAnalysisSettingsImpl(platform, sdk, isAdditionalBuiltInFeaturesSupported) } } class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService { override fun getResolutionFacade(element: KtElement): ResolutionFacade { val file = element.fileForElement() if (file.isScript()) { // Scripts support seem to modify some of the important aspects via file user data without triggering PsiModificationTracker. // If in doubt, run ScriptDefinitionsOrderTestGenerated val settings = file.moduleInfo.platformSettings(file.platform) return getFacadeToAnalyzeFile(file, settings) } else { return CachedValuesManager.getCachedValue(file) { val settings = file.moduleInfo.platformSettings(file.platform) CachedValueProvider.Result( getFacadeToAnalyzeFile(file, settings), PsiModificationTracker.MODIFICATION_COUNT, ProjectRootModificationTracker.getInstance(project), ) } } } override fun getResolutionFacade(elements: List<KtElement>): ResolutionFacade { val files = getFilesForElements(elements) if (files.size == 1) return getResolutionFacade(files.single()) val platform = files.first().platform // it is quite suspicious that we take first().moduleInfo, while there might be multiple files of different kinds (e.g. // some might be "special", see case chasing in [getFacadeToAnalyzeFiles] later val settings = files.first().moduleInfo.platformSettings(platform) return getFacadeToAnalyzeFiles(files, settings) } // Implementation note: currently, it provides platform-specific view on common sources via plain creation of // separate GlobalFacade even when CompositeAnalysis is enabled. // // Because GlobalFacade retains a lot of memory and is cached per-platform, calling this function with non-simple TargetPlatforms // (e.g. with {JVM, Android}, {JVM_1.6, JVM_1.8}, etc.) might lead to explosive growth of memory consumption, so such calls are // logged as errors currently and require immediate attention. override fun getResolutionFacadeWithForcedPlatform(elements: List<KtElement>, platform: TargetPlatform): ResolutionFacade { val files = getFilesForElements(elements) val moduleInfo = files.first().moduleInfo val settings = PlatformAnalysisSettingsImpl(platform, moduleInfo.sdk, moduleInfo.supportsAdditionalBuiltInsMembers(project)) if (!canGetFacadeWithForcedPlatform(elements, files, moduleInfo, platform)) { // Fallback to facade without forced platform return getResolutionFacade(elements) } // Note that there's no need to switch on project.useCompositeAnalysis // - For SEPARATE analysis, using 'PlatformAnalysisSettingsImpl' is totally OK, and actually that's what we'd create normally // // - For COMPOSITE analysis, we intentionally want to use 'PlatformAnalysisSettingsImpl' to re-analyze code in separate // platform-specific facade, even though normally we'd create CompositeAnalysisSettings. // Some branches in [getFacadeToAnalyzeFile] in such case will be effectively dead due to [canGetFacadeWithForcedPlatform] // (e.g. everything script-related), but, for example, special-files are still needed, so one can't just skip straight to // [getResolutionFacadeByModuleInfoAndSettings] instead return getFacadeToAnalyzeFiles(files, settings) } private fun canGetFacadeWithForcedPlatform( elements: List<KtElement>, files: List<KtFile>, moduleInfo: IdeaModuleInfo, platform: TargetPlatform ): Boolean { val specialFiles = files.filterNotInProjectSource(moduleInfo) val scripts = specialFiles.filterScripts() return when { platform.size > 1 -> { LOG.error( "Getting resolution facade with non-trivial platform $platform is strongly discouraged,\n" + "as it can lead to heavy memory consumption. Facade with non-forced platform will be used instead." ) false } moduleInfo is ScriptDependenciesInfo || moduleInfo is ScriptDependenciesSourceInfo -> { LOG.error( "Getting resolution facade for ScriptDependencies is not supported\n" + "Requested elements: $elements\n" + "Files for requested elements: $files\n" + "Module info for the first file: $moduleInfo" ) false } scripts.isNotEmpty() -> { LOG.error( "Getting resolution facade with forced platform is not supported for scripts\n" + "Requested elements: $elements\n" + "Files for requested elements: $files\n" + "Among them, following are scripts: $scripts" ) false } else -> true } } private fun getFilesForElements(elements: List<KtElement>): List<KtFile> { return elements.map { it.fileForElement() }.distinct() } private fun KtElement.fileForElement() = try { // in theory `containingKtFile` is `@NotNull` but in practice EA-114080 @Suppress("USELESS_ELVIS") containingKtFile ?: throw IllegalStateException("containingKtFile was null for $this of ${this.javaClass}") } catch (e: Exception) { if (e is ControlFlowException) throw e throw KotlinExceptionWithAttachments("Couldn't get containingKtFile for ktElement", e) .withPsiAttachment("element", this) .withPsiAttachment("file", this.containingFile) .withAttachment("original", e.message) } override fun getSuppressionCache(): KotlinSuppressCache = kotlinSuppressCache.value private val globalFacadesPerPlatformAndSdk: SLRUCache<PlatformAnalysisSettings, GlobalFacade> = object : SLRUCache<PlatformAnalysisSettings, GlobalFacade>(2 * 3 * 2, 2 * 3 * 2) { override fun createValue(settings: PlatformAnalysisSettings): GlobalFacade { return GlobalFacade(settings) } } private val facadeForScriptDependenciesForProject = createFacadeForScriptDependencies(ScriptDependenciesInfo.ForProject(project)) private fun createFacadeForScriptDependencies( dependenciesModuleInfo: ScriptDependenciesInfo ): ProjectResolutionFacade { val sdk = dependenciesModuleInfo.sdk val platform = JvmPlatforms.defaultJvmPlatform // TODO: Js scripts? val settings = createPlatformAnalysisSettings(project, platform, sdk, true) val dependenciesForScriptDependencies = listOf( LibraryModificationTracker.getInstance(project), ProjectRootModificationTracker.getInstance(project), ScriptDependenciesModificationTracker.getInstance(project) ) val scriptFile = (dependenciesModuleInfo as? ScriptDependenciesInfo.ForFile)?.scriptFile val relatedModules = scriptFile?.let { ScriptAdditionalIdeaDependenciesProvider.getRelatedModules(it, project) } val globalFacade = if (relatedModules?.isNotEmpty() == true) { facadeForModules(settings) } else { getOrBuildGlobalFacade(settings).facadeForSdk } val globalContext = globalFacade.globalContext.contextWithCompositeExceptionTracker(project, "facadeForScriptDependencies") return ProjectResolutionFacade( "facadeForScriptDependencies", resolverForScriptDependenciesName, project, globalContext, settings, reuseDataFrom = globalFacade, allModules = dependenciesModuleInfo.dependencies(), //TODO: provide correct trackers dependencies = dependenciesForScriptDependencies, moduleFilter = { it == dependenciesModuleInfo }, invalidateOnOOCB = true ) } private inner class GlobalFacade(settings: PlatformAnalysisSettings) { private val sdkContext = GlobalContext(resolverForSdkName) private val moduleFilters = GlobalFacadeModuleFilters(project) val facadeForSdk = ProjectResolutionFacade( "facadeForSdk", "$resolverForSdkName with settings=$settings", project, sdkContext, settings, moduleFilter = moduleFilters::sdkFacadeFilter, dependencies = listOf( LibraryModificationTracker.getInstance(project), ProjectRootModificationTracker.getInstance(project) ), invalidateOnOOCB = false, reuseDataFrom = null ) private val librariesContext = sdkContext.contextWithCompositeExceptionTracker(project, resolverForLibrariesName) val facadeForLibraries = ProjectResolutionFacade( "facadeForLibraries", "$resolverForLibrariesName with settings=$settings", project, librariesContext, settings, reuseDataFrom = facadeForSdk, moduleFilter = moduleFilters::libraryFacadeFilter, invalidateOnOOCB = false, dependencies = listOf( LibraryModificationTracker.getInstance(project), ProjectRootModificationTracker.getInstance(project) ) ) private val modulesContext = librariesContext.contextWithCompositeExceptionTracker(project, resolverForModulesName) val facadeForModules = ProjectResolutionFacade( "facadeForModules", "$resolverForModulesName with settings=$settings", project, modulesContext, settings, reuseDataFrom = facadeForLibraries, moduleFilter = moduleFilters::moduleFacadeFilter, dependencies = listOf( LibraryModificationTracker.getInstance(project), ProjectRootModificationTracker.getInstance(project) ), invalidateOnOOCB = true ) } private fun IdeaModuleInfo.platformSettings(targetPlatform: TargetPlatform) = createPlatformAnalysisSettings( [email protected], targetPlatform, sdk, supportsAdditionalBuiltInsMembers([email protected]) ) private fun facadeForModules(settings: PlatformAnalysisSettings) = getOrBuildGlobalFacade(settings).facadeForModules private fun librariesFacade(settings: PlatformAnalysisSettings) = getOrBuildGlobalFacade(settings).facadeForLibraries @Synchronized private fun getOrBuildGlobalFacade(settings: PlatformAnalysisSettings) = globalFacadesPerPlatformAndSdk[settings] // explicitSettings allows to override the "innate" settings of the files' moduleInfo // This can be useful, if the module is common, but we want to create a facade to // analyze that module from the platform (e.g. JVM) point of view private fun createFacadeForFilesWithSpecialModuleInfo( files: Set<KtFile>, explicitSettings: PlatformAnalysisSettings? = null ): ProjectResolutionFacade { // we assume that all files come from the same module val targetPlatform = files.map { it.platform }.toSet().single() val specialModuleInfo = files.map { it.moduleInfo }.toSet().single() val settings = explicitSettings ?: specialModuleInfo.platformSettings(specialModuleInfo.platform) // Dummy files created e.g. by J2K do not receive events. val dependencyTrackerForSyntheticFileCache = if (files.all { it.originalFile != it }) { ModificationTracker { files.sumByLong { it.outOfBlockModificationCount } } } else ModificationTracker { files.sumByLong { it.modificationStamp } } val resolverDebugName = "$resolverForSpecialInfoName $specialModuleInfo for files ${files.joinToString { it.name }} for platform $targetPlatform" fun makeProjectResolutionFacade( debugName: String, globalContext: GlobalContextImpl, reuseDataFrom: ProjectResolutionFacade? = null, moduleFilter: (IdeaModuleInfo) -> Boolean = { true }, allModules: Collection<IdeaModuleInfo>? = null ): ProjectResolutionFacade { return ProjectResolutionFacade( debugName, resolverDebugName, project, globalContext, settings, syntheticFiles = files, reuseDataFrom = reuseDataFrom, moduleFilter = moduleFilter, dependencies = listOf( dependencyTrackerForSyntheticFileCache, ProjectRootModificationTracker.getInstance(project) ), invalidateOnOOCB = true, allModules = allModules ) } return when { specialModuleInfo is ModuleSourceInfo -> { val dependentModules = specialModuleInfo.getDependentModules() val modulesFacade = facadeForModules(settings) val globalContext = modulesFacade.globalContext.contextWithCompositeExceptionTracker( project, "facadeForSpecialModuleInfo (ModuleSourceInfo)" ) makeProjectResolutionFacade( "facadeForSpecialModuleInfo (ModuleSourceInfo)", globalContext, reuseDataFrom = modulesFacade, moduleFilter = { it in dependentModules } ) } specialModuleInfo is ScriptModuleInfo -> { val facadeForScriptDependencies = createFacadeForScriptDependencies( ScriptDependenciesInfo.ForFile(project, specialModuleInfo.scriptFile, specialModuleInfo.scriptDefinition) ) val globalContext = facadeForScriptDependencies.globalContext.contextWithCompositeExceptionTracker( project, "facadeForSpecialModuleInfo (ScriptModuleInfo)" ) makeProjectResolutionFacade( "facadeForSpecialModuleInfo (ScriptModuleInfo)", globalContext, reuseDataFrom = facadeForScriptDependencies, allModules = specialModuleInfo.dependencies(), moduleFilter = { it == specialModuleInfo } ) } specialModuleInfo is ScriptDependenciesInfo -> facadeForScriptDependenciesForProject specialModuleInfo is ScriptDependenciesSourceInfo -> { val globalContext = facadeForScriptDependenciesForProject.globalContext.contextWithCompositeExceptionTracker( project, "facadeForSpecialModuleInfo (ScriptDependenciesSourceInfo)" ) makeProjectResolutionFacade( "facadeForSpecialModuleInfo (ScriptDependenciesSourceInfo)", globalContext, reuseDataFrom = facadeForScriptDependenciesForProject, allModules = specialModuleInfo.dependencies(), moduleFilter = { it == specialModuleInfo } ) } specialModuleInfo is LibrarySourceInfo || specialModuleInfo === NotUnderContentRootModuleInfo -> { val librariesFacade = librariesFacade(settings) val debugName = "facadeForSpecialModuleInfo (LibrarySourceInfo or NotUnderContentRootModuleInfo)" val globalContext = librariesFacade.globalContext.contextWithCompositeExceptionTracker(project, debugName) makeProjectResolutionFacade( debugName, globalContext, reuseDataFrom = librariesFacade, moduleFilter = { it == specialModuleInfo } ) } specialModuleInfo.isLibraryClasses() -> { //NOTE: this code should not be called for sdk or library classes // currently the only known scenario is when we cannot determine that file is a library source // (file under both classes and sources root) LOG.warn("Creating cache with synthetic files ($files) in classes of library $specialModuleInfo") val globalContext = GlobalContext("facadeForSpecialModuleInfo for file under both classes and root") makeProjectResolutionFacade( "facadeForSpecialModuleInfo for file under both classes and root", globalContext ) } else -> throw IllegalStateException("Unknown IdeaModuleInfo ${specialModuleInfo::class.java}") } } private val kotlinSuppressCache: CachedValue<KotlinSuppressCache> = CachedValuesManager.getManager(project).createCachedValue( { CachedValueProvider.Result( object : KotlinSuppressCache() { override fun getSuppressionAnnotations(annotated: PsiElement): List<AnnotationDescriptor> { if (annotated !is KtAnnotated) return emptyList() if (!annotated.hasSuppressAnnotation) { // Avoid running resolve heuristics return emptyList() } val context = when (annotated) { is KtFile -> annotated.fileAnnotationList?.safeAnalyze(BodyResolveMode.PARTIAL_NO_ADDITIONAL) is KtModifierListOwner -> annotated.modifierList?.safeAnalyze(BodyResolveMode.PARTIAL_NO_ADDITIONAL) else -> annotated.safeAnalyze(BodyResolveMode.PARTIAL_NO_ADDITIONAL) } ?: return emptyList() val annotatedDescriptor = context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, annotated) if (annotatedDescriptor != null) { return annotatedDescriptor.annotations.toList() } return annotated.annotationEntries.mapNotNull { context.get(BindingContext.ANNOTATION, it) } } }, LibraryModificationTracker.getInstance(project), PsiModificationTracker.MODIFICATION_COUNT ) }, false ) private val specialFilesCacheProvider = CachedValueProvider { // NOTE: computations inside createFacadeForFilesWithSpecialModuleInfo depend on project root structure // so we additionally drop the whole slru cache on change CachedValueProvider.Result( object : SLRUCache<Pair<Set<KtFile>, PlatformAnalysisSettings>, ProjectResolutionFacade>(2, 3) { override fun createValue(filesAndSettings: Pair<Set<KtFile>, PlatformAnalysisSettings>) = createFacadeForFilesWithSpecialModuleInfo(filesAndSettings.first, filesAndSettings.second) }, LibraryModificationTracker.getInstance(project), ProjectRootModificationTracker.getInstance(project) ) } private fun getFacadeForSpecialFiles(files: Set<KtFile>, settings: PlatformAnalysisSettings): ProjectResolutionFacade { val cachedValue: SLRUCache<Pair<Set<KtFile>, PlatformAnalysisSettings>, ProjectResolutionFacade> = CachedValuesManager.getManager(project).getCachedValue(project, specialFilesCacheProvider) // In Upsource, we create multiple instances of KotlinCacheService, which all access the same CachedValue instance (UP-8046) // This is so because class name of provider is used as a key when fetching cached value, see CachedValueManager.getKeyForClass. // To avoid race conditions, we can't use any local lock to access the cached value contents. return cachedValue.getOrCreateValue(files to settings) } private val scriptsCacheProvider = CachedValueProvider { CachedValueProvider.Result( object : SLRUCache<Set<KtFile>, ProjectResolutionFacade>(10, 5) { override fun createValue(files: Set<KtFile>) = createFacadeForFilesWithSpecialModuleInfo(files) }, LibraryModificationTracker.getInstance(project), ProjectRootModificationTracker.getInstance(project), ScriptDependenciesModificationTracker.getInstance(project) ) } private fun getFacadeForScripts(files: Set<KtFile>): ProjectResolutionFacade { val cachedValue: SLRUCache<Set<KtFile>, ProjectResolutionFacade> = CachedValuesManager.getManager(project).getCachedValue(project, scriptsCacheProvider) return cachedValue.getOrCreateValue(files) } private fun <K, V> SLRUCache<K, V>.getOrCreateValue(key: K): V = synchronized(this) { this.getIfCached(key) } ?: run { // do actual value calculation out of any locks // trade-off: several instances could be created, but only one would be used val newValue = this.createValue(key)!! synchronized(this) { val cached = this.getIfCached(key) cached ?: run { this.put(key, newValue) newValue } } } private fun getFacadeToAnalyzeFiles(files: Collection<KtFile>, settings: PlatformAnalysisSettings): ResolutionFacade { val moduleInfo = files.first().moduleInfo val specialFiles = files.filterNotInProjectSource(moduleInfo) val scripts = specialFiles.filterScripts() if (scripts.isNotEmpty()) { val projectFacade = getFacadeForScripts(scripts) return ModuleResolutionFacadeImpl(projectFacade, moduleInfo).createdFor(scripts, moduleInfo, settings) } if (specialFiles.isNotEmpty()) { val projectFacade = getFacadeForSpecialFiles(specialFiles, settings) return ModuleResolutionFacadeImpl(projectFacade, moduleInfo).createdFor(specialFiles, moduleInfo, settings) } return getResolutionFacadeByModuleInfoAndSettings(moduleInfo, settings).createdFor(emptyList(), moduleInfo, settings) } private fun getFacadeToAnalyzeFile(file: KtFile, settings: PlatformAnalysisSettings): ResolutionFacade { val moduleInfo = file.moduleInfo val specialFile = filterNotInProjectSource(file, moduleInfo) specialFile?.filterScript()?.let { script -> val scripts = setOf(script) val projectFacade = getFacadeForScripts(scripts) return ModuleResolutionFacadeImpl(projectFacade, moduleInfo).createdFor(scripts, moduleInfo, settings) } if (specialFile != null) { val specialFiles = setOf(specialFile) val projectFacade = getFacadeForSpecialFiles(specialFiles, settings) return ModuleResolutionFacadeImpl(projectFacade, moduleInfo).createdFor(specialFiles, moduleInfo, settings) } return getResolutionFacadeByModuleInfoAndSettings(moduleInfo, settings).createdFor(emptyList(), moduleInfo, settings) } override fun getResolutionFacadeByFile(file: PsiFile, platform: TargetPlatform): ResolutionFacade? { if (!RootKindFilter.everything.matches(file)) { return null } assert(file !is PsiCodeFragment) val moduleInfo = file.moduleInfo return getResolutionFacadeByModuleInfo(moduleInfo, platform) } private fun getResolutionFacadeByModuleInfo(moduleInfo: IdeaModuleInfo, platform: TargetPlatform): ResolutionFacade { val settings = moduleInfo.platformSettings(platform) return getResolutionFacadeByModuleInfoAndSettings(moduleInfo, settings) } private fun getResolutionFacadeByModuleInfoAndSettings( moduleInfo: IdeaModuleInfo, settings: PlatformAnalysisSettings ): ResolutionFacade { val projectFacade = when (moduleInfo) { is ScriptDependenciesInfo.ForProject, is ScriptDependenciesSourceInfo.ForProject -> facadeForScriptDependenciesForProject is ScriptDependenciesInfo.ForFile -> createFacadeForScriptDependencies(moduleInfo) else -> facadeForModules(settings) } return ModuleResolutionFacadeImpl(projectFacade, moduleInfo) } override fun getResolutionFacadeByModuleInfo(moduleInfo: ModuleInfo, platform: TargetPlatform): ResolutionFacade? = (moduleInfo as? IdeaModuleInfo)?.let { getResolutionFacadeByModuleInfo(it, platform) } override fun getResolutionFacadeByModuleInfo(moduleInfo: ModuleInfo, settings: PlatformAnalysisSettings): ResolutionFacade? { val ideaModuleInfo = moduleInfo as? IdeaModuleInfo ?: return null return getResolutionFacadeByModuleInfoAndSettings(ideaModuleInfo, settings) } private fun Collection<KtFile>.filterNotInProjectSource(moduleInfo: IdeaModuleInfo): Set<KtFile> = mapNotNullTo(mutableSetOf()) { filterNotInProjectSource(it, moduleInfo) } private fun filterNotInProjectSource(file: KtFile, moduleInfo: IdeaModuleInfo): KtFile? { val fileToAnalyze = when (file) { is KtCodeFragment -> file.getContextFile() else -> file } if (fileToAnalyze == null) { return null } val isInProjectSource = RootKindFilter.projectSources.matches(fileToAnalyze) && moduleInfo.contentScope.contains(fileToAnalyze) return if (!isInProjectSource) fileToAnalyze else null } private fun Collection<KtFile>.filterScripts(): Set<KtFile> = mapNotNullTo(mutableSetOf()) { it.filterScript() } private fun KtFile.filterScript(): KtFile? { val contextFile = if (this is KtCodeFragment) this.getContextFile() else this return contextFile?.takeIf { it.isScript() } } private fun KtFile.isScript(): Boolean { val contextFile = if (this is KtCodeFragment) this.getContextFile() else this return contextFile?.isScript() ?: false } private fun KtCodeFragment.getContextFile(): KtFile? { val contextElement = context ?: return null val contextFile = (contextElement as? KtElement)?.containingKtFile ?: throw AssertionError("Analyzing kotlin code fragment of type ${this::class.java} with java context of type ${contextElement::class.java}") return if (contextFile is KtCodeFragment) contextFile.getContextFile() else contextFile } } fun IdeaModuleInfo.supportsAdditionalBuiltInsMembers(project: Project): Boolean { return IDELanguageSettingsProvider .getLanguageVersionSettings(this, project) .supportsFeature(LanguageFeature.AdditionalBuiltInsMembers) } val IdeaModuleInfo.sdk: Sdk? get() = dependencies().firstIsInstanceOrNull<SdkInfo>()?.sdk
apache-2.0
75a1cfec13a9403175dc487c8bd40174
48.922118
153
0.690234
6.385734
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/StringEntityImpl.kt
2
6150
// 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.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class StringEntityImpl(val dataSource: StringEntityData) : StringEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val data: String get() = dataSource.data override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: StringEntityData?) : ModifiableWorkspaceEntityBase<StringEntity, StringEntityData>(result), StringEntity.Builder { constructor() : this(StringEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity StringEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field StringEntity#data should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as StringEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData(true).data = value changedProperty.add("data") } override fun getEntityClass(): Class<StringEntity> = StringEntity::class.java } } class StringEntityData : WorkspaceEntityData<StringEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<StringEntity> { val modifiable = StringEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): StringEntity { return getCached(snapshot) { val entity = StringEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return StringEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return StringEntity(data, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as StringEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as StringEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
51a3d74a3547fe2025451fee069f8d73
31.03125
138
0.726504
5.242967
false
false
false
false
moshbit/Kotlift
test-src/14_generics.kt
2
529
class Box<T>(t: T) { var value: T // value = t won't work, as this must happen in swift inside constructor fun doNothing(value2: T) : T { return value } init { value = t } } class BigBox<T>(t: T) { var value1: T val value2: T init { value1 = t value2 = t } } fun main(args: Array<String>) { val box: Box<Int> = Box<Int>(t = 1) println(box) val box2 = Box(t = 2) println(box2) println(box.doNothing(4)) val bigBox = BigBox(t = 3) println(bigBox.value1 + bigBox.value2) }
apache-2.0
1471de2339d32b27d075a2908872b864
14.588235
87
0.586011
2.769634
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/styling/InsertImageAction.kt
5
3115
// 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.ui.actions.styling import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.ReadOnlyFragmentModificationException import com.intellij.openapi.editor.ReadOnlyModificationException import com.intellij.openapi.editor.actionSystem.EditorActionManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.Messages import com.intellij.refactoring.RefactoringBundle import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.images.ConfigureImageDialog import org.intellij.plugins.markdown.editor.images.ImageUtils import org.intellij.plugins.markdown.editor.images.MarkdownImageData import org.intellij.plugins.markdown.ui.actions.MarkdownActionPlaces import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil class InsertImageAction: DumbAwareAction() { init { addTextOverride(MarkdownActionPlaces.INSERT_POPUP) { MarkdownBundle.message("action.org.intellij.plugins.markdown.ui.actions.styling.InsertImageAction.insert.popup.text") } } override fun update(event: AnActionEvent) { val editor = MarkdownActionUtil.findMarkdownEditor(event) event.presentation.apply { isVisible = editor != null isEnabled = editor?.document?.isWritable == true } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun actionPerformed(event: AnActionEvent) { val editor = MarkdownActionUtil.findRequiredMarkdownEditor(event) val project = editor.project ConfigureImageDialog(project, MarkdownBundle.message("markdown.insert.image.dialog.title")).show { imageData -> val document = editor.document val imageText = buildImageText(imageData) try { WriteCommandAction.runWriteCommandAction(project, templateText, null, { editor.caretModel.runForEachCaret { caret -> val offset = caret.offset document.insertString(offset, imageText) caret.moveToOffset(offset + imageText.length) } }) } catch (exception: ReadOnlyModificationException) { Messages.showErrorDialog(project, exception.localizedMessage, RefactoringBundle.message("error.title")) } catch (exception: ReadOnlyFragmentModificationException) { EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(exception) } } } private fun buildImageText(imageData: MarkdownImageData): String { return when { imageData.shouldConvertToHtml -> { ImageUtils.createHtmlImageText(imageData) } else -> { val (path, _, _, title, description) = imageData ImageUtils.createMarkdownImageText(description, path, title) } } } }
apache-2.0
34cf9df9c158ef965a10ee2321d506a6
41.094595
158
0.762119
4.905512
false
false
false
false
siosio/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/fus/PackageSearchEventsLogger.kt
1
8462
package com.jetbrains.packagesearch.intellij.plugin.fus import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventId3 import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.tryDoing import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules private const val FUS_ENABLED = false // See the documentation at https://confluence.jetbrains.com/display/FUS/IntelliJ+Reporting+API internal class PackageSearchEventsLogger : CounterUsagesCollector() { override fun getGroup() = GROUP override fun getVersion() = VERSION companion object { private const val VERSION = 2 private val GROUP = EventLogGroup(FUSGroupIds.GROUP_ID, VERSION) // FIELDS private val coordinatesField = EventFields.StringValidatedByCustomRule(FUSGroupIds.COORDINATES, FUSGroupIds.COORDINATES) private val scopeField = EventFields.StringValidatedByCustomRule(FUSGroupIds.SCOPE, FUSGroupIds.SCOPE) private val buildSystemField = EventFields.StringValidatedByCustomRule(FUSGroupIds.BUILD_SYSTEM, FUSGroupIds.BUILD_SYSTEM) private val repositoryIdField = EventFields.StringValidatedByCustomRule(FUSGroupIds.REPOSITORY_ID, FUSGroupIds.REPOSITORY_ID) private val repositoryUrlField = EventFields.StringValidatedByCustomRule(FUSGroupIds.REPOSITORY_URL, FUSGroupIds.REPOSITORY_URL) private val packageIsInstalledField = EventFields.Boolean(FUSGroupIds.PACKAGE_IS_INSTALLED) internal val preferencesGradleScopesField = EventFields.StringValidatedByCustomRule(FUSGroupIds.PREFERENCES_GRADLE_SCOPES, FUSGroupIds.PREFERENCES_GRADLE_SCOPES) internal val preferencesUpdateScopesOnUsageField = EventFields.StringValidatedByCustomRule(FUSGroupIds.PREFERENCES_UPDATE_SCOPES_ON_USAGE, FUSGroupIds.PREFERENCES_UPDATE_SCOPES_ON_USAGE) internal val preferencesDefaultGradleScopeField = EventFields.StringValidatedByCustomRule(FUSGroupIds.PREFERENCES_DEFAULT_GRADLE_SCOPE, FUSGroupIds.PREFERENCES_DEFAULT_GRADLE_SCOPE) internal val preferencesDefaultMavenScopeField = EventFields.StringValidatedByCustomRule(FUSGroupIds.PREFERENCES_DEFAULT_MAVEN_SCOPE, FUSGroupIds.PREFERENCES_DEFAULT_MAVEN_SCOPE) private val targetModuleNameField = EventFields.String( FUSGroupIds.TARGET_MODULE_NAME, listOfNotNull( TargetModules.None::class.simpleName, TargetModules.One::class.simpleName, TargetModules.All::class.simpleName, ) ) private val quickFixTypeField = EventFields.Enum(FUSGroupIds.QUICK_FIX_TYPE, FUSGroupIds.QuickFixTypes::class.java) private val quickFixFileTypeField = EventFields.StringValidatedByCustomRule(FUSGroupIds.FILE_TYPE, FUSGroupIds.FILE_TYPE) private val detailsLinkLabelField = EventFields.Enum(FUSGroupIds.DETAILS_LINK_LABEL, FUSGroupIds.DetailsLinkTypes::class.java) private val detailsLinkUrlField = EventFields.StringValidatedByCustomRule(FUSGroupIds.DETAILS_LINK_URL, FUSGroupIds.DETAILS_LINK_URL) private val toggleTypeField = EventFields.Enum(FUSGroupIds.DETAILS_VISIBLE, FUSGroupIds.ToggleTypes::class.java) private val valueField = EventFields.Boolean(FUSGroupIds.DETAILS_VISIBLE) private val searchRequestField = EventFields.StringValidatedByCustomRule(FUSGroupIds.SEARCH_QUERY, FUSGroupIds.SEARCH_QUERY) // EVENTS private val packageInstalledEvent = GROUP.registerEvent(FUSGroupIds.PACKAGE_INSTALLED, coordinatesField, scopeField, buildSystemField) private val packageRemovedEvent = GROUP.registerEvent(FUSGroupIds.PACKAGE_REMOVED, coordinatesField, scopeField, buildSystemField) private val packageUpdatedEvent = GROUP.registerEvent(FUSGroupIds.PACKAGE_UPDATED, coordinatesField, scopeField, buildSystemField) private val repositoryAddedEvent = GROUP.registerEvent(FUSGroupIds.REPOSITORY_ADDED, repositoryIdField, repositoryUrlField) private val repositoryRemovedEvent = GROUP.registerEvent(FUSGroupIds.REPOSITORY_REMOVED, repositoryIdField, repositoryUrlField) private val preferencesChangedEvent = GROUP.registerVarargEvent(FUSGroupIds.PREFERENCES_CHANGED) private val preferencesResetEvent = GROUP.registerEvent(FUSGroupIds.PREFERENCES_RESET) private val packageSelectedEvent = GROUP.registerEvent(FUSGroupIds.PACKAGE_SELECTED, packageIsInstalledField) private val moduleSelectedEvent = GROUP.registerEvent(FUSGroupIds.MODULE_SELECTED, targetModuleNameField) private val runQuickFixEvent = GROUP.registerEvent(FUSGroupIds.RUN_QUICK_FIX, quickFixTypeField, quickFixFileTypeField) private val detailsLinkClickEvent = GROUP.registerEvent(FUSGroupIds.DETAILS_LINK_CLICK, detailsLinkLabelField, detailsLinkUrlField) private val toggleEvent = GROUP.registerEvent(FUSGroupIds.TOGGLE, toggleTypeField, valueField) private val searchRequestEvent = GROUP.registerEvent(FUSGroupIds.SEARCH_REQUEST, searchRequestField) private val searchQueryClearEvent = GROUP.registerEvent(FUSGroupIds.SEARCH_QUERY_CLEAR) private val upgradeAllEvent = GROUP.registerEvent(FUSGroupIds.UPGRADE_ALL) private fun EventId3<String?, String?, String?>.logPackage(dependency: UnifiedDependency, targetModule: ProjectModule) { tryDoing { val coordinates = dependency.coordinates.displayName val scope = dependency.scope val buildSystem = targetModule.buildSystemType.name log(coordinates, scope, buildSystem) } } fun logPackageInstalled(dependency: UnifiedDependency, targetModule: ProjectModule) = ifLoggingEnabled { packageInstalledEvent.logPackage(dependency, targetModule) } fun logPackageRemoved(dependency: UnifiedDependency, targetModule: ProjectModule) = ifLoggingEnabled { packageRemovedEvent.logPackage(dependency, targetModule) } fun logPackageUpdated(dependency: UnifiedDependency, targetModule: ProjectModule) = ifLoggingEnabled { packageUpdatedEvent.logPackage(dependency, targetModule) } fun logRepositoryAdded(model: UnifiedDependencyRepository) = ifLoggingEnabled { repositoryAddedEvent.log(model.id, model.url) } fun logRepositoryRemoved(model: UnifiedDependencyRepository) = ifLoggingEnabled { repositoryRemovedEvent.log(model.id, model.url) } fun logPreferencesChanged(vararg preferences: EventPair<String?>) = ifLoggingEnabled { preferencesChangedEvent.log(*preferences) } fun logPreferencesReset() = ifLoggingEnabled { preferencesResetEvent.log() } fun logModuleSelected(targetModuleName: String?) = ifLoggingEnabled { moduleSelectedEvent.log(targetModuleName) } fun logRunQuickFix(type: FUSGroupIds.QuickFixTypes, fileType: String?) = ifLoggingEnabled { runQuickFixEvent.log(type, fileType) } fun logPackageSelected(isInstalled: Boolean) = ifLoggingEnabled { packageSelectedEvent.log(isInstalled) } fun logDetailsLinkClick(type: FUSGroupIds.DetailsLinkTypes, url: String) = ifLoggingEnabled { detailsLinkClickEvent.log(type, url) } fun logToggle(type: FUSGroupIds.ToggleTypes, state: Boolean) = ifLoggingEnabled { toggleEvent.log(type, state) } fun logSearchRequest(query: String) = ifLoggingEnabled { searchRequestEvent.log(query) } fun logSearchQueryClear() = ifLoggingEnabled { searchQueryClearEvent.log() } fun logUpgradeAll() { upgradeAllEvent.log() } private fun ifLoggingEnabled(action: () -> Unit) { if (FUS_ENABLED) tryDoing { action() } } } }
apache-2.0
3f92945a865c36d7d500720fcf17688f
55.791946
147
0.750886
5.548852
false
false
false
false
smmribeiro/intellij-community
platform/diff-impl/tests/testSrc/com/intellij/diff/merge/MergeTestBase.kt
4
15022
// 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.diff.merge import com.intellij.diff.DiffContentFactoryImpl import com.intellij.diff.HeavyDiffTestCase import com.intellij.diff.contents.DocumentContent import com.intellij.diff.merge.MergeTestBase.SidesState.* import com.intellij.diff.merge.TextMergeViewer.MyThreesideViewer import com.intellij.diff.tools.util.base.IgnorePolicy import com.intellij.diff.tools.util.base.TextDiffSettingsHolder.TextDiffSettings import com.intellij.diff.util.* import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.openapi.project.Project import com.intellij.openapi.util.Couple import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.util.ui.UIUtil abstract class MergeTestBase : HeavyDiffTestCase() { fun test1(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, 1, f) } fun test2(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, 2, f) } fun testN(left: String, base: String, right: String, f: TestBuilder.() -> Unit) { test(left, base, right, -1, f) } fun test(left: String, base: String, right: String, changesCount: Int, f: TestBuilder.() -> Unit) { test(left, base, right, changesCount, IgnorePolicy.DEFAULT, f) } fun test(left: String, base: String, right: String, changesCount: Int, policy: IgnorePolicy, f: TestBuilder.() -> Unit) { val contentFactory = DiffContentFactoryImpl() val leftContent: DocumentContent = contentFactory.create(parseSource(left)) val baseContent: DocumentContent = contentFactory.create(parseSource(base)) val rightContent: DocumentContent = contentFactory.create(parseSource(right)) val outputContent: DocumentContent = contentFactory.create(parseSource("")) outputContent.document.setReadOnly(false) val context = MockMergeContext(project) val request = MockMergeRequest(leftContent, baseContent, rightContent, outputContent) val settings = TextDiffSettings() settings.ignorePolicy = policy context.putUserData(TextDiffSettings.KEY, settings) val viewer = TextMergeTool.INSTANCE.createComponent(context, request) as TextMergeViewer try { val toolbar = viewer.init() viewer.viewer.rediff() UIUtil.dispatchAllInvocationEvents() val builder = TestBuilder(viewer, toolbar.toolbarActions ?: emptyList()) builder.assertChangesCount(changesCount) builder.f() } finally { Disposer.dispose(viewer) } } inner class TestBuilder(val mergeViewer: TextMergeViewer, private val actions: List<AnAction>) { val viewer: MyThreesideViewer = mergeViewer.viewer val changes: List<TextMergeChange> = viewer.allChanges val editor: EditorEx = viewer.editor val document: Document = editor.document private val textEditor = TextEditorProvider.getInstance().getTextEditor(editor) private val undoManager = UndoManager.getInstance(project!!) fun change(num: Int): TextMergeChange { if (changes.size < num) throw Exception("changes: ${changes.size}, index: $num") return changes[num] } fun activeChanges(): List<TextMergeChange> = viewer.changes // // Actions // fun runApplyNonConflictsAction(side: ThreeSide) { runActionById(side.select("Left", "All", "Right")!!) } private fun runActionById(text: String): Boolean { val action = actions.filter { text == it.templatePresentation.text }.single() return runAction(action) } private fun runAction(action: AnAction): Boolean { val actionEvent = AnActionEvent.createFromAnAction(action, null, ActionPlaces.MAIN_MENU, editor.dataContext) action.update(actionEvent) val success = actionEvent.presentation.isEnabledAndVisible if (success) action.actionPerformed(actionEvent) return success } // // Modification // fun command(affected: TextMergeChange, f: () -> Unit) { command(listOf(affected), f) } fun command(affected: List<TextMergeChange>? = null, f: () -> Unit) { viewer.executeMergeCommand(null, affected, f) UIUtil.dispatchAllInvocationEvents() } fun write(f: () -> Unit) { ApplicationManager.getApplication().runWriteAction { CommandProcessor.getInstance().executeCommand(project, f, null, null) } } fun Int.ignore(side: Side, modifier: Boolean = false) { val change = change(this) command(change) { viewer.ignoreChange(change, side, modifier) } } fun Int.apply(side: Side, modifier: Boolean = false) { val change = change(this) command(change) { viewer.replaceChange(change, side, modifier) } } fun Int.resolve() { val change = change(this) command(change) { assertTrue(change.isConflict && viewer.canResolveChangeAutomatically(change, ThreeSide.BASE)) viewer.resolveChangeAutomatically(change, ThreeSide.BASE) } } fun Int.canResolveConflict(): Boolean { val change = change(this) return viewer.canResolveChangeAutomatically(change, ThreeSide.BASE) } // // Text modification // fun insertText(offset: Int, newContent: CharSequence) { replaceText(offset, offset, newContent) } fun deleteText(startOffset: Int, endOffset: Int) { replaceText(startOffset, endOffset, "") } fun replaceText(startOffset: Int, endOffset: Int, newContent: CharSequence) { write { document.replaceString(startOffset, endOffset, parseSource(newContent)) } } fun insertText(offset: LineCol, newContent: CharSequence) { replaceText(offset.toOffset(), offset.toOffset(), newContent) } fun deleteText(startOffset: LineCol, endOffset: LineCol) { replaceText(startOffset.toOffset(), endOffset.toOffset(), "") } fun replaceText(startOffset: LineCol, endOffset: LineCol, newContent: CharSequence) { write { replaceText(startOffset.toOffset(), endOffset.toOffset(), newContent) } } fun replaceText(oldContent: CharSequence, newContent: CharSequence) { write { val range = findRange(parseSource(oldContent)) replaceText(range.first, range.second, newContent) } } fun deleteText(oldContent: CharSequence) { write { val range = findRange(parseSource(oldContent)) replaceText(range.first, range.second, "") } } fun insertTextBefore(oldContent: CharSequence, newContent: CharSequence) { write { insertText(findRange(parseSource(oldContent)).first, newContent) } } fun insertTextAfter(oldContent: CharSequence, newContent: CharSequence) { write { insertText(findRange(parseSource(oldContent)).second, newContent) } } private fun findRange(oldContent: CharSequence): Couple<Int> { val text = document.charsSequence val index1 = StringUtil.indexOf(text, oldContent) assertTrue(index1 >= 0, "content - '\n$oldContent\n'\ntext - '\n$text'") val index2 = StringUtil.indexOf(text, oldContent, index1 + 1) assertTrue(index2 == -1, "content - '\n$oldContent\n'\ntext - '\n$text'") return Couple(index1, index1 + oldContent.length) } // // Undo // fun assertCantUndo() { assertFalse(undoManager.isUndoAvailable(textEditor)) } fun undo(count: Int = 1) { if (count == -1) { while (undoManager.isUndoAvailable(textEditor)) { undoManager.undo(textEditor) } } else { for (i in 1..count) { assertTrue(undoManager.isUndoAvailable(textEditor)) undoManager.undo(textEditor) } } } fun redo(count: Int = 1) { if (count == -1) { while (undoManager.isRedoAvailable(textEditor)) { undoManager.redo(textEditor) } } else { for (i in 1..count) { assertTrue(undoManager.isRedoAvailable(textEditor)) undoManager.redo(textEditor) } } } fun checkUndo(count: Int = -1, f: TestBuilder.() -> Unit) { val initialState = ViewerState.recordState(viewer) f() UIUtil.dispatchAllInvocationEvents() val afterState = ViewerState.recordState(viewer) undo(count) UIUtil.dispatchAllInvocationEvents() val undoState = ViewerState.recordState(viewer) redo(count) UIUtil.dispatchAllInvocationEvents() val redoState = ViewerState.recordState(viewer) assertEquals(initialState, undoState) assertEquals(afterState, redoState) } // // Checks // fun assertChangesCount(expected: Int) { if (expected == -1) return val actual = activeChanges().size assertEquals(expected, actual) } fun Int.assertType(type: TextDiffType, changeType: SidesState) { assertType(type) assertType(changeType) } fun Int.assertType(type: TextDiffType) { val change = change(this) assertEquals(change.diffType, type) } fun Int.assertType(changeType: SidesState) { assertTrue(changeType != NONE) val change = change(this) val actual = change.type val isLeftChange = changeType != RIGHT val isRightChange = changeType != LEFT assertEquals(Pair(isLeftChange, isRightChange), Pair(actual.isChange(Side.LEFT), actual.isChange(Side.RIGHT))) } fun Int.assertResolved(type: SidesState) { val change = change(this) val isLeftResolved = type == LEFT || type == BOTH val isRightResolved = type == RIGHT || type == BOTH assertEquals(Pair(isLeftResolved, isRightResolved), Pair(change.isResolved(Side.LEFT), change.isResolved(Side.RIGHT))) } fun Int.assertRange(start: Int, end: Int) { val change = change(this) assertEquals(Pair(start, end), Pair(change.startLine, change.endLine)) } fun Int.assertRange(start1: Int, end1: Int, start2: Int, end2: Int, start3: Int, end3: Int) { val change = change(this) assertEquals(MergeRange(start1, end1, start2, end2, start3, end3), MergeRange(change.getStartLine(ThreeSide.LEFT), change.getEndLine(ThreeSide.LEFT), change.getStartLine(ThreeSide.BASE), change.getEndLine(ThreeSide.BASE), change.getStartLine(ThreeSide.RIGHT), change.getEndLine(ThreeSide.RIGHT))) } fun Int.assertContent(expected: String, start: Int, end: Int) { assertContent(expected) assertRange(start, end) } fun Int.assertContent(expected: String) { val change = change(this) val document = editor.document val actual = DiffUtil.getLinesContent(document, change.startLine, change.endLine) assertEquals(parseSource(expected), actual) } fun assertContent(expected: String) { val actual = viewer.editor.document.charsSequence assertEquals(parseSource(expected), actual) } // // Helpers // operator fun Int.not(): LineColHelper = LineColHelper(this) operator fun LineColHelper.minus(col: Int): LineCol = LineCol(this.line, col) inner class LineColHelper(val line: Int) inner class LineCol(val line: Int, val col: Int) { fun toOffset(): Int = editor.document.getLineStartOffset(line) + col } } private class MockMergeContext(private val myProject: Project?) : MergeContext() { override fun getProject(): Project? = myProject override fun isFocusedInWindow(): Boolean = false override fun requestFocusInWindow() { } override fun finishMerge(result: MergeResult) { } } private class MockMergeRequest(val left: DocumentContent, val base: DocumentContent, val right: DocumentContent, val output: DocumentContent) : TextMergeRequest() { override fun getTitle(): String? = null override fun applyResult(result: MergeResult) { } override fun getContents(): List<DocumentContent> = listOf(left, base, right) override fun getOutputContent(): DocumentContent = output override fun getContentTitles(): List<String?> = listOf(null, null, null) } enum class SidesState { LEFT, RIGHT, BOTH, NONE } private data class ViewerState constructor(private val content: CharSequence, private val changes: List<ViewerState.ChangeState>) { companion object { fun recordState(viewer: MyThreesideViewer): ViewerState { val content = viewer.editor.document.immutableCharSequence val changes = viewer.allChanges.map { recordChangeState(viewer, it) } return ViewerState(content, changes) } private fun recordChangeState(viewer: MyThreesideViewer, change: TextMergeChange): ChangeState { val document = viewer.editor.document val content = DiffUtil.getLinesContent(document, change.startLine, change.endLine) val resolved = if (change.isResolved) BOTH else if (change.isResolved(Side.LEFT)) LEFT else if (change.isResolved(Side.RIGHT)) RIGHT else NONE val starts = Trio.from { change.getStartLine(it) } val ends = Trio.from { change.getStartLine(it) } return ChangeState(content, starts, ends, resolved) } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ViewerState) return false if (!StringUtil.equals(content, other.content)) return false if (changes != other.changes) return false return true } override fun hashCode(): Int = StringUtil.stringHashCode(content) private data class ChangeState(private val content: CharSequence, private val starts: Trio<Int>, private val ends: Trio<Int>, private val resolved: SidesState) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ChangeState) return false if (!StringUtil.equals(content, other.content)) return false if (starts != other.starts) return false if (ends != other.ends) return false if (resolved != other.resolved) return false return true } override fun hashCode(): Int = StringUtil.stringHashCode(content) } } }
apache-2.0
97e512efa804c3d57a4b2920a543bfea
33.775463
140
0.675276
4.646458
false
false
false
false
mackristof/FollowMe
common/src/main/java/org/mackristof/followme/Constants.kt
1
697
package org.mackristof.followme class Constants { companion object { val COMMAND_ACTIVATE_GPS = "/startGPS" val COMMAND_DESACTIVATE_GPS = "/stopGPS" val COMMAND_PING = "/ping" val COMMAND_START = "/start" val COMMAND_STOP = "/stop" val COMMAND_IS_GPS = "/gps" val CONNECTION_TIME_OUT_MS: Long = 100 val INTENT_LOCATION = "location" val INTENT_LOCATION_EXTRA_PUBLISH = "publish" val INTENT_LOCATION_STATUS = "status" val TAG = javaClass.`package`.name val GPS_UPDATE_INTERVAL_MS: Long = 1000 val GPS_FASTEST_INTERVAL_MS: Long = 0 val DATA_ITEM_PATH_LOCATION = "/location" } }
apache-2.0
89b386b9c314ff85a0eb9151c794cb65
30.727273
53
0.609756
3.872222
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/model/detail/CertificateData.kt
1
782
package sk.styk.martin.apkanalyzer.model.detail import android.annotation.SuppressLint import android.os.Parcelable import kotlinx.android.parcel.Parcelize import java.util.* /** * Represents data obtained from certificate file */ @SuppressLint("ParcelCreator") @Parcelize data class CertificateData( val signAlgorithm: String, val certificateHash: String, val publicKeyMd5: String, val startDate: Date, val endDate: Date, val serialNumber: Int = 0, val issuerName: String? = null, val issuerOrganization: String? = null, val issuerCountry: String? = null, val subjectName: String? = null, val subjectOrganization: String? = null, val subjectCountry: String? = null ) : Parcelable
gpl-3.0
650651900b5d32819ab4e5045c80b4e9
27.962963
49
0.68798
4.468571
false
false
false
false
hsz/idea-gitignore
src/main/kotlin/mobi/hsz/idea/gitignore/daemon/MissingGitignoreNotificationProvider.kt
1
4080
// 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.daemon import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import mobi.hsz.idea.gitignore.IgnoreBundle import mobi.hsz.idea.gitignore.command.CreateFileCommandAction import mobi.hsz.idea.gitignore.file.type.kind.GitFileType import mobi.hsz.idea.gitignore.lang.kind.GitLanguage import mobi.hsz.idea.gitignore.settings.IgnoreSettings import mobi.hsz.idea.gitignore.ui.GeneratorDialog import mobi.hsz.idea.gitignore.util.Properties import mobi.hsz.idea.gitignore.util.Utils /** * Editor notification provider that checks if there is .gitignore file in root directory and suggest to create one. */ class MissingGitignoreNotificationProvider(project: Project) : EditorNotifications.Provider<EditorNotificationPanel?>() { private val notifications = EditorNotifications.getInstance(project) private val settings = service<IgnoreSettings>() companion object { private val KEY = Key.create<EditorNotificationPanel?>("MissingGitignoreNotificationProvider") } override fun getKey() = KEY /** * Creates notification panel for given file and checks if is allowed to show the notification. * * @param file current file * @param fileEditor current file editor * @return created notification panel */ override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? = when { !settings.missingGitignore -> null Properties.isIgnoreMissingGitignore(project) -> null else -> { val vcsDirectory = GitLanguage.INSTANCE.vcsDirectory val moduleRoot = Utils.getModuleRootForFile(file, project) val gitignoreFile = moduleRoot?.findChild(GitLanguage.INSTANCE.filename) when { vcsDirectory == null -> null moduleRoot == null -> null gitignoreFile != null -> null moduleRoot.findChild(vcsDirectory)?.isDirectory ?: true -> null else -> createPanel(project, moduleRoot) } } } /** * Creates notification panel. * * @param project current project * @param moduleRoot module root * @return notification panel */ private fun createPanel(project: Project, moduleRoot: VirtualFile): EditorNotificationPanel { val fileType = GitFileType.INSTANCE return EditorNotificationPanel().apply { text = IgnoreBundle.message("daemon.missingGitignore") createActionLabel(IgnoreBundle.message("daemon.missingGitignore.create")) { val directory = PsiManager.getInstance(project).findDirectory(moduleRoot) if (directory != null) { try { val file = CreateFileCommandAction(project, directory, fileType).execute() FileEditorManager.getInstance(project).openFile(file.virtualFile, true) GeneratorDialog(project, file).show() } catch (throwable: Throwable) { throwable.printStackTrace() } } } createActionLabel(IgnoreBundle.message("daemon.cancel")) { Properties.setIgnoreMissingGitignore(project) notifications.updateAllNotifications() } try { // ignore if older SDK does not support panel icon fileType.icon?.let { icon(it) } } catch (ignored: NoSuchMethodError) { } } } }
mit
63c4a1159e877db19c242c7ab4d9ec47
42.404255
140
0.67598
5.237484
false
false
false
false
MaTriXy/gradle-play-publisher-1
play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/GenerateResources.kt
1
19226
package com.github.triplet.gradle.play.tasks import com.github.triplet.gradle.common.utils.climbUpTo import com.github.triplet.gradle.common.utils.isChildOf import com.github.triplet.gradle.common.utils.isDirectChildOf import com.github.triplet.gradle.common.utils.marked import com.github.triplet.gradle.common.utils.orNull import com.github.triplet.gradle.common.utils.readProcessed import com.github.triplet.gradle.common.utils.safeCreateNewFile import com.github.triplet.gradle.common.utils.sibling import com.github.triplet.gradle.play.internal.AppDetail import com.github.triplet.gradle.play.internal.GRAPHICS_PATH import com.github.triplet.gradle.play.internal.ImageType import com.github.triplet.gradle.play.internal.LISTINGS_PATH import com.github.triplet.gradle.play.internal.PLAY_PATH import com.github.triplet.gradle.play.internal.PRODUCTS_PATH import com.github.triplet.gradle.play.internal.RELEASE_NAMES_PATH import com.github.triplet.gradle.play.internal.RELEASE_NOTES_PATH import org.gradle.api.DefaultTask import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.Directory import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.FileSystemOperations import org.gradle.api.file.FileType import org.gradle.api.provider.ListProperty import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SkipWhenEmpty import org.gradle.api.tasks.TaskAction import org.gradle.kotlin.dsl.submit import org.gradle.kotlin.dsl.support.serviceOf import org.gradle.work.ChangeType import org.gradle.work.InputChanges import org.gradle.workers.WorkAction import org.gradle.workers.WorkParameters import org.gradle.workers.WorkerExecutor import java.io.BufferedReader import java.io.File import java.util.TreeSet import javax.inject.Inject @CacheableTask internal abstract class GenerateResources : DefaultTask() { @get:Internal abstract val resSrcDirs: ListProperty<Directory> @get:SkipWhenEmpty @get:PathSensitive(PathSensitivity.RELATIVE) @get:InputFiles abstract val resSrcTree: ConfigurableFileCollection @get:OutputDirectory abstract val resDir: DirectoryProperty @TaskAction fun generate(changes: InputChanges) { val fileChanges = changes.getFileChanges(resSrcTree) val validateChanges = fileChanges .filterNot { it.changeType == ChangeType.REMOVED } .map { it.file } val generateChanges = fileChanges .filter { it.fileType == FileType.FILE } .map { it.changeType to it.file } val work = project.serviceOf<WorkerExecutor>().noIsolation() if (validateChanges.isNotEmpty()) { work.submit(Validator::class) { files.set(validateChanges) inputDirs.set(resSrcDirs) } } if (generateChanges.isNotEmpty()) { work.submit(Generator::class) { projectDirectory.set(project.layout.projectDirectory) inputDirs.set(resSrcDirs) outputDir.set(resDir) changedFiles.set(generateChanges) } } } abstract class Validator : WorkAction<Validator.Params> { override fun execute() { for (file in parameters.files.get()) file.validate() } private fun File.validate() { val areRootsValid = name == PLAY_PATH || isDirectChildOf(PLAY_PATH) || isChildOf(LISTINGS_PATH) || isChildOf(RELEASE_NOTES_PATH) || isChildOf(RELEASE_NAMES_PATH) || isChildOf(PRODUCTS_PATH) check(areRootsValid) { "Unknown Play resource file: $this" } val isPlayKeywordReserved = name != PLAY_PATH || parameters.inputDirs.get().any { it.asFile == this } check(isPlayKeywordReserved) { "The file name 'play' is illegal: $this" } check(extension != INDEX_MARKER) { "Resources cannot use the 'index' extension: $this" } validateListings() validateReleaseNotes() validateReleaseNames() validateProducts() } private fun File.validateListings() { val listings = climbUpTo(LISTINGS_PATH) ?: return check(listings.isDirectChildOf(PLAY_PATH)) { "Listings ($listings) must be under the '$PLAY_PATH' directory" } if (isChildOf(LISTINGS_PATH)) validateLocales(listings) } private fun File.validateReleaseNotes() { val releaseNotes = climbUpTo(RELEASE_NOTES_PATH) ?: return check(releaseNotes.isDirectChildOf(PLAY_PATH)) { "Release notes ($releaseNotes) must be under the '$PLAY_PATH' directory" } if (isChildOf(RELEASE_NOTES_PATH)) validateLocales(releaseNotes) } private fun File.validateReleaseNames() { val releaseNames = climbUpTo(RELEASE_NAMES_PATH) ?: return check(releaseNames.isDirectChildOf(PLAY_PATH)) { "Release names ($releaseNames) must be under the '$PLAY_PATH' directory" } check(releaseNames.isDirectory) { "$releaseNames must be a directory" } } private fun File.validateProducts() { val products = climbUpTo(PRODUCTS_PATH) ?: return check(products.isDirectChildOf(PLAY_PATH)) { "Products ($products) must be under the '$PLAY_PATH' directory" } check(products.isDirectory) { "$products must be a directory" } } private fun File.validateLocales(category: File) { // Locales should be a child directory of the category var locale = this while (locale.parentFile != category) { locale = locale.parentFile } check(locale.isDirectory) { "Files are not allowed under the ${category.name} directory: ${locale.name}" } } interface Params : WorkParameters { val files: ListProperty<File> val inputDirs: ListProperty<Directory> } } abstract class Generator @Inject constructor( private val fileOps: FileSystemOperations ) : WorkAction<Generator.Params> { private val defaultLocale = findDefaultLocale() private val genOrder = newGenOrder() override fun execute() { // ## Definitions // // Index: Map<GeneratedFile, SortedSet<ProducerFile>> // Reverse index: Map<ProducerFile, SortedSet<GeneratedFile>> // Index on disk: combo of the two, looks something like this. // $ cat GeneratedFile.index // - // ProducerFile1 // GeneratedFile1 // GeneratedFile2 // ... // - // ProducerFile2 // GeneratedFile1 // GeneratedFile2 // ... // // The paths are in unix separators and relative to the project dir. // // ## Algorithm // // 1. Collect all locales from src/**/listings/* // 2. Collect all previous *.index files from build/**/$outputDir/** // 3. Build partial index from input changes // 4. Merge both indexes, saving which GeneratedFiles need updating // 5. Write new merged index to disk // 6. Follow the index to write the changed GeneratedFiles // // ## Merge algorithm // // Spec: keep each locale's producers ordered by the $inputDirs. The default locale is // on bottom, the actual locale on top. // // ### ADD // // 1. If for $defaultLocale: collect all locales and add to reverse index. // 2. Update index with each GeneratedFile and its producer. // // ### INSERT // // 1. If for $defaultLocale: collect all locales and add to reverse index. // 2. For each GeneratedFile: // 1. Take all $defaultLocale changes from partial index node and merge them with the // bottom of the node. All $defaultLocale producers should be at the bottom. // 2. Take all non-$defaultLocale changes from partial index node and merge them with // the top. // // ### MODIFY // // Do nothing. Keeping track of which GeneratedFiles changed is enough. // // ### DELETE // // Follow each GeneratedFile the producer produced from the reverse index and remove it // from the index. // // ## Writing the generated files // // Use the index: the first ProducerFile wins and gets written as the GeneratedFile. val (locales, prevIndex, prevReverseIndex) = parseSrcTree() val (index, reverseIndex, prunedResources) = buildIndex() insertNewLocales(index, reverseIndex, locales) mergeExistingReferences(prevIndex, index, reverseIndex) pruneOutdatedReferences(prevReverseIndex, index, reverseIndex, prunedResources) writeIndex(index, reverseIndex) pruneGeneratedResources(prevIndex, prevReverseIndex, index, prunedResources) generateResources(index) } private fun parseSrcTree(): SourceTree { val locales = mutableSetOf<String>() val index = mutableMapOf<File, MutableSet<File>>() val reverseIndex = mutableMapOf<File, MutableSet<File>>() for (dir in parameters.inputDirs.get()) { dir.asFileTree.visit { if (file.isDirectChildOf(LISTINGS_PATH) && name != defaultLocale) { locales += name } } } parameters.outputDir.get().asFileTree.visit { if (file.extension == INDEX_MARKER) { open().bufferedReader().use { reader -> reader.readIndex(index, reverseIndex) } } } return SourceTree(locales, index, reverseIndex) } private fun BufferedReader.readIndex( index: MutableMap<File, MutableSet<File>>, reverseIndex: MutableMap<File, MutableSet<File>> ) { var line: String? lateinit var producer: File while (true) { line = readLine() if (line == null) break if (line == "-") { producer = parameters.projectDirectory.get().file(readLine()).asFile continue } val generated = parameters.projectDirectory.get().file(line).asFile safeAddValue(index, reverseIndex, generated, producer) } } private fun buildIndex(): Index { val index = mutableMapOf<File, MutableSet<File>>() val reverseIndex = mutableMapOf<File, MutableSet<File>>() val prunedResources = mutableSetOf<File>() for ((type, producer) in parameters.changedFiles.get()) { if (type == ChangeType.REMOVED) prunedResources += producer safeAddValue(index, reverseIndex, producer.findDest(), producer) } return Index(index, reverseIndex, prunedResources) } private fun insertNewLocales( index: MutableMap<File, MutableSet<File>>, reverseIndex: MutableMap<File, MutableSet<File>>, locales: Set<String> ) { for (producer in reverseIndex.keys.toSet()) { if (!producer.isDefaultResource()) continue val listings = producer.climbUpTo(LISTINGS_PATH)!! val pathFromDefault = producer.toRelativeString(File(listings, defaultLocale!!)) val destListings = listings.findDest() for (locale in locales) { val genLocale = File(File(destListings, locale), pathFromDefault) safeAddValue(index, reverseIndex, genLocale, producer) } } } private fun mergeExistingReferences( prevIndex: Map<File, Set<File>>, index: MutableMap<File, MutableSet<File>>, reverseIndex: MutableMap<File, MutableSet<File>> ) { for (generated in index.keys.toSet()) { val prevProducers = prevIndex[generated].orEmpty() for (prevProducer in prevProducers) { safeAddValue(index, reverseIndex, generated, prevProducer) } } } private fun pruneOutdatedReferences( prevReverseIndex: Map<File, Set<File>>, index: MutableMap<File, MutableSet<File>>, reverseIndex: MutableMap<File, MutableSet<File>>, prunedResources: Set<File> ) { for (prevProducer in prunedResources) { val prevGens = prevReverseIndex.getValue(prevProducer) reverseIndex -= prevProducer for (prevGenerated in prevGens) { val producers = index.getValue(prevGenerated) producers -= prevProducer if (producers.isEmpty()) index -= prevGenerated } } } private fun writeIndex( index: Map<File, Set<File>>, reverseIndex: Map<File, Set<File>> ) { val projectDir = parameters.projectDirectory.get().asFile for ((generated, producers) in index) { val builder = StringBuilder() for (producer in producers) { builder.apply { append("-").append("\n") val pathFromRootToProducer = producer.relativeTo(projectDir).invariantSeparatorsPath append(pathFromRootToProducer).append("\n") } for (reverseGenerated in reverseIndex.getValue(producer)) { val pathFromRootToGenerated = reverseGenerated.relativeTo(projectDir).invariantSeparatorsPath builder.append(pathFromRootToGenerated).append("\n") } } generated.marked(INDEX_MARKER).safeCreateNewFile().writeText(builder.toString()) } } private fun pruneGeneratedResources( prevIndex: Map<File, Set<File>>, prevReverseIndex: Map<File, Set<File>>, index: Map<File, Set<File>>, prunedResources: Set<File> ) { for (producer in prunedResources) { val prevGens = prevReverseIndex.getValue(producer) for (prevGenerated in prevGens) { val prevProducers = prevIndex.getValue(prevGenerated) if (prevProducers.first() == producer && index[prevGenerated] == null) { fileOps.delete { delete(prevGenerated, prevGenerated.marked(INDEX_MARKER)) } } } } } private fun generateResources(index: Map<File, Set<File>>) { for ((generated, producers) in index) { fileOps.copy { from(producers.first()) into(generated.parentFile) } } } private fun safeAddValue( index: MutableMap<File, MutableSet<File>>, reverseIndex: MutableMap<File, MutableSet<File>>, generated: File, producer: File ) { index.safeAddValue(generated, producer) reverseIndex.safeAddValue(producer, generated) } private fun MutableMap<File, MutableSet<File>>.safeAddValue(key: File, value: File) { val store = get(key) ?: TreeSet(genOrder) store += value put(key, store) } private fun File.isDefaultResource(): Boolean { val defaultLocale = defaultLocale return defaultLocale != null && isChildOf(LISTINGS_PATH) && isDirectChildOf(defaultLocale) } private fun File.findDest(): File { val default = File(parameters.outputDir.get().asFile, toRelativeString(findOwner())) val isTopLevelGraphic = default.isDirectChildOf(GRAPHICS_PATH) && ImageType.values().any { default.nameWithoutExtension == it.dirName } return if (isTopLevelGraphic) { default.sibling(default.nameWithoutExtension + "/" + default.name) } else { default } } private fun File.findOwner() = parameters.inputDirs.get().single { startsWith(it.asFile) }.asFile private fun newGenOrder() = compareBy<File> { f -> f.isDefaultResource() }.thenByDescending { f -> val flavor = checkNotNull(f.climbUpTo(PLAY_PATH)?.parentFile?.name) { "File not a play resource: $f" } parameters.inputDirs.get().indexOfFirst { it.asFile.parentFile.name == flavor } }.thenBy { f -> f.path } private fun findDefaultLocale() = parameters.inputDirs.get().mapNotNull { it.file(AppDetail.DEFAULT_LANGUAGE.fileName).asFile.orNull()?.readProcessed() }.lastOrNull() // Pick the most specialized option available. E.g. `paidProdRelease` data class SourceTree( val locales: Set<String>, val prevIndex: Map<File, Set<File>>, val prevReverseIndex: Map<File, Set<File>> ) data class Index( val index: MutableMap<File, MutableSet<File>>, val reverseIndex: MutableMap<File, MutableSet<File>>, val prunedResources: Set<File> ) interface Params : WorkParameters { val projectDirectory: DirectoryProperty val outputDir: DirectoryProperty val inputDirs: ListProperty<Directory> val changedFiles: ListProperty<Pair<ChangeType, File>> } } private companion object { const val INDEX_MARKER = "index" } }
mit
e8e438febffbc23644031aec5e46e25e
38.72314
100
0.574691
5.254441
false
false
false
false
aspanu/KibarDataApi
src/main/kotlin/id/kibar/api/data/service/RegistrationService.kt
1
2210
package id.kibar.api.data.service import id.kibar.api.data.entity.Activity import id.kibar.api.data.entity.User import id.kibar.api.data.persistence.ActivityPersistence import id.kibar.api.data.persistence.UserActivityPersistence import id.kibar.api.data.persistence.UserPersistence import java.time.LocalDate class RegistrationService { private val userPersistence = UserPersistence() private val userActivityPersistence = UserActivityPersistence() private val activityPersistence = ActivityPersistence() fun addNewUser(name: String, email: String, sub: String = "N/A") { this.save(User(firstName = name, email = email, lastName = name, sub = sub)) } fun findByEmail(email: String): User? { return userPersistence.getUserWithEmail(email) } fun save(user: User): User { if (user.id == 0 && getUserIdForEmail(user.email) == -1) return userPersistence.addUser(user) else return userPersistence.updateUser(user) } fun checkIn(userId: Int, activityId: Int) { val user = userPersistence.getUser(userId) val activity = activityPersistence.getActivity(activityId) userActivityPersistence.checkInUser(user, activity) } fun getUserIdForEmail(email: String): Int { if (!userPersistence.checkIfUserEmailExists(email)) return -1 return userPersistence.getUserWithEmail(email).id } fun registerUserForActivity(userId: Int, activityId: Int) { val user = userPersistence.getUser(userId) val activity = activityPersistence.getActivity(activityId) userActivityPersistence.registerUser(user, activity) } fun signInUserIsNew(name: String, email: String, sub: String): Boolean { return if (!userPersistence.hasUserWithSub(sub)) { addNewUser(name = "", email = email, sub = sub) true } else { false } } fun createActivity(name: String, description: String, dateString: String): Int { return activityPersistence.createActivity( Activity(name = name, description = description, date = LocalDate.parse(dateString)) ).id } }
gpl-3.0
1e30b2829ef0f26e290acd40ed8e9513
32.484848
96
0.683258
4.547325
false
false
false
false
google/audio-to-tactile
extras/android/java/com/google/audio_to_tactile/Tuning.kt
1
3446
/* Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Algorithm tuning knob settings, corresponding to `TuningKnobs` in src/tactile/tuning.h. */ package com.google.audio_to_tactile class Tuning(initValues: IntArray = TuningNative.defaultTuningKnobs) { /** IntArray of all the tuning knob values. */ val values = initValues.copyOf() /** Number of tuning knobs. */ val size get() = values.size /** Range indices for iterating the tuning knobs. */ val indices get() = values.indices /** Interface for one tuning knob, accessed through the [Tuning.get] operator. */ class Entry(val values: IntArray, val index: Int) { /** Knob value, an integer between 0 and 255. */ var value: Int get() = values[index] set(newValue) { values[index] = newValue.coerceIn(0, 255) // Clamp value to 0-255. } /** Brief name string identifying this knob. */ val name get() = TuningNative.name(index) /** Longer description string with more details. */ val description get() = TuningNative.description(index) /** The knob's current value represented as a string, including units if applicable. */ val valueString get() = mapping(value) /** Function for how this knob maps `value` in 0-255 to a string. */ fun mapping(value: Int): String = TuningNative.mapControlValue(index, value) // When printing negative values, replace '-' with nicer-looking unicode minus symbol. .replace('-', '\u2212') /** Resets knob to its default value. */ fun reset() { value = TuningNative.default(index) } } operator fun get(index: Int) = entries[index.coerceAtMost(size - 1)] private val entries = List(size, { i -> Entry(values, i) }) /** Creates a copy of the Tuning. */ fun copyOf() = Tuning(values) /** Tests whether two Tunings are equal. */ fun contentEquals(rhs: Tuning?) = rhs?.values?.contentEquals(values) ?: false /** Resets all knobs to their default values. */ fun resetAll() { for (i in indices) { get(i).reset() } } companion object { val NUM_TUNING_KNOBS = TuningNative.numTuningKnobs() val DEFAULT_TUNING_KNOBS = TuningNative.defaultTuningKnobs } } /** Tuning JNI bindings. */ private object TuningNative { init { System.loadLibrary("tuning_jni") } val defaultTuningKnobs = IntArray(numTuningKnobs()) { i -> default(i) } /** Gets the name string for `knob`. */ external fun name(knob: Int): String /** Gets the description string for `knob`. */ external fun description(knob: Int): String /** Gets the default value for `knob`. */ external fun default(knob: Int): Int /** Gets the number of tuning knobs. */ external fun numTuningKnobs(): Int /** Maps a knob control value and formats it as a string, including units if applicable. */ external fun mapControlValue(knob: Int, value: Int): String }
apache-2.0
f0e19a6107daf83c242877c109013475
34.525773
94
0.675566
4.107271
false
false
false
false
oversecio/oversec_crypto
crypto/src/main/java/io/oversec/one/crypto/gpg/GpgEncryptionParams.kt
1
3110
package io.oversec.one.crypto.gpg import android.content.Context import io.oversec.one.crypto.AbstractEncryptionParams import io.oversec.one.crypto.EncryptionMethod import java.util.* class GpgEncryptionParams : AbstractEncryptionParams { private var mOwnPublicKey: Long = 0 var isSign = true private var mPublicKeys: MutableSet<Long> = HashSet() val publicKeyIds: Set<Long> get() = mPublicKeys val ownPublicKey: Long? get() = mOwnPublicKey val allPublicKeyIds: LongArray get() { val allKeys = ArrayList(mPublicKeys) if (mOwnPublicKey != 0L) { allKeys.add(mOwnPublicKey) } return allKeys.toLongArray() } constructor(pkids: List<Long>?, coderId: String, padderId: String?) : super( EncryptionMethod.GPG, coderId, padderId ) { pkids?.run { mPublicKeys.addAll(this) } } constructor(keyIds: LongArray?, coderId: String, padderId: String?) : super( EncryptionMethod.GPG, coderId, padderId ) { keyIds?.run { mPublicKeys.addAll(this.asList()) } } fun removePublicKey(keyId: Long?) { mPublicKeys.remove(keyId) } fun addPublicKeyIds(keyIds: Array<Long>, omitThisKey: Long) { keyIds.forEach { if (it != omitThisKey) { mPublicKeys.add(it) } } } fun setOwnPublicKey(k: Long) { mOwnPublicKey = k mPublicKeys.remove(k) } fun addPublicKey(id: Long) { mPublicKeys.add(id) } override fun isStillValid(ctx: Context): Boolean { //TODO: check that OpenKEychain service is still up and running, //TODO: check that we do still have the keys return true } fun setPublicKeyIds(ids: LongArray) { mPublicKeys.clear() mPublicKeys.addAll(ids.asList()) } override fun toString(): String { return "GpgEncryptionParams{" + "mOwnPublicKey=" + mOwnPublicKey + ", mSign=" + isSign + ", mPublicKeys=" + Arrays.toString(mPublicKeys.toTypedArray()) + '}'.toString() } companion object { fun LongListToLongArray(a: List<Long>?): LongArray? { return a?.toLongArray() } fun LongArrayToLongList(a: LongArray?): List<Long>? { return a?.toList() } // fun longArrayToLongArray(a: LongArray?): Array<Long>? { // if (a == null) { // return null // } // val res = arrayOfNulls<Long>(a.size) // for (i in res.indices) { // res[i] = a[i] // } // return res // } // // fun LongArrayTolongArray(a: Array<Long>?): LongArray? { // if (a == null) { // return null // } // val res = LongArray(a.size) // for (i in res.indices) { // res[i] = a[i] // } // return res // } } }
gpl-3.0
d75c1b7eca68fbe9fe8ffb759971485b
24.284553
80
0.53537
4.248634
false
false
false
false
cloudbearings/contentful-management.java
src/test/kotlin/com/contentful/java/cma/EntryTests.kt
1
12079
/* * Copyright (C) 2014 Contentful GmbH * * 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.contentful.java.cma import com.contentful.java.cma.lib.ModuleTestUtils import com.contentful.java.cma.lib.TestCallback import com.contentful.java.cma.lib.TestUtils import com.contentful.java.cma.model.CMAEntry import com.squareup.okhttp.HttpUrl import com.squareup.okhttp.mockwebserver.MockResponse import retrofit.RetrofitError import java.io.IOException import kotlin.test.* import org.junit.Test as test class EntryTests : BaseTest() { test fun testArchive() { val responseBody = TestUtils.fileToString("entry_archive_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val entry = CMAEntry().setId("entryid").setSpaceId("spaceid") assertFalse(entry.isArchived()) val result = assertTestCallback( client!!.entries().async().archive(entry, TestCallback()) as TestCallback) assertTrue(result.isArchived()) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/entries/entryid/archived", recordedRequest.getPath()) } test fun testCreate() { val requestBody = TestUtils.fileToString("entry_create_request.json") val responseBody = TestUtils.fileToString("entry_create_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val entry = CMAEntry() .setField("fid1", "value1", "en-US") .setField("fid2", "value2", "en-US") val result = assertTestCallback(client!!.entries() .async() .create("spaceid", "ctid", entry, TestCallback()) as TestCallback) assertEquals(2, result.getFields().size()) val entries = result.getFields().entrySet().toList() assertEquals("id1", entries[0].key) assertEquals("id2", entries[1].key) assertEquals("value1", entries[0].value["en-US"]) assertEquals("value2", entries[1].value["en-US"]) // Request val recordedRequest = server!!.takeRequest() assertEquals("POST", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/entries", recordedRequest.getPath()) assertEquals(requestBody, recordedRequest.getUtf8Body()) assertEquals("ctid", recordedRequest.getHeader("X-Contentful-Content-Type")) } test fun testCreateWithId() { val requestBody = TestUtils.fileToString("entry_create_request.json") val responseBody = TestUtils.fileToString("entry_create_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val entry = CMAEntry() .setId("entryid") .setField("fid1", "value1", "en-US") .setField("fid2", "value2", "en-US") assertTestCallback(client!!.entries().async().create( "spaceid", "ctid", entry, TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/entries/entryid", recordedRequest.getPath()) assertEquals(requestBody, recordedRequest.getUtf8Body()) assertEquals("ctid", recordedRequest.getHeader("X-Contentful-Content-Type")) } test fun testCreateWithLinks() { val requestBody = TestUtils.fileToString("entry_create_links_request.json") server!!.enqueue(MockResponse().setResponseCode(200)) val LOCALE = "en-US" val foo = CMAEntry().setId("foo").setField("name", "foo", LOCALE) val bar = CMAEntry().setId("bar").setField("name", "bar", LOCALE) foo.setField("link", bar, LOCALE) foo.setField("link", bar, "he-IL") foo.setField("array", listOf(bar), LOCALE) bar.setField("link", foo, LOCALE) client!!.entries().create("space", "type", foo) val request = server!!.takeRequest() assertEquals(requestBody, request.getUtf8Body()) } test(expected = RetrofitError::class) fun testCreateWithBadLinksThrows() { val foo = CMAEntry().setId("bar").setField("link", CMAEntry(), "en-US") server!!.enqueue(MockResponse().setResponseCode(200)) try { client!!.entries().create("space", "type", foo) } catch(e: RetrofitError) { assertEquals("Entry contains link to draft resource (has no ID).", e.getMessage()) throw e } } test fun testDelete() { server!!.enqueue(MockResponse().setResponseCode(200)) assertTestCallback(client!!.entries().async().delete( "spaceid", "entryid", TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("DELETE", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/entries/entryid", recordedRequest.getPath()) } test fun testFetchAll() { val responseBody = TestUtils.fileToString("entry_fetch_all_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.entries().async().fetchAll( "spaceid", TestCallback()) as TestCallback) assertEquals("Array", result.getSys()["type"]) assertEquals(1, result.getTotal()) assertEquals(1, result.getItems().size()) val item = result.getItems()[0] assertEquals(2, item.getFields().size()) assertNotNull(item.getFields()["name"]) assertNotNull(item.getFields()["type"]) assertNull(result.getIncludes()) // Request val request = server!!.takeRequest() assertEquals("GET", request.getMethod()) assertEquals("/spaces/spaceid/entries", request.getPath()) } test fun testFetchAllWithQuery() { server!!.enqueue(MockResponse().setResponseCode(200).setBody( TestUtils.fileToString("entry_fetch_all_response.json"))) val query = hashMapOf(Pair("skip", "1"), Pair("limit", "2"), Pair("content_type", "foo")) assertTestCallback(client!!.entries().async().fetchAll( "spaceid", query, TestCallback()) as TestCallback) // Request val request = server!!.takeRequest() val url = HttpUrl.parse(server!!.getUrl(request.getPath()).toString()) assertEquals("1", url.queryParameter("skip")) assertEquals("2", url.queryParameter("limit")) assertEquals("foo", url.queryParameter("content_type")) } test fun testFetchWithId() { val responseBody = TestUtils.fileToString("entry_fetch_one_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.entries().async().fetchOne( "space", "entry", TestCallback()) as TestCallback) val sys = result.getSys() val fields = result.getFields() assertEquals("Entry", sys["type"]) assertEquals("entryid", sys["id"]) assertEquals(2, fields.size()) assertEquals("http://www.url.com", fields["url"]["en-US"]) assertEquals("value", fields["key"]["en-US"]) // Request val request = server!!.takeRequest() assertEquals("GET", request.getMethod()) assertEquals("/spaces/space/entries/entry", request.getPath()) } test fun testParseEntryWithList() { gson!!.fromJson( TestUtils.fileToString("entry_with_list_object.json"), javaClass<CMAEntry>()) } test fun testUpdate() { val requestBody = TestUtils.fileToString("entry_update_request.json") val responseBody = TestUtils.fileToString("entry_update_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.entries().async().update(CMAEntry() .setId("entryid") .setSpaceId("spaceid") .setVersion(1.0) .setField("fid1", "newvalue1", "en-US") .setField("fid2", "newvalue2", "en-US"), TestCallback()) as TestCallback) val fields = result.getFields().entrySet().toList() assertEquals("entryid", result.getSys()["id"]) assertEquals("Entry", result.getSys()["type"]) assertEquals(2, fields.size()) assertEquals("fid1", fields[0].key) assertEquals("newvalue1", fields[0].value["en-US"]) assertEquals("fid2", fields[1].key) assertEquals("newvalue2", fields[1].value["en-US"]) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/entries/entryid", recordedRequest.getPath()) assertNotNull(recordedRequest.getHeader("X-Contentful-Version")) assertEquals(requestBody, recordedRequest.getUtf8Body()) } test fun testPublish() { server!!.enqueue(MockResponse().setResponseCode(200)) assertTestCallback(client!!.entries().async().publish(CMAEntry() .setId("entryid") .setSpaceId("spaceid") .setVersion(1.0), TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/entries/entryid/published", recordedRequest.getPath()) assertNotNull(recordedRequest.getHeader("X-Contentful-Version")) } test fun testUnArchive() { server!!.enqueue(MockResponse().setResponseCode(200)) assertTestCallback(client!!.entries().async().unArchive( CMAEntry().setId("entryid").setSpaceId("spaceid"), TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("DELETE", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/entries/entryid/archived", recordedRequest.getPath()) } test fun testUnPublish() { server!!.enqueue(MockResponse().setResponseCode(200)) assertTestCallback(client!!.entries().async().unPublish( CMAEntry().setId("entryid").setSpaceId("spaceid"), TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("DELETE", recordedRequest.getMethod()) assertEquals("/spaces/spaceid/entries/entryid/published", recordedRequest.getPath()) } test(expected = RetrofitError::class) fun testRetainsSysOnNetworkError() { val badClient = CMAClient.Builder() .setAccessToken("accesstoken") .setClient { throw RetrofitError.unexpectedError(it.getUrl(), IOException()) } .build() val entry = CMAEntry().setVersion(31337.0) try { badClient.entries().create("spaceid", "ctid", entry) } catch (e: RetrofitError) { assertEquals(31337, entry.getVersion()) throw e } } test(expected = Exception::class) fun testUpdateFailsWithoutVersion() { ModuleTestUtils.assertUpdateWithoutVersion { client!!.entries().update(CMAEntry().setId("eid").setSpaceId("spaceid")) } } }
apache-2.0
f59438829d2cb51a0b2eab37d1cba3c6
38.996689
97
0.638712
4.894246
false
true
false
false
dsvoronin/RxKotlin
src/main/kotlin/rx/lang/kotlin/subscribers.kt
1
2751
package rx.lang.kotlin import rx.Subscriber import rx.exceptions.OnErrorNotImplementedException import rx.observers.SerializedSubscriber import java.util.* public class FunctionSubscriber<T>() : Subscriber<T>() { private val onCompletedFunctions = ArrayList<() -> Unit>() private val onErrorFunctions = ArrayList<(e: Throwable) -> Unit>() private val onNextFunctions = ArrayList<(value: T) -> Unit>() private val onStartFunctions = ArrayList<() -> Unit>() override fun onCompleted() = onCompletedFunctions.forEach { it() } override fun onError(e: Throwable?) = (e ?: RuntimeException("exception is unknown")).let { ex -> if (onErrorFunctions.isEmpty()) { throw OnErrorNotImplementedException(ex) } else { onErrorFunctions.forEach { it(ex) } } } override fun onNext(t: T) = onNextFunctions.forEach { it(t) } override fun onStart() = onStartFunctions.forEach { it() } fun onCompleted(onCompletedFunction: () -> Unit): FunctionSubscriber<T> = copy { onCompletedFunctions.add(onCompletedFunction) } fun onError(onErrorFunction: (t: Throwable) -> Unit): FunctionSubscriber<T> = copy { onErrorFunctions.add(onErrorFunction) } fun onNext(onNextFunction: (t: T) -> Unit): FunctionSubscriber<T> = copy { onNextFunctions.add(onNextFunction) } fun onStart(onStartFunction: () -> Unit): FunctionSubscriber<T> = copy { onStartFunctions.add(onStartFunction) } private fun copy(block: FunctionSubscriber<T>.() -> Unit): FunctionSubscriber<T> { val newSubscriber = FunctionSubscriber<T>() newSubscriber.onCompletedFunctions.addAll(onCompletedFunctions) newSubscriber.onErrorFunctions.addAll(onErrorFunctions) newSubscriber.onNextFunctions.addAll(onNextFunctions) newSubscriber.onStartFunctions.addAll(onStartFunctions) newSubscriber.block() return newSubscriber } } public class FunctionSubscriberModifier<T>(init: FunctionSubscriber<T> = subscriber()) { public var subscriber: FunctionSubscriber<T> = init private set fun onCompleted(onCompletedFunction: () -> Unit): Unit { subscriber = subscriber.onCompleted(onCompletedFunction) } fun onError(onErrorFunction: (t: Throwable) -> Unit): Unit { subscriber = subscriber.onError(onErrorFunction) } fun onNext(onNextFunction: (t: T) -> Unit): Unit { subscriber = subscriber.onNext(onNextFunction) } fun onStart(onStartFunction: () -> Unit): Unit { subscriber = subscriber.onStart(onStartFunction) } } public fun <T> subscriber(): FunctionSubscriber<T> = FunctionSubscriber() public fun <T> Subscriber<T>.synchronized(): Subscriber<T> = SerializedSubscriber(this)
apache-2.0
e3c288a55a8ba45e5b55fd37642bc1b0
39.455882
132
0.703017
4.826316
false
false
false
false
jansorg/BashSupport
src/com/ansorgit/plugins/bash/editor/codecompletion/BashPathCompletionService.kt
1
5949
/* * Copyright (c) Joachim Ansorg, [email protected] * * 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.ansorgit.plugins.bash.editor.codecompletion import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfoRt import org.apache.commons.lang.StringUtils import java.io.File import java.io.IOException import java.io.UncheckedIOException import java.nio.file.FileSystemException import java.nio.file.Files import java.nio.file.InvalidPathException import java.nio.file.Paths import java.util.* /** * Service which exposes the commands used for Bash code completion. * * @author jansorg */ class BashPathCompletionService() { companion object { private val LOG = Logger.getInstance("#bash.completion") @JvmStatic fun getInstance() = ServiceManager.getService(BashPathCompletionService::class.java)!! } data class CompletionItem(val filename: String, val path: String) private val commands: NavigableMap<String, CompletionItem> by lazy { val start = System.currentTimeMillis() val result = TreeMap<String, CompletionItem>() try { val paths = System.getenv("PATH") if (paths != null) { for (e in StringUtils.split(paths, File.pathSeparatorChar)) { val trimmed = e.trim('"', File.pathSeparatorChar) if (trimmed.isEmpty()) { continue } try { val path = Paths.get(trimmed) if (Files.isDirectory(path)) { val files = Files.find(path, 1, { f, attr -> attr.isRegularFile && Files.isExecutable(f) }, emptyArray()) try { files.forEach { try { val fileName = it.fileName.toString() val isExecutable = when { SystemInfoRt.isWindows -> fileName.endsWith(".exe") || fileName.endsWith(".bat") else -> true } if (isExecutable) { result.put(fileName, CompletionItem(fileName, it.toString())) } } catch (e: FileSystemException) { if (LOG.isDebugEnabled) { LOG.debug("error accessing file $it") } } catch (e: UncheckedIOException) { if (LOG.isDebugEnabled) { LOG.debug("error accessing file $it") } } } } finally { files.close() } } } catch (ex: Exception) { when (ex) { is InvalidPathException, is IOException, is UncheckedIOException, is SecurityException -> LOG.debug("Invalid path detected in \$PATH element $e", ex) is FileSystemException -> LOG.debug("Ignoring filesystem exception in \$PATH element $e", ex) else -> LOG.error("Exception while scanning \$PATH for command names", ex) } } } } result } finally { val duration = System.currentTimeMillis() - start val size = result.size LOG.debug("bash commands loaded $size commands in $duration ms") } } fun findCommands(commandPrefix: String): Collection<CompletionItem> { val subMap = commands.subMap(commandPrefix, true, findUpperLimit(commandPrefix), true) return subMap.values } fun allCommands(): Collection<CompletionItem> { return commands.values } /** * Find the upper limit of the TreeSet map lookup. E.g. "git" has a upper lookup limit of "giu" (exclusive). * * @param prefix The prefix which should be used to retrieve all keys which start with this value * @return The key to use for the upper limit l */ protected fun findUpperLimit(prefix: String): String { return when { prefix.isEmpty() -> "z" prefix.length == 1 -> { val c = prefix[0] if (c < 'z') Character.toString((c.toInt() + 1).toChar()) else "z" } else -> { //change the last character to 'z' to create the lookup range //if it already is 'z' then cut it off and call again with the substring val lastChar = prefix[prefix.length - 1] if (lastChar < 'z') { prefix.substring(0, prefix.length - 1) + Character.toString((lastChar.toInt() + 1).toChar()) } else { findUpperLimit(prefix.substring(0, prefix.length - 1)) } } } } }
apache-2.0
4ae8767d6be020ebcb73d74fb106ed46
41.198582
177
0.51723
5.292705
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/accessors/PluginTree.kt
4
2268
/* * Copyright 2018 the original author or 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.gradle.kotlin.dsl.accessors internal sealed class PluginTree { data class PluginGroup(val path: List<String>, val plugins: Map<String, PluginTree>) : PluginTree() data class PluginSpec(val id: String, val implementationClass: String) : PluginTree() companion object { fun of(plugins: Sequence<PluginSpec>): Map<String, PluginTree> { val root = linkedMapOf<String, PluginTree>() plugins.sortedBy { it.id }.forEach { plugin -> val path = plugin.id.split('.') val pluginGroupPath = path.dropLast(1) pluginTreeForGroup(pluginGroupPath, root) ?.put(path.last(), plugin) } return root } private fun pluginTreeForGroup(groupPath: List<String>, root: MutableMap<String, PluginTree>): MutableMap<String, PluginTree>? { var branch = root groupPath.forEachIndexed { index, segment -> when (val group = branch[segment]) { null -> { val newGroupMap = linkedMapOf<String, PluginTree>() val newGroup = PluginGroup(groupPath.take(index + 1), newGroupMap) branch[segment] = newGroup branch = newGroupMap } is PluginGroup -> { branch = group.plugins as MutableMap<String, PluginTree> } else -> { return null } } } return branch } } }
apache-2.0
68fcabb7b9fe2a369bc90fff650c0e4d
35.580645
128
0.574515
5.085202
false
false
false
false
neoranga55/kontacts-android-kotlin
app/src/main/java/com/neoranga55/kontacts/DetailActivity.kt
1
661
package com.neoranga55.kontacts import android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_detail.* class DetailActivity : AppCompatActivity() { companion object { val EXTRA_NAME = "extraName" val EXTRA_IMAGE = "extraImage" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) val name = intent.getStringExtra(EXTRA_NAME) supportActionBar?.title = name contactText.text = name contactImage.loadUrl(intent.getStringExtra(EXTRA_IMAGE)) } }
apache-2.0
0be8d6b568a80110b6cdd6aa5cb008e8
27.782609
64
0.712557
4.436242
false
false
false
false
Takhion/android-extras-delegates
library/src/main/java/me/eugeniomarletti/extras/Utils.kt
1
3137
@file:Suppress("NOTHING_TO_INLINE") package me.eugeniomarletti.extras import kotlin.jvm.internal.CallableReference import kotlin.reflect.KClass import kotlin.reflect.KDeclarationContainer import kotlin.reflect.KProperty inline fun KProperty<*>.defaultDelegateName(customPrefix: String?, separator: String = "::") = (customPrefix ?: ownerCanonicalName)?.let { it + separator + name } ?: name inline val KProperty<*>.ownerCanonicalName: String? get() = owner?.canonicalName inline val KProperty<*>.owner: KDeclarationContainer? get() = if (this is CallableReference) owner else null inline val KDeclarationContainer.canonicalName: String? get() = if (this is KClass<*>) this.java.canonicalName else null internal typealias RemoveExtra<This> = This.(name: String) -> Any? internal typealias HasExtra<This> = This.(name: String) -> Boolean internal typealias ExtraReaderDefault<This, R> = This.(name: String, defaultValue: R) -> R @PublishedApi internal inline fun <T, R : Any> T.putExtra( crossinline removeExtra: RemoveExtra<T>, crossinline writer: ExtraWriter<T, R>, name: String, value: R? ) = if (value != null) writer(name, value) else removeExtra(name) @PublishedApi internal inline fun <T, R : Any> T.readPrimitive( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, R>, defaultValue: R, name: String ) = if (hasExtra(name)) reader(name, defaultValue) else null @PublishedApi internal inline fun <T> T.readBoolean( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, Boolean>, name: String ) = readPrimitive(hasExtra, reader, false, name) @PublishedApi internal inline fun <T> T.readByte( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, Byte>, name: String ) = readPrimitive(hasExtra, reader, 0, name) @PublishedApi internal inline fun <T> T.readChar( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, Char>, name: String ) = readPrimitive(hasExtra, reader, '0', name) @PublishedApi internal inline fun <T> T.readInt( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, Int>, name: String ) = readPrimitive(hasExtra, reader, 0, name) @PublishedApi internal inline fun <T> T.readDouble( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, Double>, name: String ) = readPrimitive(hasExtra, reader, 0.0, name) @PublishedApi internal inline fun <T> T.readFloat( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, Float>, name: String ) = readPrimitive(hasExtra, reader, 0f, name) @PublishedApi internal inline fun <T> T.readShort( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, Short>, name: String ) = readPrimitive(hasExtra, reader, 0, name) @PublishedApi internal inline fun <T> T.readLong( crossinline hasExtra: HasExtra<T>, crossinline reader: ExtraReaderDefault<T, Long>, name: String ) = readPrimitive(hasExtra, reader, 0L, name)
mit
52d5be3b2ec73348177f09c3a2a0b020
33.472527
120
0.727128
4.13307
false
false
false
false
Catherine22/WebServices
WebServices/app/src/main/java/com/catherine/webservices/kotlin_sample/player/Player.kt
1
2139
package com.catherine.webservices.kotlin_sample.player import com.catherine.webservices.toolkits.CLog import kotlin.properties.Delegates /** * Created by Catherine on 2017/7/28. */ class Player { companion object { val TAG = "Player" } interface OnPlayStateChangedListener { fun OnPlayStateChanged(prevState: State, newState: State) } //nullable var onPlayStateChangedListener: OnPlayStateChangedListener? = null /** * 通过Delegates.observable可以捕捉状态的变化,并会叫回调接口 */ private var state: State by Delegates.observable(State.IDLE, { prop, old, new -> CLog.w(TAG, "$old -> $new") //?.表示只有在onPlayStateChangedListener不为空时才调用方法,Java中就是if(onPlayStateChangedListener!=null)... onPlayStateChangedListener?.OnPlayStateChanged(old, new) }) private fun executeCmd(cmd: PlayerCmd) { when (cmd) { is PlayerCmd.Play -> { CLog.v(TAG, "Play ${cmd.url} from ${cmd.position}ms") state = State.PLAYING } is PlayerCmd.Pause -> { CLog.v(TAG, "Pause") state = State.PAUSED } is PlayerCmd.Resume -> { CLog.v(TAG, "Resume") state = State.PLAYING } is PlayerCmd.Stop -> { CLog.v(TAG, "Stop") state = State.IDLE } is PlayerCmd.Seek -> { CLog.v(TAG, "Seek to ${cmd.position}ms, state: $state") } } } /** * 给position一个默认值0,呼叫方法时就可以只带url一个参数 */ fun play(url: String, position: Long = 0) { val cmd = PlayerCmd.Play(url, position) executeCmd(cmd) } fun seekTo(position: Long) { val cmd = PlayerCmd.Seek(position) executeCmd(cmd) } fun pause() { executeCmd(PlayerCmd.Pause) } fun resume() { executeCmd(PlayerCmd.Resume) } fun stop() { executeCmd(PlayerCmd.Stop) } }
apache-2.0
59b0533dd465907a572b7cdbe421ea36
24.948718
99
0.557588
4.013889
false
false
false
false
Drakojin/livingdoc2
livingdoc-engine/src/test/kotlin/org/livingdoc/engine/execution/examples/scenarios/ScenarioExecutorTest.kt
1
9475
package org.livingdoc.engine.execution.examples.scenarios import io.mockk.every import io.mockk.verify import io.mockk.verifySequence import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.livingdoc.engine.execution.Result.* import org.livingdoc.engine.execution.examples.scenarios.model.ScenarioResult import org.livingdoc.repositories.model.scenario.Scenario import org.livingdoc.repositories.model.scenario.Step import strikt.api.expect import strikt.api.expectThat import strikt.assertions.containsExactlyInAnyOrder import strikt.assertions.hasSize import strikt.assertions.isA import strikt.assertions.isEqualTo import strikt.assertions.toList internal class ScenarioExecutorTest { val cut = ScenarioExecutor() @Test fun `executes a complete scenario`() { val step1 = Step("when the customer scans a banana for 49 cents") val step2 = Step("and an apple for 39 cents") val step3 = Step("when the customer checks out, the total sum is 88") val steps = listOf(step1, step2, step3) val scenarioResult = cut.execute(Scenario(steps), SelfCheckoutScenarioFixture::class.java, null) expect { that(scenarioResult.result).isEqualTo(Executed) that(scenarioResult.steps).hasSize(3) } scenarioResult.steps.forEach { step -> expectThat(step.result).isEqualTo(Executed) } } @Test fun `executes scenarios following the expected lifecycle`() { val steps = listOf(Step("step1"), Step("step2")) val resultScenario = cut.execute(Scenario(steps), LifeCycleFixture::class.java, null) expectThat(resultScenario.result).isEqualTo(Executed) val fixture = LifeCycleFixture.callback verifySequence { fixture.before() fixture.step1() fixture.step2() fixture.after() } } @Test fun `multiple steps matching different templates can be mapped to the same method`() { val steps = listOf( Step("step2"), Step("Alternate template for step2") ) cut.execute(Scenario(steps), LifeCycleFixture::class.java, null) val fixture = LifeCycleFixture.callback verify(exactly = 2) { fixture.step2() } } @Nested inner class `when executing steps with parameters` { val fixture = ExtendedLifeCycleFixture.callback!! @Test fun `parameter values are passed as method parameters with the same name`() { // requires compilation with "-parameters" (Java8) // Reminder: To configure this in Intellij IDEA, go to "Settings" > "Build, Execution, Deployment" > // "Compiler" > "Java Compiler" and add "-parameters" to "Additional command line parameters", // then clean and rebuild the project. execute(Step("Step with parameter: wonderful")) verify { fixture.parameterizedStep("wonderful") } } @Test fun `parameter values are passed to methods based on explicit name bindings`() { execute(Step("Step with parameter passed by explicit name bindings: explicit")) verify { fixture.parameterizedStepWithBinding("explicit") } } @Test fun `a mismatching parameter results in "Exception"`() { val result = execute(Step("Step with mismatching parameter: Oh noes!")).result expectThat(result).isA<Exception>() } } @Nested inner class `when an assertion fails during execution of a scenario step` { val fixture = ExtendedLifeCycleFixture.callback!! @Test fun `the result of the scenario is Executed`() { every { fixture.step1() } throws AssertionError() val result = execute(Step("step1"), Step("step2")).result expectThat(result).isA<Executed>() } @Test fun `the result of the step is Failed`() { every { fixture.step1() } throws AssertionError() val stepResult = execute(Step("step1"), Step("step2")).steps[0].result expectThat(stepResult).isA<Failed>() } @Test fun `the following steps are Skipped`() { every { fixture.step1() } throws AssertionError() val stepResult = execute(Step("step1"), Step("step2")).steps[1].result expectThat(stepResult).isA<Skipped>() } @Test fun `the teardown commands are executed`() { every { fixture.step1() } throws AssertionError() execute() verify { fixture.after1() fixture.after2() } } } @Nested inner class `when an exception is thrown` { val fixture = ExtendedLifeCycleFixture.callback!! @Nested inner class duringasetupcommandBefore { @Test fun `the result is Exception`() { every { fixture.before1() } throws IllegalStateException() val result = execute(Step("step1"), Step("step2")).result expectThat(result).isA<Exception>() } @Test fun `the following setup commands are not invoked`() { every { fixture.before1() } throws IllegalStateException() execute(Step("step1"), Step("step2")) verify(exactly = 0) { fixture.before2() } } @Test fun `no scenario steps are executed`() { every { fixture.before1() } throws IllegalStateException() execute(Step("step1"), Step("step2")) verify(exactly = 0) { fixture.step1() fixture.step2() } } @Test fun `the results of all steps are Skipped`() { every { fixture.before1() } throws IllegalStateException() val result = execute(Step("step1"), Step("step2")) expectThat(result.steps[0].result).isEqualTo(Skipped) expectThat(result.steps[1].result).isEqualTo(Skipped) } @Test fun `teardown commands, however, are invoked`() { every { fixture.before1() } throws IllegalStateException() execute(Step("step1"), Step("step2")) verify { fixture.after1() fixture.after2() } } } @Nested inner class `during execution of a step` { @Test fun `the result of the scenario is Executed`() { every { fixture.step1() } throws IllegalStateException() val result = execute(Step("step1"), Step("step2")).result expectThat(result).isA<Executed>() } @Test fun `the result of the step is Exception`() { every { fixture.step1() } throws IllegalStateException() val stepResult = execute(Step("step1"), Step("step2")).steps[0].result expectThat(stepResult).isA<Exception>() } @Test fun `the following steps are Skipped`() { every { fixture.step1() } throws IllegalStateException() val stepResult = execute(Step("step1"), Step("step2")).steps[1].result expectThat(stepResult).isA<Skipped>() } @Test fun `the teardown commands are executed`() { every { fixture.step1() } throws IllegalStateException() execute() verify { fixture.after1() fixture.after2() } } } @Nested inner class duringateardowncommandAfter { @Test fun `the result of the scenario is Exception`() { every { fixture.after1() } throws IllegalStateException() val result = execute().result expectThat(result).isA<Exception>() } @Test fun `all exceptions are collected and attached to the Exception result`() { val exception1 = IllegalStateException() val exception2 = IllegalStateException() every { fixture.after1() } throws exception1 every { fixture.after2() } throws exception2 val result = execute().result as Exception expectThat(result.exception).isA<ScenarioExecution.AfterMethodExecutionException>() expectThat(result.exception.suppressed).toList().containsExactlyInAnyOrder(exception1, exception2) } @Test fun `subsequent teardown commands are executed`() { every { fixture.after1() } throws IllegalStateException() execute() verify { fixture.after2() } } } } @BeforeEach fun reset() { LifeCycleFixture.reset() ExtendedLifeCycleFixture.reset() } private fun execute(vararg steps: Step): ScenarioResult { val scenario = Scenario(steps.asList()) return cut.execute(scenario, ExtendedLifeCycleFixture::class.java, null) } }
apache-2.0
cb2a57f4013ddbb63d973c6d87c92f9c
30.688963
116
0.576042
5.088614
false
true
false
false
intellij-rust/intellij-rust
src/main/kotlin/org/rust/ide/console/RsConsoleVariablesView.kt
3
2425
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.console import com.intellij.ide.util.treeView.smartTree.SmartTreeStructure import com.intellij.openapi.Disposable import com.intellij.openapi.application.runInEdt import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.psi.PsiFileFactory import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.tree.AsyncTreeModel import com.intellij.ui.tree.StructureTreeModel import com.intellij.ui.treeStructure.Tree import org.rust.ide.structure.RsStructureViewModel import org.rust.lang.RsLanguage import org.rust.lang.core.psi.RsReplCodeFragment import org.rust.openapiext.document class RsConsoleVariablesView(project: Project, private val codeFragmentContext: RsConsoleCodeFragmentContext) : SimpleToolWindowPanel(true, true), Disposable { private val variablesFile: RsReplCodeFragment private val treeStructure: SmartTreeStructure private val structureTreeModel: StructureTreeModel<SmartTreeStructure> init { val allCommands = codeFragmentContext.getAllCommandsText() variablesFile = PsiFileFactory.getInstance(project) .createFileFromText(RsConsoleView.VIRTUAL_FILE_NAME, RsLanguage, allCommands) as RsReplCodeFragment val structureViewModel = RsStructureViewModel(null, variablesFile) treeStructure = SmartTreeStructure(project, structureViewModel) structureTreeModel = StructureTreeModel(treeStructure, this) val asyncTreeModel = AsyncTreeModel(structureTreeModel, this) val tree = Tree(asyncTreeModel) tree.isRootVisible = false tree.emptyText.text = EMPTY_TEXT setContent(ScrollPaneFactory.createScrollPane(tree)) } fun rebuild() { runInEdt { runWriteAction { val allCommands = codeFragmentContext.getAllCommandsText() variablesFile.virtualFile.document?.setText(allCommands) } structureTreeModel.invoker.invokeLater { treeStructure.rebuildTree() structureTreeModel.invalidate() } } } override fun dispose() {} companion object { private const val EMPTY_TEXT: String = "No variables yet" } }
mit
fc7bc9aee42afe32d2470605b88a41c9
35.19403
111
0.74433
5.020704
false
false
false
false
ansman/kotshi
tests/src/test/kotlin/se/ansman/kotshi/TestPrimitiveAdapters.kt
1
7858
package se.ansman.kotshi import com.squareup.moshi.JsonAdapter import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import com.squareup.moshi.Moshi import okio.Buffer import org.junit.Before import org.junit.Test import kotlin.test.assertEquals class TestPrimitiveAdapters { private lateinit var moshi: Moshi private lateinit var stringAdapter: DelegateAdapter<String> private lateinit var booleanAdapter: DelegateAdapter<Boolean> private lateinit var byteAdapter: DelegateAdapter<Byte> private lateinit var charAdapter: DelegateAdapter<Char> private lateinit var shortAdapter: DelegateAdapter<Short> private lateinit var intAdapter: DelegateAdapter<Int> private lateinit var longAdapter: DelegateAdapter<Long> private lateinit var floatAdapter: DelegateAdapter<Float> private lateinit var doubleAdapter: DelegateAdapter<Double> @Before fun setup() { val basicMoshi = Moshi.Builder().build() stringAdapter = DelegateAdapter(basicMoshi.adapter(String::class.java)) booleanAdapter = DelegateAdapter(basicMoshi.adapter(Boolean::class.java)) byteAdapter = DelegateAdapter(basicMoshi.adapter(Byte::class.java)) charAdapter = DelegateAdapter(basicMoshi.adapter(Char::class.java)) shortAdapter = DelegateAdapter(basicMoshi.adapter(Short::class.java)) intAdapter = DelegateAdapter(basicMoshi.adapter(Int::class.java)) longAdapter = DelegateAdapter(basicMoshi.adapter(Long::class.java)) floatAdapter = DelegateAdapter(basicMoshi.adapter(Float::class.java)) doubleAdapter = DelegateAdapter(basicMoshi.adapter(Double::class.java)) moshi = Moshi.Builder() .add(TestFactory) .add(String::class.java, stringAdapter) .add(Boolean::class.javaPrimitiveType!!, booleanAdapter) .add(Boolean::class.javaObjectType, booleanAdapter) .add(Byte::class.javaPrimitiveType!!, byteAdapter) .add(Byte::class.javaObjectType, byteAdapter) .add(Char::class.javaPrimitiveType!!, charAdapter) .add(Char::class.javaObjectType, charAdapter) .add(Short::class.javaPrimitiveType!!, shortAdapter) .add(Short::class.javaObjectType, shortAdapter) .add(Int::class.javaPrimitiveType!!, intAdapter) .add(Int::class.javaObjectType, intAdapter) .add(Long::class.javaPrimitiveType!!, longAdapter) .add(Long::class.javaObjectType, longAdapter) .add(Float::class.javaPrimitiveType!!, floatAdapter) .add(Float::class.javaObjectType, floatAdapter) .add(Double::class.javaPrimitiveType!!, doubleAdapter) .add(Double::class.javaObjectType, doubleAdapter) .add(Int::class.javaObjectType, Hello::class.java, intAdapter) .build() } @Test fun testDoesntCallAdapter() { testFormatting(json, NotUsingPrimitiveAdapterTestClass( aString = "hello", aBoolean = true, aNullableBoolean = false, aByte = -1, nullableByte = Byte.MIN_VALUE, aChar = 'c', nullableChar = 'n', aShort = 32767, nullableShort = -32768, integer = 4711, nullableInteger = 1337, aLong = 4711, nullableLong = 1337, aFloat = 4711.5f, nullableFloat = 1337.5f, aDouble = 4711.5, nullableDouble = 1337.5)) assertEquals(0, stringAdapter.readCount) assertEquals(0, stringAdapter.writeCount) assertEquals(0, booleanAdapter.readCount) assertEquals(0, booleanAdapter.writeCount) assertEquals(0, byteAdapter.readCount) assertEquals(0, byteAdapter.writeCount) assertEquals(0, charAdapter.readCount) assertEquals(0, charAdapter.writeCount) assertEquals(0, shortAdapter.readCount) assertEquals(0, shortAdapter.writeCount) assertEquals(0, intAdapter.readCount) assertEquals(0, intAdapter.writeCount) assertEquals(0, longAdapter.readCount) assertEquals(0, longAdapter.writeCount) assertEquals(0, floatAdapter.readCount) assertEquals(0, floatAdapter.writeCount) assertEquals(0, doubleAdapter.readCount) assertEquals(0, doubleAdapter.writeCount) } @Test fun testCallsAdapter() { testFormatting(json, UsingPrimitiveAdapterTestClass( aString = "hello", aBoolean = true, aNullableBoolean = false, aByte = -1, nullableByte = Byte.MIN_VALUE, aChar = 'c', nullableChar = 'n', aShort = 32767, nullableShort = -32768, integer = 4711, nullableInteger = 1337, aLong = 4711, nullableLong = 1337, aFloat = 4711.5f, nullableFloat = 1337.5f, aDouble = 4711.5, nullableDouble = 1337.5)) assertEquals(1, stringAdapter.readCount) assertEquals(1, stringAdapter.writeCount) assertEquals(2, booleanAdapter.readCount) assertEquals(2, booleanAdapter.writeCount) assertEquals(2, byteAdapter.readCount) assertEquals(2, byteAdapter.writeCount) assertEquals(2, charAdapter.readCount) assertEquals(2, charAdapter.writeCount) assertEquals(2, shortAdapter.readCount) assertEquals(2, shortAdapter.writeCount) assertEquals(2, intAdapter.readCount) assertEquals(2, intAdapter.writeCount) assertEquals(2, longAdapter.readCount) assertEquals(2, longAdapter.writeCount) assertEquals(2, floatAdapter.readCount) assertEquals(2, floatAdapter.writeCount) assertEquals(2, doubleAdapter.readCount) assertEquals(2, doubleAdapter.writeCount) } @Test fun callsAdapterWhenQualifiersPresent() { testFormatting("""{ | "greetingInt": 1 |}""".trimMargin(), PrimitiveWithJsonQualifierTestClass(1)) assertEquals(1, intAdapter.readCount) assertEquals(1, intAdapter.writeCount) } private inline fun <reified T> testFormatting(json: String, expected: T) { val adapter = moshi.adapter(T::class.java) val actual = adapter.fromJson(json) assertEquals(expected, actual) assertEquals(json, Buffer() .apply { JsonWriter.of(this).run { indent = " " adapter.toJson(this, actual) } } .readUtf8()) } companion object { val json = """{ | "aString": "hello", | "aBoolean": true, | "aNullableBoolean": false, | "aByte": 255, | "nullableByte": 128, | "aChar": "c", | "nullableChar": "n", | "aShort": 32767, | "nullableShort": -32768, | "integer": 4711, | "nullableInteger": 1337, | "aLong": 4711, | "nullableLong": 1337, | "aFloat": 4711.5, | "nullableFloat": 1337.5, | "aDouble": 4711.5, | "nullableDouble": 1337.5 |}""".trimMargin() } private class DelegateAdapter<T>(private val delegate: JsonAdapter<T>) : JsonAdapter<T>() { var writeCount: Int = 0 private set var readCount: Int = 0 private set override fun toJson(writer: JsonWriter, value: T?) { writeCount += 1 delegate.toJson(writer, value) } override fun fromJson(reader: JsonReader): T? { readCount += 1 return delegate.fromJson(reader) } } }
apache-2.0
e58576637ce56d51fc0033083088b5b4
37.714286
95
0.617842
4.942138
false
true
false
false
splitwise/TokenAutoComplete
library/src/main/java/com/tokenautocomplete/TokenCompleteTextView.kt
1
60517
package com.tokenautocomplete import android.content.Context import android.graphics.Rect import android.graphics.Typeface import android.os.Build import android.os.Parcel import android.os.Parcelable import android.text.Editable import android.text.InputFilter import android.text.InputType import android.text.Layout import android.text.NoCopySpan import android.text.Selection import android.text.SpanWatcher import android.text.Spannable import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.Spanned import android.text.TextUtils import android.text.TextWatcher import android.text.style.ForegroundColorSpan import android.util.AttributeSet import android.util.Log import android.view.KeyEvent import android.view.MotionEvent import android.view.View import android.view.accessibility.AccessibilityEvent import android.view.inputmethod.EditorInfo import android.view.inputmethod.ExtractedText import android.view.inputmethod.ExtractedTextRequest import android.view.inputmethod.InputConnection import android.view.inputmethod.InputConnectionWrapper import android.view.inputmethod.InputMethodManager import android.widget.ListView import android.widget.TextView import android.widget.TextView.OnEditorActionListener import androidx.annotation.UiThread import androidx.appcompat.widget.AppCompatAutoCompleteTextView import java.io.Serializable import java.lang.reflect.ParameterizedType import java.util.* /** * GMail style auto complete view with easy token customization * override getViewForObject to provide your token view * <br></br> * Created by mgod on 9/12/13. * * @author mgod */ abstract class TokenCompleteTextView<T: Any> : AppCompatAutoCompleteTextView, OnEditorActionListener, ViewSpan.Layout { //When the user clicks on a token... enum class TokenClickStyle(val isSelectable: Boolean) { None(false), //...do nothing, but make sure the cursor is not in the token Delete(false), //...delete the token Select(true), //...select the token. A second click will delete it. SelectDeselect(true); } private var tokenizer: Tokenizer? = null private var selectedObject: T? = null private var listener: TokenListener<T>? = null private var spanWatcher: TokenSpanWatcher = TokenSpanWatcher() private var textWatcher: TokenTextWatcher = TokenTextWatcher() private var countSpan: CountSpan = CountSpan() private var hiddenContent: SpannableStringBuilder? = null private var tokenClickStyle: TokenClickStyle? = TokenClickStyle.None private var prefix: CharSequence? = null private var lastLayout: Layout? = null private var initialized = false private var performBestGuess = true private var preventFreeFormText = true private var savingState = false private var shouldFocusNext = false private var allowCollapse = true private var internalEditInProgress = false private var inBatchEditAPI26to29Workaround = false private var tokenLimit = -1 /** * Android M/API 30 introduced a change to the SpannableStringBuilder that triggers additional * text change callbacks when we do our token replacement. It's supposed to report if it's a * recursive call to the callbacks to let the recipient handle nested calls differently, but * for some reason, in our case the first and second callbacks both report a depth of 1 and only * on the third callback do we get a depth of 2, so we need to track this ourselves. */ private var ignoreNextTextCommit = false @Transient private var lastCompletionText: String? = null private val hintVisible: Boolean get() { return text.getSpans(0, text.length, HintSpan::class.java).isNotEmpty() } /** * Add the TextChangedListeners */ protected open fun addListeners() { val text = text if (text != null) { text.setSpan(spanWatcher, 0, text.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE) addTextChangedListener(textWatcher) } } /** * Remove the TextChangedListeners */ protected open fun removeListeners() { val text = text if (text != null) { val spanWatchers = text.getSpans(0, text.length, TokenSpanWatcher::class.java) for (watcher in spanWatchers) { text.removeSpan(watcher) } removeTextChangedListener(textWatcher) } } /** * Initialise the variables and various listeners */ private fun init() { if (initialized) return // Initialise variables setTokenizer(CharacterTokenizer(listOf(',', ';'), ",")) // Initialise TextChangedListeners addListeners() setTextIsSelectable(false) isLongClickable = false //In theory, get the soft keyboard to not supply suggestions. very unreliable inputType = inputType or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE setHorizontallyScrolling(false) // Listen to IME action keys setOnEditorActionListener(this) // Initialise the text filter (listens for the split chars) filters = arrayOf(InputFilter { source, _, _, _, destinationStart, destinationEnd -> if (internalEditInProgress) { return@InputFilter null } // Token limit check if (tokenLimit != -1 && objects.size == tokenLimit) { return@InputFilter "" } //Detect split characters, remove them and complete the current token instead if (tokenizer!!.containsTokenTerminator(source)) { //Only perform completion if we don't allow free form text, or if there's enough //content to believe this should be a token if (preventFreeFormText || currentCompletionText().isNotEmpty()) { performCompletion() return@InputFilter "" } } //We need to not do anything when we would delete the prefix prefix?.also { prefix -> if (destinationStart < prefix.length) { //when setText is called, which should only be called during restoring, //destinationStart and destinationEnd are 0. If not checked, it will clear out //the prefix. //This is why we need to return null in this if condition to preserve state. if (destinationStart == 0 && destinationEnd == 0) { return@InputFilter null } else return@InputFilter if (destinationEnd <= prefix.length) { //Don't do anything prefix.subSequence(destinationStart, destinationEnd) } else { //Delete everything up to the prefix prefix.subSequence(destinationStart, prefix.length) } } } null }) initialized = true } constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super( context, attrs, defStyle ) { init() } override fun performFiltering(text: CharSequence, keyCode: Int) { val filter = filter filter?.filter(currentCompletionText(), this) } fun setTokenizer(t: Tokenizer) { tokenizer = t } /** * Set the action to be taken when a Token is clicked * * @param cStyle The TokenClickStyle */ fun setTokenClickStyle(cStyle: TokenClickStyle) { tokenClickStyle = cStyle } /** * Set the listener that will be notified of changes in the Token list * * @param l The TokenListener */ fun setTokenListener(l: TokenListener<T>?) { listener = l } /** * Override if you want to prevent a token from being added. Defaults to false. * @param token the token to check * @return true if the token should not be added, false if it's ok to add it. */ open fun shouldIgnoreToken(token: T): Boolean { return false } /** * Override if you want to prevent a token from being removed. Defaults to true. * @param token the token to check * @return false if the token should not be removed, true if it's ok to remove it. */ open fun isTokenRemovable(@Suppress("unused_parameter") token: T): Boolean { return true } /** * A String of text that is shown before all the tokens inside the EditText * (Think "To: " in an email address field. I would advise against this: use a label and a hint. * * @param p String with the hint */ @Suppress("MemberVisibilityCanBePrivate") fun setPrefix(p: CharSequence) { //Have to clear and set the actual text before saving the prefix to avoid the prefix filter val prevPrefix = prefix prefix = p val text = text if (text != null) { internalEditInProgress = true if (prevPrefix.isNullOrEmpty()) { text.insert(0, p) } else { text.replace(0, prevPrefix.length, p) } internalEditInProgress = false } //prefix = p; updateHint() } /** * * You can get a color integer either using * [androidx.core.content.ContextCompat.getColor] * or with [android.graphics.Color.parseColor]. * * [android.graphics.Color.parseColor] * accepts these formats (copied from android.graphics.Color): * You can use: '#RRGGBB', '#AARRGGBB' * or one of the following names: 'red', 'blue', 'green', 'black', 'white', * 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', * 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', * 'olive', 'purple', 'silver', 'teal'. * * @param prefix prefix * @param color A single color value in the form 0xAARRGGBB. */ fun setPrefix(prefix: CharSequence, color: Int) { val spannablePrefix = SpannableString(prefix) spannablePrefix.setSpan(ForegroundColorSpan(color), 0, spannablePrefix.length, 0) setPrefix(spannablePrefix) } /** * Get the list of Tokens * * @return List of tokens */ val objects: List<T> get() { val objects = ArrayList<T>() var text = text if (hiddenContent != null) { text = hiddenContent } for (span in text.getSpans(0, text.length, TokenImageSpan::class.java)) { @Suppress("unchecked_cast") objects.add(span.token as T) } return objects } /** * Get the content entered in the text field, including hidden text when ellipsized * * @return CharSequence of the entered content */ val contentText: CharSequence get() = hiddenContent ?: text /** * Set whether we try to guess an entry from the autocomplete spinner or just use the * defaultObject implementation for inline token completion. * * @param guess true to enable guessing */ fun performBestGuess(guess: Boolean) { performBestGuess = guess } /** * If set to true, the only content in this view will be the tokens and the current completion * text. Use this setting to create things like lists of email addresses. If false, it the view * will allow text in addition to tokens. Use this if you want to use the token search to find * things like user names or hash tags to put in with text. * * @param prevent true to prevent non-token text. Defaults to true. */ fun preventFreeFormText(prevent: Boolean) { preventFreeFormText = prevent } /** * Set whether the view should collapse to a single line when it loses focus. * * @param allowCollapse true if it should collapse */ fun allowCollapse(allowCollapse: Boolean) { this.allowCollapse = allowCollapse } /** * Set a number of tokens limit. * * @param tokenLimit The number of tokens permitted. -1 value disables limit. */ @Suppress("unused") fun setTokenLimit(tokenLimit: Int) { this.tokenLimit = tokenLimit } /** * A token view for the object * * @param obj the object selected by the user from the list * @return a view to display a token in the text field for the object */ protected abstract fun getViewForObject(obj: T): View? /** * Provides a default completion when the user hits , and there is no item in the completion * list * * @param completionText the current text we are completing against * @return a best guess for what the user meant to complete or null if you don't want a guess */ protected abstract fun defaultObject(completionText: String): T? //Replace token spans //Need to take the existing tet buffer and // - replace all tokens with a decent string representation of the object // - set the selection span to the corresponding location in the new CharSequence /** * Correctly build accessibility string for token contents * * This seems to be a hidden API, but there doesn't seem to be another reasonable way * @return custom string for accessibility */ @Suppress("MemberVisibilityCanBePrivate") open val textForAccessibility: CharSequence get() { if (objects.isEmpty()) { return text } var description = SpannableStringBuilder() val text = text var selectionStart = -1 var selectionEnd = -1 var i: Int //Need to take the existing tet buffer and // - replace all tokens with a decent string representation of the object // - set the selection span to the corresponding location in the new CharSequence i = 0 while (i < text.length) { //See if this is where we should start the selection val origSelectionStart = Selection.getSelectionStart(text) if (i == origSelectionStart) { selectionStart = description.length } val origSelectionEnd = Selection.getSelectionEnd(text) if (i == origSelectionEnd) { selectionEnd = description.length } //Replace token spans val tokens = text.getSpans(i, i, TokenImageSpan::class.java) if (tokens.isNotEmpty()) { val token = tokens[0] description = description.append(tokenizer!!.wrapTokenValue(token.token.toString())) i = text.getSpanEnd(token) ++i continue } description = description.append(text.subSequence(i, i + 1)) ++i } val origSelectionStart = Selection.getSelectionStart(text) if (i == origSelectionStart) { selectionStart = description.length } val origSelectionEnd = Selection.getSelectionEnd(text) if (i == origSelectionEnd) { selectionEnd = description.length } if (selectionStart >= 0 && selectionEnd >= 0) { Selection.setSelection(description, selectionStart, selectionEnd) } return description } /** * Clear the completion text only. */ @Suppress("unused") fun clearCompletionText() { //Respect currentCompletionText in case hint is visible or if other checks are added. if (currentCompletionText().isEmpty()) { return } val currentRange = currentCandidateTokenRange internalEditInProgress = true text.delete(currentRange.start, currentRange.end) internalEditInProgress = false } override fun onInitializeAccessibilityEvent(event: AccessibilityEvent) { super.onInitializeAccessibilityEvent(event) if (event.eventType == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { val text = textForAccessibility event.fromIndex = Selection.getSelectionStart(text) event.toIndex = Selection.getSelectionEnd(text) event.itemCount = text.length } } //Don't try to search the hint for possible tokenizable strings //We want to find the largest string that contains the selection end that is not already tokenized private val currentCandidateTokenRange: Range get() { val editable = text val cursorEndPosition = selectionEnd var candidateStringStart = prefix?.length ?: 0 var candidateStringEnd = editable.length if (hintVisible) { //Don't try to search the hint for possible tokenizable strings candidateStringEnd = candidateStringStart } //We want to find the largest string that contains the selection end that is not already tokenized val spans = editable.getSpans(prefix?.length ?: 0, editable.length, TokenImageSpan::class.java) for (span in spans) { val spanEnd = editable.getSpanEnd(span) if (spanEnd in (candidateStringStart + 1)..cursorEndPosition) { candidateStringStart = spanEnd } val spanStart = editable.getSpanStart(span) if (candidateStringEnd > spanStart && cursorEndPosition <= spanEnd) { candidateStringEnd = spanStart } } val tokenRanges = tokenizer!!.findTokenRanges(editable, candidateStringStart, candidateStringEnd) for (range in tokenRanges) { @Suppress("unused") if (range.start <= cursorEndPosition && cursorEndPosition <= range.end) { return range } } return Range(cursorEndPosition, cursorEndPosition) } /** * Override if you need custom logic to provide a sting representation of a token * @param token the token to convert * @return the string representation of the token. Defaults to [Object.toString] */ @Suppress("MemberVisibilityCanBePrivate") protected open fun tokenToString(token: T): CharSequence { return token.toString() } protected open fun currentCompletionText(): String { if (hintVisible) return "" //Can't have any text if the hint is visible val editable = text val currentRange = currentCandidateTokenRange val result = TextUtils.substring(editable, currentRange.start, currentRange.end) Log.d(TAG, "Current completion text: $result") return result } @Suppress("MemberVisibilityCanBePrivate") protected open fun maxTextWidth(): Float { return (width - paddingLeft - paddingRight).toFloat() } override val maxViewSpanWidth: Int get() = maxTextWidth().toInt() fun redrawTokens() { // There's no straight-forward way to convince the widget to redraw the text and spans. We trigger a redraw by // making an invisible change (either adding or removing a dummy span). val text = text ?: return val textLength = text.length val dummySpans = text.getSpans(0, textLength, DummySpan::class.java) if (dummySpans.isNotEmpty()) { text.removeSpan(DummySpan.INSTANCE) } else { text.setSpan( DummySpan.INSTANCE, 0, textLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE ) } } override fun enoughToFilter(): Boolean { if (tokenizer == null || hintVisible) { return false } val cursorPosition = selectionEnd if (cursorPosition < 0) { return false } val currentCandidateRange = currentCandidateTokenRange //Don't allow 0 length entries to filter @Suppress("MemberVisibilityCanBePrivate") return currentCandidateRange.length() >= threshold.coerceAtLeast(1) } override fun performCompletion() { if ((adapter == null || listSelection == ListView.INVALID_POSITION) && enoughToFilter()) { val bestGuess: Any? = if (adapter != null && adapter.count > 0 && performBestGuess) { adapter.getItem(0) } else { defaultObject(currentCompletionText()) } replaceText(convertSelectionToString(bestGuess)) } else { super.performCompletion() } } override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection { val superConn = super.onCreateInputConnection(outAttrs) val conn = TokenInputConnection(superConn, true) outAttrs.imeOptions = outAttrs.imeOptions and EditorInfo.IME_FLAG_NO_ENTER_ACTION.inv() outAttrs.imeOptions = outAttrs.imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI return conn } /** * Create a token and hide the keyboard when the user sends the DONE IME action * Use IME_NEXT if you want to create a token and go to the next field */ private fun handleDone() { // Attempt to complete the current token token performCompletion() // Hide the keyboard val imm = context.getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager imm.hideSoftInputFromWindow(windowToken, 0) } override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { val handled = super.onKeyUp(keyCode, event) if (shouldFocusNext) { shouldFocusNext = false handleDone() } return handled } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { var handled = false when (keyCode) { KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_DPAD_CENTER -> if (event?.hasNoModifiers() == true) { shouldFocusNext = true handled = true } KeyEvent.KEYCODE_DEL -> handled = !canDeleteSelection(1) || deleteSelectedObject() } return handled || super.onKeyDown(keyCode, event) } private fun deleteSelectedObject(): Boolean { if (tokenClickStyle?.isSelectable == true) { val text = text ?: return false @Suppress("unchecked_cast") val spans: Array<TokenImageSpan> = text.getSpans(0, text.length, TokenImageSpan::class.java) as Array<TokenImageSpan> for (span in spans) { if (span.view.isSelected) { removeSpan(text, span) return true } } } return false } override fun onEditorAction(view: TextView, action: Int, keyEvent: KeyEvent?): Boolean { if (action == EditorInfo.IME_ACTION_DONE) { handleDone() return true } return false } override fun onTouchEvent(event: MotionEvent): Boolean { val action = event.actionMasked val text = text var handled = false if (tokenClickStyle == TokenClickStyle.None) { handled = super.onTouchEvent(event) } if (isFocused && text != null && lastLayout != null && action == MotionEvent.ACTION_UP) { val offset = getOffsetForPosition(event.x, event.y) if (offset != -1) { @Suppress("unchecked_cast") val links: Array<TokenImageSpan> = text.getSpans(offset, offset, TokenImageSpan::class.java) as Array<TokenImageSpan> if (links.isNotEmpty()) { links[0].onClick() handled = true } else { //We didn't click on a token, so if any are selected, we should clear that clearSelections() } } } if (!handled && tokenClickStyle != TokenClickStyle.None) { handled = super.onTouchEvent(event) } return handled } override fun onSelectionChanged(selStart: Int, selEnd: Int) { var selectionStart = selStart if (hintVisible) { //Don't let users select the hint selectionStart = 0 } //Never let users select text val selectionEnd = selectionStart if (tokenClickStyle?.isSelectable == true) { val text = text if (text != null) { clearSelections() } } if (selectionStart < prefix?.length ?: 0 || selectionEnd < prefix?.length ?: 0) { //Don't let users select the prefix setSelection(prefix?.length ?: 0) } else { val text = text if (text != null) { //Make sure if we are in a span, we select the spot 1 space after the span end @Suppress("unchecked_cast") val spans: Array<TokenImageSpan> = text.getSpans(selectionStart, selectionEnd, TokenImageSpan::class.java) as Array<TokenImageSpan> for (span in spans) { val spanEnd = text.getSpanEnd(span) if (selectionStart <= spanEnd && text.getSpanStart(span) < selectionStart) { if (spanEnd == text.length) setSelection(spanEnd) else setSelection(spanEnd + 1) return } } } super.onSelectionChanged(selectionStart, selectionEnd) } } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) lastLayout = layout //Used for checking text positions } /** * Collapse the view by removing all the tokens not on the first line. Displays a "+x" token. * Restores the hidden tokens when the view gains focus. * * @param hasFocus boolean indicating whether we have the focus or not. */ open fun performCollapse(hasFocus: Boolean) { internalEditInProgress = true if (!hasFocus) { // Display +x thingy/ellipse if appropriate val text = text if (text != null && hiddenContent == null && lastLayout != null) { //Ellipsize copies spans, so we need to stop listening to span changes here text.removeSpan(spanWatcher) val temp = if (preventFreeFormText) countSpan else null val ellipsized = SpanUtils.ellipsizeWithSpans( prefix, temp, objects.size, lastLayout!!.paint, text, maxTextWidth() ) if (ellipsized != null) { hiddenContent = SpannableStringBuilder(text) setText(ellipsized) TextUtils.copySpansFrom( ellipsized, 0, ellipsized.length, TokenImageSpan::class.java, getText(), 0 ) TextUtils.copySpansFrom( text, 0, hiddenContent!!.length, TokenImageSpan::class.java, hiddenContent, 0 ) hiddenContent!!.setSpan( spanWatcher, 0, hiddenContent!!.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE ) } else { getText().setSpan( spanWatcher, 0, getText().length, Spanned.SPAN_INCLUSIVE_INCLUSIVE ) } } } else { if (hiddenContent != null) { text = hiddenContent TextUtils.copySpansFrom( hiddenContent, 0, hiddenContent!!.length, TokenImageSpan::class.java, text, 0 ) hiddenContent = null if (hintVisible) { setSelection(prefix?.length ?: 0) } else { post { setSelection(text.length) } } @Suppress("unchecked_cast") val watchers: Array<TokenSpanWatcher> = text.getSpans(0, text.length, TokenSpanWatcher::class.java) as Array<TokenSpanWatcher> if (watchers.isEmpty()) { //Span watchers can get removed in setText text.setSpan(spanWatcher, 0, text.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE) } } } internalEditInProgress = false } public override fun onFocusChanged(hasFocus: Boolean, direction: Int, previous: Rect?) { super.onFocusChanged(hasFocus, direction, previous) // Clear sections when focus changes to avoid a token remaining selected clearSelections() // Collapse the view to a single line if (allowCollapse) performCollapse(hasFocus) } override fun convertSelectionToString(selectedObject: Any?): CharSequence { @Suppress("unchecked_cast") this.selectedObject = selectedObject as T? return "" } @Suppress("MemberVisibilityCanBePrivate") protected open fun buildSpanForObject(obj: T?): TokenImageSpan? { if (obj == null) { return null } return getViewForObject(obj)?.let { TokenImageSpan(it, obj) } } override fun replaceText(ignore: CharSequence) { clearComposingText() // Don't build a token for an empty String if (selectedObject?.toString().isNullOrEmpty()) return val tokenSpan = buildSpanForObject(selectedObject) val editable = text val candidateRange = currentCandidateTokenRange val original = TextUtils.substring(editable, candidateRange.start, candidateRange.end) //Keep track of replacements for a bug workaround if (original.isNotEmpty()) { lastCompletionText = original } if (editable != null) { internalEditInProgress = true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ignoreNextTextCommit = true } if (tokenSpan == null) { editable.replace(candidateRange.start, candidateRange.end, "") } else if (shouldIgnoreToken(tokenSpan.token)) { editable.replace(candidateRange.start, candidateRange.end, "") if (listener != null) { listener?.onTokenIgnored(tokenSpan.token) } } else { val ssb = SpannableStringBuilder(tokenizer!!.wrapTokenValue(tokenToString(tokenSpan.token))) editable.replace(candidateRange.start, candidateRange.end, ssb) editable.setSpan( tokenSpan, candidateRange.start, candidateRange.start + ssb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) editable.insert(candidateRange.start + ssb.length, " ") } internalEditInProgress = false } } override fun extractText(request: ExtractedTextRequest, outText: ExtractedText): Boolean { return try { super.extractText(request, outText) } catch (ex: IndexOutOfBoundsException) { Log.d(TAG, "extractText hit IndexOutOfBoundsException. This may be normal.", ex) false } } /** * Append a token object to the object list. May only be called from the main thread. * * @param obj the object to add to the displayed tokens */ @UiThread fun addObjectSync(obj: T) { if (shouldIgnoreToken(obj)) { if (listener != null) { listener?.onTokenIgnored(obj) } return } if (tokenLimit != -1 && objects.size == tokenLimit) return buildSpanForObject(obj)?.also { insertSpan(it) } if (text != null && isFocused) setSelection(text.length) } /** * Append a token object to the object list. Object will be added on the main thread. * * @param obj the object to add to the displayed tokens */ fun addObjectAsync(obj: T) { post { addObjectSync(obj) } } /** * Remove an object from the token list. Will remove duplicates if present or do nothing if no * object is present in the view. Uses [Object.equals] to find objects. May only * be called from the main thread * * @param obj object to remove, may be null or not in the view */ @UiThread fun removeObjectSync(obj: T) { //To make sure all the appropriate callbacks happen, we just want to piggyback on the //existing code that handles deleting spans when the text changes val texts = ArrayList<Editable>() //If there is hidden content, it's important that we update it first hiddenContent?.also { texts.add(it) } if (text != null) { texts.add(text) } // If the object is currently visible, remove it for (text in texts) { @Suppress("unchecked_cast") val spans: Array<TokenImageSpan> = text.getSpans(0, text.length, TokenImageSpan::class.java) as Array<TokenImageSpan> for (span in spans) { if (span.token == obj) { removeSpan(text, span) } } } updateCountSpan() } /** * Remove an object from the token list. Will remove duplicates if present or do nothing if no * object is present in the view. Uses [Object.equals] to find objects. Object * will be added on the main thread * * @param obj object to remove, may be null or not in the view */ fun removeObjectAsync(obj: T) { post { removeObjectSync(obj) } } /** * Remove all objects from the token list. Objects will be removed on the main thread. */ fun clearAsync() { post { for (obj in objects) { removeObjectSync(obj) } } } /** * Set the count span the current number of hidden objects */ private fun updateCountSpan() { //No count span with free form text if (!preventFreeFormText) { return } val text = text val visibleCount = getText().getSpans(0, getText().length, TokenImageSpan::class.java).size countSpan.setCount(objects.size - visibleCount) val spannedCountText = SpannableStringBuilder(countSpan.countText) spannedCountText.setSpan( countSpan, 0, spannedCountText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) internalEditInProgress = true val countStart = text.getSpanStart(countSpan) if (countStart != -1) { //Span is in the text, replace existing text //This will also remove the span if the count is 0 text.replace(countStart, text.getSpanEnd(countSpan), spannedCountText) } else { text.append(spannedCountText) } internalEditInProgress = false } /** * Remove a span from the current EditText and fire the appropriate callback * * @param text Editable to remove the span from * @param span TokenImageSpan to be removed */ private fun removeSpan(text: Editable, span: TokenImageSpan) { //We usually add whitespace after a token, so let's try to remove it as well if it's present var end = text.getSpanEnd(span) if (end < text.length && text[end] == ' ') { end += 1 } internalEditInProgress = true text.delete(text.getSpanStart(span), end) internalEditInProgress = false if (allowCollapse && !isFocused) { updateCountSpan() } } /** * Insert a new span for an Object * * @param tokenSpan span to insert */ private fun insertSpan(tokenSpan: TokenImageSpan) { val ssb = tokenizer!!.wrapTokenValue(tokenToString(tokenSpan.token)) val editable = text ?: return // If we haven't hidden any objects yet, we can try adding it if (hiddenContent == null) { internalEditInProgress = true var offset = editable.length //There might be a hint visible... if (hintVisible) { //...so we need to put the object in in front of the hint offset = prefix?.length ?: 0 } else { val currentRange = currentCandidateTokenRange if (currentRange.length() > 0) { // The user has entered some text that has not yet been tokenized. // Find the beginning of this text and insert the new token there. offset = currentRange.start } } editable.insert(offset, ssb) editable.insert(offset + ssb.length, " ") editable.setSpan( tokenSpan, offset, offset + ssb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) internalEditInProgress = false } else { val tokenText = tokenizer!!.wrapTokenValue( tokenToString( tokenSpan.token ) ) val start = hiddenContent!!.length hiddenContent!!.append(tokenText) hiddenContent!!.append(" ") hiddenContent!!.setSpan( tokenSpan, start, start + tokenText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) updateCountSpan() } } private fun updateHint() { val text = text val hintText = hint if (text == null || hintText == null) { return } //Show hint if we need to if (prefix?.isNotEmpty() == true) { val hints = text.getSpans(0, text.length, HintSpan::class.java) var hint: HintSpan? = null var testLength = prefix?.length ?: 0 if (hints.isNotEmpty()) { hint = hints[0] testLength += text.getSpanEnd(hint) - text.getSpanStart(hint) } if (text.length == testLength) { if (hint != null) { return //hint already visible } //We need to display the hint manually val tf = typeface var style = Typeface.NORMAL if (tf != null) { style = tf.style } val colors = hintTextColors val hintSpan = HintSpan(null, style, textSize.toInt(), colors, colors) internalEditInProgress = true val spannedHint = SpannableString(hintText) spannedHint.setSpan(hintSpan, 0, spannedHint.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) text.insert(prefix?.length ?: 0, spannedHint) internalEditInProgress = false setSelection(prefix?.length ?: 0) } else { if (hint == null) { return //hint already removed } //Remove the hint. There should only ever be one val sStart = text.getSpanStart(hint) val sEnd = text.getSpanEnd(hint) internalEditInProgress = true text.removeSpan(hint) text.replace(sStart, sEnd, "") setSelection(sStart) internalEditInProgress = false } } } private fun clearSelections() { if (tokenClickStyle?.isSelectable != true) return val text = text ?: return @Suppress("unchecked_cast") val tokens: Array<TokenImageSpan> = text.getSpans(0, text.length, TokenImageSpan::class.java) as Array<TokenImageSpan> var shouldRedrawTokens = false for (token in tokens) { if (token.view.isSelected) { token.view.isSelected = false shouldRedrawTokens = true } } if (shouldRedrawTokens) { redrawTokens() } } inner class TokenImageSpan(d: View, val token: T) : ViewSpan(d, this@TokenCompleteTextView), NoCopySpan { fun onClick() { val text = text ?: return when (tokenClickStyle) { TokenClickStyle.Select, TokenClickStyle.SelectDeselect -> { if (!view.isSelected) { clearSelections() view.isSelected = true redrawTokens() } else if (tokenClickStyle == TokenClickStyle.SelectDeselect || !isTokenRemovable(token)) { view.isSelected = false redrawTokens() } else if (isTokenRemovable(token)) { removeSpan(text, this) } } TokenClickStyle.Delete -> if (isTokenRemovable(token)) { removeSpan(text, this) } TokenClickStyle.None -> if (selectionStart != text.getSpanEnd(this)) { //Make sure the selection is not in the middle of the span setSelection(text.getSpanEnd(this)) } else -> {} } } } interface TokenListener<T> { fun onTokenAdded(token: T) fun onTokenRemoved(token: T) fun onTokenIgnored(token: T) } private inner class TokenSpanWatcher : SpanWatcher { override fun onSpanAdded(text: Spannable, what: Any, start: Int, end: Int) { if (what is TokenCompleteTextView<*>.TokenImageSpan && !savingState) { // If we're not focused: collapse the view if necessary if (!isFocused && allowCollapse) performCollapse(false) @Suppress("unchecked_cast") if (listener != null) listener?.onTokenAdded(what.token as T) } } override fun onSpanRemoved(text: Spannable, what: Any, start: Int, end: Int) { if (what is TokenCompleteTextView<*>.TokenImageSpan && !savingState) { @Suppress("unchecked_cast") if (listener != null) listener?.onTokenRemoved(what.token as T) } } override fun onSpanChanged( text: Spannable, what: Any, oldStart: Int, oldEnd: Int, newStart: Int, newEnd: Int ) { } } private inner class TokenTextWatcher : TextWatcher { var spansToRemove = ArrayList<TokenImageSpan>() override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { if (internalEditInProgress || ignoreNextTextCommit) return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (s is SpannableStringBuilder && s.textWatcherDepth > 1) return } // count > 0 means something will be deleted if (count > 0 && text != null) { val text = text val end = start + count @Suppress("unchecked_cast") val spans = text.getSpans(start, end, TokenImageSpan::class.java) as Array<TokenCompleteTextView<T>.TokenImageSpan> //NOTE: I'm not completely sure this won't cause problems if we get stuck in a text changed loop //but it appears to work fine. Spans will stop getting removed if this breaks. val spansToRemove = ArrayList<TokenImageSpan>() for (token in spans) { if (text.getSpanStart(token) < end && start < text.getSpanEnd(token)) { spansToRemove.add(token) } } this.spansToRemove = spansToRemove } } override fun afterTextChanged(text: Editable) { if (!internalEditInProgress) { val spansCopy = ArrayList(spansToRemove) spansToRemove.clear() for (token in spansCopy) { //Only remove it if it's still present if (text.getSpanStart(token) != -1 && text.getSpanEnd(token) != -1) { removeSpan(text, token) } } ignoreNextTextCommit = false } clearSelections() if (!inBatchEditAPI26to29Workaround) { updateHint() } } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} } @Suppress("MemberVisibilityCanBePrivate") protected open fun getSerializableObjects(): List<Serializable> { val serializables = ArrayList<Serializable>() for (obj in objects) { if (obj is Serializable) { serializables.add(obj as Serializable) } else { Log.e(TAG, "Unable to save '$obj'") } } if (serializables.size != objects.size) { val message = """ You should make your objects Serializable or Parcelable or override getSerializableObjects and convertSerializableArrayToObjectArray """.trimIndent() Log.e(TAG, message) } return serializables } @Suppress("MemberVisibilityCanBePrivate") protected open fun convertSerializableObjectsToTypedObjects(s: List<*>?): List<T>? { @Suppress("unchecked_cast") return s as List<T>? } //Used to determine if we can use the Parcelable interface private fun reifyParameterizedTypeClass(): Class<*> { //Borrowed from http://codyaray.com/2013/01/finding-generic-type-parameters-with-guava //Figure out what class of objects we have var viewClass: Class<*> = javaClass while (viewClass.superclass != TokenCompleteTextView::class.java) { viewClass = viewClass.superclass as Class<*> } // This operation is safe. Because viewClass is a direct sub-class, getGenericSuperclass() will // always return the Type of this class. Because this class is parameterized, the cast is safe val superclass = viewClass.genericSuperclass as ParameterizedType val type = superclass.actualTypeArguments[0] return type as Class<*> } override fun onSaveInstanceState(): Parcelable { //We don't want to save the listeners as part of the parent //onSaveInstanceState, so remove them first removeListeners() //Apparently, saving the parent state on 2.3 mutates the spannable //prevent this mutation from triggering add or removes of token objects ~mgod savingState = true val superState = super.onSaveInstanceState() savingState = false val state = SavedState(superState) state.prefix = prefix state.allowCollapse = allowCollapse state.performBestGuess = performBestGuess state.preventFreeFormText = preventFreeFormText state.tokenClickStyle = tokenClickStyle val parameterizedClass = reifyParameterizedTypeClass() //Our core array is Parcelable, so use that interface if (Parcelable::class.java.isAssignableFrom(parameterizedClass)) { state.parcelableClassName = parameterizedClass.name state.baseObjects = objects } else { //Fallback on Serializable state.parcelableClassName = SavedState.SERIALIZABLE_PLACEHOLDER state.baseObjects = getSerializableObjects() } state.tokenizer = tokenizer //So, when the screen is locked or some other system event pauses execution, //onSaveInstanceState gets called, but it won't restore state later because the //activity is still in memory, so make sure we add the listeners again //They should not be restored in onInstanceState if the app is actually killed //as we removed them before the parent saved instance state, so our adding them in //onRestoreInstanceState is good. addListeners() return state } override fun onRestoreInstanceState(state: Parcelable) { if (state !is SavedState) { super.onRestoreInstanceState(state) return } super.onRestoreInstanceState(state.superState) internalEditInProgress = true setText(state.prefix) prefix = state.prefix internalEditInProgress = false updateHint() allowCollapse = state.allowCollapse performBestGuess = state.performBestGuess preventFreeFormText = state.preventFreeFormText tokenClickStyle = state.tokenClickStyle tokenizer = state.tokenizer addListeners() val objects: List<T>? = if (SavedState.SERIALIZABLE_PLACEHOLDER == state.parcelableClassName) { convertSerializableObjectsToTypedObjects(state.baseObjects) } else { @Suppress("unchecked_cast") state.baseObjects as List<T>? } //TODO: change this to keep object spans in the correct locations based on ranges. if (objects != null) { for (obj in objects) { addObjectSync(obj) } } // Collapse the view if necessary if (!isFocused && allowCollapse) { post { //Resize the view and display the +x if appropriate performCollapse(isFocused) } } } /** * Handle saving the token state */ private class SavedState : BaseSavedState { var prefix: CharSequence? = null var allowCollapse = false var performBestGuess = false var preventFreeFormText = false var tokenClickStyle: TokenClickStyle? = null var parcelableClassName: String = SERIALIZABLE_PLACEHOLDER var baseObjects: List<*>? = null var tokenizerClassName: String? = null var tokenizer: Tokenizer? = null constructor(parcel: Parcel) : super(parcel) { prefix = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel) allowCollapse = parcel.readInt() != 0 performBestGuess = parcel.readInt() != 0 preventFreeFormText = parcel.readInt() != 0 tokenClickStyle = TokenClickStyle.values()[parcel.readInt()] parcelableClassName = parcel.readString() ?: SERIALIZABLE_PLACEHOLDER baseObjects = if (SERIALIZABLE_PLACEHOLDER == parcelableClassName) { parcel.readSerializable() as ArrayList<*> } else { try { val loader = Class.forName(parcelableClassName).classLoader parcel.readArrayList(loader) } catch (ex: ClassNotFoundException) { //This should really never happen, class had to be available to get here throw RuntimeException(ex) } } tokenizerClassName = parcel.readString() tokenizer = try { val loader = Class.forName(tokenizerClassName!!).classLoader parcel.readParcelable(loader) } catch (ex: ClassNotFoundException) { //This should really never happen, class had to be available to get here throw RuntimeException(ex) } } constructor(superState: Parcelable?) : super(superState) override fun writeToParcel(out: Parcel, flags: Int) { super.writeToParcel(out, flags) TextUtils.writeToParcel(prefix, out, 0) out.writeInt(if (allowCollapse) 1 else 0) out.writeInt(if (performBestGuess) 1 else 0) out.writeInt(if (preventFreeFormText) 1 else 0) out.writeInt((tokenClickStyle ?: TokenClickStyle.None).ordinal) if (SERIALIZABLE_PLACEHOLDER == parcelableClassName) { out.writeString(SERIALIZABLE_PLACEHOLDER) out.writeSerializable(baseObjects as Serializable?) } else { out.writeString(parcelableClassName) out.writeList(baseObjects) } out.writeString(tokenizer!!.javaClass.canonicalName) out.writeParcelable(tokenizer, 0) } override fun toString(): String { val str = ("TokenCompleteTextView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " tokens=" + baseObjects) return "$str}" } companion object { const val SERIALIZABLE_PLACEHOLDER = "Serializable" @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<SavedState?> = object : Parcelable.Creator<SavedState?> { override fun createFromParcel(parcel: Parcel): SavedState { return SavedState(parcel) } override fun newArray(size: Int): Array<SavedState?> { return arrayOfNulls(size) } } } } /** * Checks if selection can be deleted. This method is called from TokenInputConnection . * @param beforeLength the number of characters before the current selection end to check * @return true if there are no non-deletable pieces of the section */ fun canDeleteSelection(beforeLength: Int): Boolean { if (objects.isEmpty()) return true // if beforeLength is 1, we either have no selection or the call is coming from OnKey Event. // In these scenarios, getSelectionStart() will return the correct value. val endSelection = selectionEnd val startSelection = if (beforeLength == 1) selectionStart else endSelection - beforeLength val text = text val spans = text.getSpans(0, text.length, TokenImageSpan::class.java) // Iterate over all tokens and allow the deletion // if there are no tokens not removable in the selection for (span in spans) { val startTokenSelection = text.getSpanStart(span) val endTokenSelection = text.getSpanEnd(span) // moving on, no need to check this token @Suppress("unchecked_cast") if (isTokenRemovable(span.token as T)) continue if (startSelection == endSelection) { // Delete single if (endTokenSelection + 1 == endSelection) { return false } } else { // Delete range // Don't delete if a non removable token is in range if (startSelection <= startTokenSelection && endTokenSelection + 1 <= endSelection ) { return false } } } return true } private inner class TokenInputConnection( target: InputConnection?, mutable: Boolean ) : InputConnectionWrapper(target, mutable) { private val needsWorkaround: Boolean get() { return Build.VERSION_CODES.O <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q } override fun beginBatchEdit(): Boolean { if (needsWorkaround) { inBatchEditAPI26to29Workaround = true } return super.beginBatchEdit() } override fun endBatchEdit(): Boolean { val result = super.endBatchEdit() if (needsWorkaround) { inBatchEditAPI26to29Workaround = false post { updateHint() } } return result } // This will fire if the soft keyboard delete key is pressed. // The onKeyPressed method does not always do this. override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { // Shouldn't be able to delete any text with tokens that are not removable var fixedBeforeLength = beforeLength if (!canDeleteSelection(fixedBeforeLength)) return false //Shouldn't be able to delete prefix, so don't do anything if (selectionStart <= prefix?.length ?: 0) { fixedBeforeLength = 0 return deleteSelectedObject() || super.deleteSurroundingText( fixedBeforeLength, afterLength ) } return super.deleteSurroundingText(fixedBeforeLength, afterLength) } override fun setComposingRegion(start: Int, end: Int): Boolean { //The hint is displayed inline as regular text, but we want to disable normal compose //functionality on it, so if we attempt to set a composing region on the hint, set the //composing region to have length of 0, which indicates there is no composing region //Without this, on many software keyboards, the first word of the hint will be underlined var fixedStart = start var fixedEnd = end if (hintVisible) { fixedEnd = 0 fixedStart = fixedEnd } return super.setComposingRegion(fixedStart, fixedEnd) } override fun setComposingText(text: CharSequence, newCursorPosition: Int): Boolean { //There's an issue with some keyboards where they will try to insert the first word //of the prefix as the composing text var fixedText: CharSequence? = text val hint = hint if (hint != null && fixedText != null) { val firstWord = hint.toString().trim { it <= ' ' }.split(" ").toTypedArray()[0] if (firstWord.isNotEmpty() && firstWord == fixedText.toString()) { fixedText = "" //It was trying to use th hint, so clear that text } } //Also, some keyboards don't correctly respect the replacement if the replacement //is the same number of characters as the replacement span //We need to ignore this value if it's available lastCompletionText?.also { lastCompletion -> fixedText?.also { fixed -> if (fixed.length == lastCompletion.length + 1 && fixed.toString().startsWith(lastCompletion)) { fixedText = fixed.subSequence(fixed.length - 1, fixed.length) lastCompletionText = null } } } return super.setComposingText(fixedText, newCursorPosition) } } companion object { //Logging const val TAG = "TokenAutoComplete" } }
apache-2.0
192c2a684dffab513d67bcfdc9e34b90
37.546497
131
0.583109
5.322047
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/provider/BuildServices.kt
1
4062
/* * Copyright 2017 the original author or 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.gradle.kotlin.dsl.provider import org.gradle.api.internal.ClassPathRegistry import org.gradle.api.internal.artifacts.dsl.dependencies.DependencyFactory import org.gradle.api.internal.classpath.ModuleRegistry import org.gradle.cache.internal.GeneratedGradleJarCache import org.gradle.groovy.scripts.internal.ScriptSourceHasher import org.gradle.initialization.ClassLoaderScopeRegistry import org.gradle.internal.classloader.ClasspathHasher import org.gradle.internal.logging.progress.ProgressLoggerFactory import org.gradle.internal.operations.BuildOperationExecutor import org.gradle.kotlin.dsl.cache.ScriptCache import org.gradle.kotlin.dsl.support.EmbeddedKotlinProvider import org.gradle.kotlin.dsl.support.ImplicitImports import org.gradle.plugin.management.internal.autoapply.AutoAppliedPluginHandler import org.gradle.plugin.use.internal.PluginRequestApplicator internal object BuildServices { @Suppress("unused") fun createKotlinScriptClassPathProvider( moduleRegistry: ModuleRegistry, classPathRegistry: ClassPathRegistry, classLoaderScopeRegistry: ClassLoaderScopeRegistry, dependencyFactory: DependencyFactory, jarCache: GeneratedGradleJarCache, progressLoggerFactory: ProgressLoggerFactory ) = KotlinScriptClassPathProvider( moduleRegistry, classPathRegistry, classLoaderScopeRegistry.coreAndPluginsScope, gradleApiJarsProviderFor(dependencyFactory), versionedJarCacheFor(jarCache), StandardJarGenerationProgressMonitorProvider(progressLoggerFactory)) @Suppress("unused") fun createPluginRequestsHandler( pluginRequestApplicator: PluginRequestApplicator, autoAppliedPluginHandler: AutoAppliedPluginHandler ) = PluginRequestsHandler(pluginRequestApplicator, autoAppliedPluginHandler) @Suppress("unused") fun createClassPathModeExceptionCollector() = ClassPathModeExceptionCollector() @Suppress("unused") fun createKotlinScriptEvaluator( classPathProvider: KotlinScriptClassPathProvider, classloadingCache: KotlinScriptClassloadingCache, pluginRequestsHandler: PluginRequestsHandler, pluginRequestApplicator: PluginRequestApplicator, embeddedKotlinProvider: EmbeddedKotlinProvider, classPathModeExceptionCollector: ClassPathModeExceptionCollector, kotlinScriptBasePluginsApplicator: KotlinScriptBasePluginsApplicator, scriptSourceHasher: ScriptSourceHasher, classPathHasher: ClasspathHasher, scriptCache: ScriptCache, implicitImports: ImplicitImports, progressLoggerFactory: ProgressLoggerFactory, buildOperationExecutor: BuildOperationExecutor ): KotlinScriptEvaluator = StandardKotlinScriptEvaluator( classPathProvider, classloadingCache, pluginRequestApplicator, pluginRequestsHandler, embeddedKotlinProvider, classPathModeExceptionCollector, kotlinScriptBasePluginsApplicator, scriptSourceHasher, classPathHasher, scriptCache, implicitImports, progressLoggerFactory, buildOperationExecutor) private fun versionedJarCacheFor(jarCache: GeneratedGradleJarCache): JarCache = { id, creator -> jarCache[id, creator] } }
apache-2.0
79ca81c4c302d5bcdeb4c1a1b00a33fe
35.927273
80
0.755539
5.729196
false
false
false
false
nestlabs/connectedhomeip
src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/clusterclient/BasicClientFragment.kt
2
18963
package com.google.chip.chiptool.clusterclient import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.ArrayAdapter import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import chip.devicecontroller.ChipClusters import chip.devicecontroller.ChipClusters.BasicCluster import chip.devicecontroller.ChipDeviceController import com.google.chip.chiptool.ChipClient import com.google.chip.chiptool.GenericChipDeviceListener import com.google.chip.chiptool.R import kotlinx.android.synthetic.main.basic_client_fragment.attributeNameSpinner import kotlinx.android.synthetic.main.basic_client_fragment.basicClusterCommandStatus import kotlinx.android.synthetic.main.basic_client_fragment.locationEd import kotlinx.android.synthetic.main.basic_client_fragment.nodeLabelEd import kotlinx.android.synthetic.main.basic_client_fragment.view.attributeNameSpinner import kotlinx.android.synthetic.main.basic_client_fragment.view.readAttributeBtn import kotlinx.android.synthetic.main.basic_client_fragment.view.writeLocalConfigDisabledSwitch import kotlinx.android.synthetic.main.basic_client_fragment.view.writeLocationBtn import kotlinx.android.synthetic.main.basic_client_fragment.view.writeNodeLabelBtn import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch class BasicClientFragment : Fragment() { private val deviceController: ChipDeviceController get() = ChipClient.getDeviceController(requireContext()) private lateinit var scope: CoroutineScope private lateinit var addressUpdateFragment: AddressUpdateFragment override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { scope = viewLifecycleOwner.lifecycleScope return inflater.inflate(R.layout.basic_client_fragment, container, false).apply { deviceController.setCompletionListener(ChipControllerCallback()) addressUpdateFragment = childFragmentManager.findFragmentById(R.id.addressUpdateFragment) as AddressUpdateFragment writeNodeLabelBtn.setOnClickListener { scope.launch { sendWriteNodeLabelAttribute() nodeLabelEd.onEditorAction(EditorInfo.IME_ACTION_DONE) }} writeLocationBtn.setOnClickListener { scope.launch { sendWriteLocationAttribute() locationEd.onEditorAction(EditorInfo.IME_ACTION_DONE) }} writeLocalConfigDisabledSwitch.setOnCheckedChangeListener { _, isChecked -> scope.launch { sendWriteLocalConfigDisabledAttribute(isChecked) } } makeAttributeList() attributeNameSpinner.adapter = makeAttributeNamesAdapter() readAttributeBtn.setOnClickListener { scope.launch { readAttributeButtonClick() }} } } inner class ChipControllerCallback : GenericChipDeviceListener() { override fun onConnectDeviceComplete() {} override fun onCommissioningComplete(nodeId: Long, errorCode: Int) { Log.d(TAG, "onCommissioningComplete for nodeId $nodeId: $errorCode") } override fun onNotifyChipConnectionClosed() { Log.d(TAG, "onNotifyChipConnectionClosed") } override fun onCloseBleComplete() { Log.d(TAG, "onCloseBleComplete") } override fun onError(error: Throwable?) { Log.d(TAG, "onError: $error") } } private fun makeAttributeNamesAdapter(): ArrayAdapter<String> { return ArrayAdapter( requireContext(), android.R.layout.simple_spinner_dropdown_item, ATTRIBUTES.toList() ).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } } private suspend fun readAttributeButtonClick() { try { readBasicClusters(attributeNameSpinner.selectedItemPosition) } catch (ex: Exception) { showMessage("readBasicCluster failed: $ex") } } private suspend fun readBasicClusters(itemIndex: Int) { when(ATTRIBUTES[itemIndex]) { getString(R.string.basic_cluster_data_model_revision_text) -> sendReadDataModelRevisionAttribute() getString(R.string.basic_cluster_vendor_name_text) -> sendReadVendorNameAttribute() getString(R.string.basic_cluster_vendor_id_text) -> sendReadVendorIDAttribute() getString(R.string.basic_cluster_product_name_text) -> sendReadProductNameAttribute() getString(R.string.basic_cluster_product_id_text) -> sendReadProductIDAttribute() getString(R.string.basic_cluster_node_label_text) -> sendReadNodeLabelAttribute() getString(R.string.basic_cluster_location_text) -> sendReadLocationAttribute() getString(R.string.basic_cluster_hardware_version_text) -> sendReadHardwareVersionAttribute() getString(R.string.basic_cluster_hardware_version_string_text) -> sendReadHardwareVersionStringAttribute() getString(R.string.basic_cluster_software_version_text) -> sendReadSoftwareVersionAttribute() getString(R.string.basic_cluster_software_version_string_text) -> sendReadSoftwareVersionStringAttribute() getString(R.string.basic_cluster_manufacturing_date_text) -> sendReadManufacturingDateAttribute() getString(R.string.basic_cluster_part_number_text) -> sendReadPartNumberAttribute() getString(R.string.basic_cluster_product_url_text) -> sendReadProductURLAttribute() getString(R.string.basic_cluster_product_label_text) -> sendReadProductLabelAttribute() getString(R.string.basic_cluster_serial_number_text) -> sendReadSerialNumberAttribute() getString(R.string.basic_cluster_local_config_disabled_text) -> sendReadLocalConfigDisabledAttribute() getString(R.string.basic_cluster_reachable_text) -> sendReadReachableAttribute() getString(R.string.basic_cluster_cluster_revision_text) -> sendReadClusterRevisionAttribute() } } private fun makeAttributeList() { ATTRIBUTES.add(getString(R.string.basic_cluster_data_model_revision_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_vendor_name_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_vendor_id_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_product_name_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_product_id_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_node_label_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_location_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_hardware_version_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_hardware_version_string_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_software_version_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_software_version_string_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_manufacturing_date_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_part_number_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_product_url_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_product_label_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_serial_number_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_local_config_disabled_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_reachable_text)) ATTRIBUTES.add(getString(R.string.basic_cluster_cluster_revision_text)) } private suspend fun sendReadDataModelRevisionAttribute() { getBasicClusterForDevice().readDataModelRevisionAttribute(object : ChipClusters.IntegerAttributeCallback { override fun onSuccess(value: Int) { Log.i(TAG,"[Read Success] DataModelRevision: $value") showMessage("[Read Success] DataModelRevision: $value") } override fun onError(ex: Exception) { showMessage("Read DataModelRevision failure $ex") Log.e(TAG, "Read DataModelRevision failure", ex) } }) } private suspend fun sendReadVendorNameAttribute() { getBasicClusterForDevice().readVendorNameAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] VendorName: $value") showMessage("[Read Success] VendorName: $value") } override fun onError(ex: Exception) { showMessage("Read VendorName failure $ex") Log.e(TAG, "Read VendorName failure", ex) } }) } private suspend fun sendReadVendorIDAttribute() { getBasicClusterForDevice().readVendorIDAttribute(object : ChipClusters.BasicCluster.VendorIDAttributeCallback { override fun onSuccess(value: Int) { Log.i(TAG,"[Read Success] VendorID: $value") showMessage("[Read Success] VendorID: $value") } override fun onError(ex: Exception) { showMessage("Read VendorID failure $ex") Log.e(TAG, "Read VendorID failure", ex) } }) } private suspend fun sendReadProductNameAttribute() { getBasicClusterForDevice().readProductNameAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] ProductName: $value") showMessage("[Read Success] ProductName: $value") } override fun onError(ex: Exception) { showMessage("Read ProductName failure $ex") Log.e(TAG, "Read ProductName failure", ex) } }) } private suspend fun sendReadProductIDAttribute() { getBasicClusterForDevice().readProductIDAttribute(object : ChipClusters.IntegerAttributeCallback { override fun onSuccess(value: Int) { Log.i(TAG,"[Read Success] ProductID: $value") showMessage("[Read Success] ProductID: $value") } override fun onError(ex: Exception) { showMessage("Read ProductID failure $ex") Log.e(TAG, "Read ProductID failure", ex) } }) } private suspend fun sendReadNodeLabelAttribute() { getBasicClusterForDevice().readNodeLabelAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] NodeLabel: $value") showMessage("[Read Success] NodeLabel: $value") } override fun onError(ex: Exception) { showMessage("Read NodeLabel failure $ex") Log.e(TAG, "Read NodeLabel failure", ex) } }) } private suspend fun sendWriteNodeLabelAttribute() { getBasicClusterForDevice().writeNodeLabelAttribute(object : ChipClusters.DefaultClusterCallback { override fun onSuccess() { showMessage("Write NodeLabel success") } override fun onError(ex: Exception) { showMessage("Write NodeLabel failure $ex") Log.e(TAG, "Write NodeLabel failure", ex) } }, nodeLabelEd.text.toString()) } private suspend fun sendReadLocationAttribute() { getBasicClusterForDevice().readLocationAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] Location: $value") showMessage("[Read Success] Location: $value") } override fun onError(ex: Exception) { showMessage("Read Location failure $ex") Log.e(TAG, "Read Location failure", ex) } }) } private suspend fun sendWriteLocationAttribute() { getBasicClusterForDevice().writeLocationAttribute(object : ChipClusters.DefaultClusterCallback { override fun onSuccess() { showMessage("Write Location success") } override fun onError(ex: Exception) { showMessage("Write Location failure $ex") Log.e(TAG, "Write Location failure", ex) } }, locationEd.text.toString()) } private suspend fun sendReadHardwareVersionAttribute() { getBasicClusterForDevice().readHardwareVersionAttribute(object : ChipClusters.IntegerAttributeCallback { override fun onSuccess(value: Int) { Log.i(TAG,"[Read Success] HardwareVersion: $value") showMessage("[Read Success] HardwareVersion: $value") } override fun onError(ex: Exception) { showMessage("Read HardwareVersion failure $ex") Log.e(TAG, "Read HardwareVersion failure", ex) } }) } private suspend fun sendReadHardwareVersionStringAttribute() { getBasicClusterForDevice().readHardwareVersionStringAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] HardwareVersionString: $value") showMessage("[Read Success] HardwareVersionString: $value") } override fun onError(ex: Exception) { showMessage("Read HardwareVersionString failure $ex") Log.e(TAG, "Read HardwareVersionString failure", ex) } }) } private suspend fun sendReadSoftwareVersionAttribute() { getBasicClusterForDevice().readSoftwareVersionAttribute(object : ChipClusters.LongAttributeCallback { override fun onSuccess(value: Long) { Log.i(TAG,"[Read Success] SoftwareVersion: $value") showMessage("[Read Success] SoftwareVersion: $value") } override fun onError(ex: Exception) { showMessage("Read SoftwareVersion failure $ex") Log.e(TAG, "Read SoftwareVersion failure", ex) } }) } private suspend fun sendReadSoftwareVersionStringAttribute() { getBasicClusterForDevice().readSoftwareVersionStringAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] SoftwareVersionString $value") showMessage("[Read Success] SoftwareVersionString: $value") } override fun onError(ex: Exception) { showMessage("Read SoftwareVersionString failure $ex") Log.e(TAG, "Read SoftwareVersionString failure", ex) } }) } private suspend fun sendReadManufacturingDateAttribute() { getBasicClusterForDevice().readManufacturingDateAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] ManufacturingDate $value") showMessage("[Read Success] ManufacturingDate: $value") } override fun onError(ex: Exception) { showMessage("Read ManufacturingDate failure $ex") Log.e(TAG, "Read ManufacturingDate failure", ex) } }) } private suspend fun sendReadPartNumberAttribute() { getBasicClusterForDevice().readPartNumberAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] PartNumber $value") showMessage("[Read Success] PartNumber: $value") } override fun onError(ex: Exception) { showMessage("Read PartNumber failure $ex") Log.e(TAG, "Read PartNumber failure", ex) } }) } private suspend fun sendReadProductURLAttribute() { getBasicClusterForDevice().readProductURLAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] ProductURL $value") showMessage("[Read Success] ProductURL: $value") } override fun onError(ex: Exception) { showMessage("Read ProductURL failure $ex") Log.e(TAG, "Read ProductURL failure", ex) } }) } private suspend fun sendReadProductLabelAttribute() { getBasicClusterForDevice().readProductLabelAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] ProductLabel $value") showMessage("[Read Success] ProductLabel: $value") } override fun onError(ex: Exception) { showMessage("Read ProductLabel failure $ex") Log.e(TAG, "Read ProductLabel failure", ex) } }) } private suspend fun sendReadSerialNumberAttribute() { getBasicClusterForDevice().readSerialNumberAttribute(object : ChipClusters.CharStringAttributeCallback { override fun onSuccess(value: String) { Log.i(TAG,"[Read Success] SerialNumber $value") showMessage("[Read Success] SerialNumber: $value") } override fun onError(ex: Exception) { showMessage("Read SerialNumber failure $ex") Log.e(TAG, "Read SerialNumber failure", ex) } }) } private suspend fun sendReadLocalConfigDisabledAttribute() { getBasicClusterForDevice().readLocalConfigDisabledAttribute(object : ChipClusters.BooleanAttributeCallback { override fun onSuccess(value: Boolean) { Log.i(TAG,"[Read Success] LocalConfigDisabled $value") showMessage("[Read Success] LocalConfigDisabled: $value") } override fun onError(ex: Exception) { showMessage("Read LocalConfigDisabled failure $ex") Log.e(TAG, "Read LocalConfigDisabled failure", ex) } }) } private suspend fun sendWriteLocalConfigDisabledAttribute(localConfigDisabled: Boolean) { getBasicClusterForDevice().writeLocalConfigDisabledAttribute(object : ChipClusters.DefaultClusterCallback { override fun onSuccess() { showMessage("Write LocalConfigDisabled success") } override fun onError(ex: Exception) { showMessage("Write LocalConfigDisabled failure $ex") Log.e(TAG, "Write LocalConfigDisabled failure", ex) } }, localConfigDisabled) } private suspend fun sendReadReachableAttribute() { getBasicClusterForDevice().readReachableAttribute(object : ChipClusters.BooleanAttributeCallback { override fun onSuccess(value: Boolean) { Log.i(TAG,"[Read Success] Reachable $value") showMessage("[Read Success] Reachable: $value") } override fun onError(ex: Exception) { showMessage("Read Reachable failure $ex") Log.e(TAG, "Read Reachable failure", ex) } }) } private suspend fun sendReadClusterRevisionAttribute() { getBasicClusterForDevice().readClusterRevisionAttribute(object : ChipClusters.IntegerAttributeCallback { override fun onSuccess(value: Int) { Log.i(TAG,"[Read Success] ClusterRevision $value") showMessage("[Read Success] ClusterRevision: $value") } override fun onError(ex: Exception) { showMessage("Read ClusterRevision failure $ex") Log.e(TAG, "Read ClusterRevision failure", ex) } }) } private fun showMessage(msg: String) { requireActivity().runOnUiThread { basicClusterCommandStatus.text = msg } } private suspend fun getBasicClusterForDevice(): BasicCluster { return BasicCluster( ChipClient.getConnectedDevicePointer(requireContext(), addressUpdateFragment.deviceId), ENDPOINT ) } companion object { private const val TAG = "BasicClientFragment" private const val ENDPOINT = 0 private val ATTRIBUTES: MutableList<String> = mutableListOf() fun newInstance(): BasicClientFragment = BasicClientFragment() } }
apache-2.0
345025cfb0b812412883fbed0111b52e
38.754717
117
0.721827
4.741935
false
false
false
false
JayNewstrom/ScreenSwitcher
dialog-manager/src/main/java/com/jaynewstrom/screenswitcher/dialogmanager/DialogManager.kt
1
6703
package com.jaynewstrom.screenswitcher.dialogmanager import android.app.Activity import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.View import com.jaynewstrom.concrete.Concrete import com.jaynewstrom.concrete.ConcreteWall import com.jaynewstrom.screenswitcher.Screen import com.jaynewstrom.screenswitcher.ScreenLifecycleListener import com.jaynewstrom.screenswitcher.ScreenSwitcher import com.jaynewstrom.screenswitcher.ScreenSwitcherData import com.jaynewstrom.screenswitcher.ScreenSwitcherState import com.jaynewstrom.screenswitcher.screenSwitcherDataIfActive import com.jaynewstrom.screenswitcher.screenmanager.CompositeScreenLifecycleListener import com.jaynewstrom.screenswitcher.setupForViewExtensions import java.lang.ref.WeakReference class DialogManager(compositeScreenLifecycleListener: CompositeScreenLifecycleListener) { private var dialogInformationList: MutableList<DialogInformation> = mutableListOf() private var savedDialogFactories: List<SavedDialogFactory>? = null private var activity: Activity? = null init { compositeScreenLifecycleListener.register(RemoveDialogInformationListener()) } fun attachActivity(activity: Activity) { this.activity = activity } fun dropActivity(activity: Activity) { if (this.activity === activity) { this.activity = null } } internal fun show(dialogFactory: DialogFactory, screen: Screen? = null, savedState: Bundle? = null) { val activity = activity ?: throw IllegalStateException("DialogManager is not attached to the activity.") val dialog = dialogFactory.createDialog(activity) if (savedState != null) { dialog.onRestoreInstanceState(savedState) } else { dialog.show() } dialogInformationList.add(DialogInformation(dialog, dialogFactory, screen)) } fun saveState() { val items = mutableListOf<SavedDialogFactory>() for (information in dialogInformationList) { val dialog: Dialog? = information.dialogWeakReference.get() if (dialog != null && dialog.isShowing) { items.add( SavedDialogFactory(information.dialogFactory, dialog.onSaveInstanceState(), information.screen) ) dialog.dismiss() } } dialogInformationList = mutableListOf() savedDialogFactories = items } fun restoreState() { val savedDialogFactories = savedDialogFactories ?: return dialogInformationList = mutableListOf() for (savedDialogFactory in savedDialogFactories) { show(savedDialogFactory.dialogFactory, savedDialogFactory.screen, savedDialogFactory.savedState) } this.savedDialogFactories = null } private class DialogInformation(dialog: Dialog, val dialogFactory: DialogFactory, val screen: Screen?) { val dialogWeakReference: WeakReference<Dialog> = WeakReference(dialog) } private class SavedDialogFactory(val dialogFactory: DialogFactory, val savedState: Bundle, val screen: Screen?) private inner class RemoveDialogInformationListener : ScreenLifecycleListener { override fun onScreenAdded(screen: Screen) {} override fun onScreenBecameActive(screen: Screen) {} override fun onScreenBecameInactive(screen: Screen) {} override fun onScreenRemoved(screen: Screen) { for (dialogInformation in ArrayList(dialogInformationList)) { if (dialogInformation.screen == screen) { val dialog = dialogInformation.dialogWeakReference.get() if (dialog != null && dialog.isShowing) { dialog.dismiss() } dialogInformationList.remove(dialogInformation) } } } } } /** * Returns the dialogDisplayer if this view is associated with the current screen. Null otherwise. */ fun View.dialogDisplayer(): DialogDisplayer? { val screenSwitcherData = screenSwitcherDataIfActive() ?: return null val dialogManager = Concrete.getComponent<DialogManagerComponent>(context).dialogManager val wall = Concrete.findWall<ConcreteWall<*>>(context) return DialogDisplayer( screenSwitcherData, wall, dialogManager ) } class DialogDisplayer internal constructor( screenSwitcherData: ScreenSwitcherData, private val wall: ConcreteWall<*>, private val dialogManager: DialogManager ) : ScreenSwitcherState.ScreenSwitcherCreatedListener { private val screen: Screen = screenSwitcherData.screen private val screenSwitcherState: ScreenSwitcherState = screenSwitcherData.screenSwitcherState private var screenSwitcher: ScreenSwitcher? = null private var parentViewForViewExtensionSetup: View? = null init { screenSwitcherData.screenSwitcherState.registerScreenSwitcherCreatedListener(screen, this) screenSwitcher = screenSwitcherData.screenSwitcher } fun show(dialogFactory: DialogFactory) { dialogManager.show(WrapperDialogFactory(dialogFactory), screen) } private inner class WrapperDialogFactory(private val dialogFactory: DialogFactory) : DialogFactory { override fun createDialog(context: Context): Dialog { val dialog = dialogFactory.createDialog(wall.createContext(context)) val contentView = dialog.findViewById<View>(android.R.id.content) contentView.addOnAttachStateChangeListener( object : View.OnAttachStateChangeListener { override fun onViewDetachedFromWindow(v: View) { screenSwitcher = null parentViewForViewExtensionSetup = null } override fun onViewAttachedToWindow(v: View) { } } ) contentView.setTag(R.id.screen_switcher_screen, screen) val parent = contentView.parent as View val localScreenSwitcher = screenSwitcher if (localScreenSwitcher == null) { parentViewForViewExtensionSetup = parent } else { parent.setupForViewExtensions(localScreenSwitcher, screenSwitcherState) } return dialog } } override fun screenSwitcherCreated(screenSwitcher: ScreenSwitcher) { this.screenSwitcher = screenSwitcher parentViewForViewExtensionSetup?.setupForViewExtensions(screenSwitcher, screenSwitcherState) parentViewForViewExtensionSetup = null } }
apache-2.0
764742d79f3a87903298d6b2fb073018
39.379518
115
0.694764
5.952931
false
false
false
false
facebook/litho
litho-testing/src/main/java/com/facebook/litho/testing/componentsfinder/ComponentsFinder.kt
1
7891
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.componentsfinder import com.facebook.litho.Component import com.facebook.litho.LithoLayoutResult import com.facebook.litho.LithoNode import com.facebook.litho.LithoView import com.facebook.litho.NestedTreeHolderResult import com.facebook.litho.ScopedComponentInfo import kotlin.reflect.KClass /** * Returns the root component of the LithoView. * * example: * ``` * class FBStory : KComponent() { * override fun ComponentScope.render() { * return Story() * } * ``` * `findRootComponentInLithoView` will only be able to return `FBStory` component, from a LithoView * with FBStory as root. If you would like to be able to find the `Story` component, see * [findDirectComponentInLithoView] */ fun getRootComponentInLithoView(lithoView: LithoView): Component? { val internalNode = getLayoutRoot(lithoView)?.node ?: return null return if (internalNode.scopedComponentInfos.isNotEmpty()) internalNode.headComponent else null } /** * Returns a component of the given class only if the component renders directly to the root * component of the LithoView * * example: * ``` * class FBStory : KComponent() { * override fun ComponentScope.render() { * return Story() * } * ``` * * findDirectComponentInLithoView will only be able to return Story Component from the LithoView * with FBStory as a root * * ``` * class FBStory : KComponent() { * override fun ComponentScope.render() { * return Column{ * child(CommentComponent()) * child(AuthorComponent()) * } * } * findDirectComponentInLithoView here will only be able to return Column * ``` */ fun findDirectComponentInLithoView(lithoView: LithoView, clazz: Class<out Component?>): Component? { val internalNode = getLayoutRoot(lithoView)?.node ?: return null return getOrderedScopedComponentInfos(internalNode) .map { it.component } .firstOrNull { it.javaClass == clazz } } /** * Returns a component of the given class only if the component renders directly to the root * component of the LithoView (for details see: [findDirectComponentInLithoView]) */ fun findDirectComponentInLithoView(lithoView: LithoView, clazz: KClass<out Component>): Component? { return findDirectComponentInLithoView(lithoView, clazz.java) } /** Returns a component of the given class from the ComponentTree or null if not found */ fun findComponentInLithoView(lithoView: LithoView, clazz: Class<out Component?>): Component? { val layoutRoot = getLayoutRoot(lithoView) ?: return null return findComponentViaBreadthFirst(clazz, layoutRoot) } /** Returns a component of the given class from the ComponentTree or null if not found */ fun findComponentInLithoView(lithoView: LithoView, clazz: KClass<out Component>): Component? { return findComponentInLithoView(lithoView, clazz.java) } fun findAllDirectComponentsInLithoView( lithoView: LithoView, clazz: KClass<out Component> ): List<Component> { return findAllDirectComponentsInLithoView(lithoView, clazz.java) } fun findAllDirectComponentsInLithoView( lithoView: LithoView, clazz: Class<out Component> ): List<Component> { val internalNode = getLayoutRoot(lithoView)?.node ?: return emptyList() return getOrderedScopedComponentInfos(internalNode) .map { it.component } .filter { it.javaClass == clazz } } /** * Returns a list of all components of the given classes from the ComponentTree or an empty list if * not found */ fun findAllComponentsInLithoView( lithoView: LithoView, vararg clazz: Class<out Component?> ): List<Component> { val layoutResult = getLayoutRoot(lithoView) ?: return emptyList() return findAllComponentsViaBreadthFirstSearch(clazz, layoutResult) } /** * Returns a list of all components of the given classes from the ComponentTree or an empty list if * not found */ fun findAllComponentsInLithoView( lithoView: LithoView, vararg clazz: KClass<out Component> ): List<Component> { val javaClasses = Array(clazz.size) { i -> clazz[i].java } return findAllComponentsInLithoView(lithoView, *javaClasses) } private fun getLayoutRoot(lithoView: LithoView): LithoLayoutResult? { val commitedLayoutState = lithoView.componentTree?.committedLayoutState ?: throw IllegalStateException( "No ComponentTree/Committed Layout/Layout Root found. Please call render() first") return commitedLayoutState.rootLayoutResult } /** * Goes through nodes in a component tree via breadth first search. Returns a component of a given * class or null if not found */ private fun findComponentViaBreadthFirst( clazz: Class<out Component?>, layoutResult: LithoLayoutResult? ): Component? { componentBreadthFirstSearch(layoutResult) { scopedComponents -> val foundComponent = scopedComponents.firstOrNull { it.javaClass == clazz } if (foundComponent != null) { return foundComponent } } return null } /** * Goes through nodes in a component tree via breadth first search. Returns all components that * match the given classes or an empty list if none found */ private fun findAllComponentsViaBreadthFirstSearch( clazzArray: Array<out Class<out Component?>>, layoutResult: LithoLayoutResult?, ): List<Component> { val foundComponentsList = mutableListOf<Component>() componentBreadthFirstSearch(layoutResult) { scopedComponents -> val foundComponents = scopedComponents.filter { it.javaClass in clazzArray } foundComponentsList.addAll(foundComponents) } return foundComponentsList } /** * Internal function to handle BFS through a set of components. * * @param onHandleScopedComponents lambda which handles the scoped components of the particular * layout. This enables the caller of the function to properly handle if any of those components * match. (For example, if looking for a single component, you would want to return in the lambda if * it matches. If looking for multiple, you would simply want to add all matching components to a * list.) */ private inline fun componentBreadthFirstSearch( startingLayoutResult: LithoLayoutResult?, onHandleScopedComponents: (List<Component>) -> Unit ) { startingLayoutResult ?: return val enqueuedLayouts = mutableSetOf<LithoLayoutResult>(startingLayoutResult) val layoutsQueue = ArrayDeque(enqueuedLayouts) while (layoutsQueue.isNotEmpty()) { val currentLayoutResult = layoutsQueue.removeFirst() val internalNode = currentLayoutResult.node onHandleScopedComponents(getOrderedScopedComponentInfos(internalNode).map { it.component }) if (currentLayoutResult is NestedTreeHolderResult) { val nestedLayout = currentLayoutResult.nestedResult?.takeUnless { it in enqueuedLayouts } ?: continue layoutsQueue.add(nestedLayout) continue } for (i in 0 until internalNode.childCount) { val childLayout = currentLayoutResult.getChildAt(i).takeUnless { it in enqueuedLayouts } ?: continue layoutsQueue.add(childLayout) } } } /** * @return list of the [ScopedComponentInfo]s, ordered from the head (closest to the root) to the * tail. */ private fun getOrderedScopedComponentInfos(internalNode: LithoNode): List<ScopedComponentInfo> { return internalNode.scopedComponentInfos.reversed() }
apache-2.0
baec6f5d3181eabcf9433401918600c1
33.609649
100
0.750982
4.652712
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
example/src/test/java/org/wordpress/android/fluxc/wc/refunds/RefundStoreTest.kt
1
5001
package org.wordpress.android.fluxc.wc.refunds import com.yarolegovich.wellsql.WellSql import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import org.wordpress.android.fluxc.SingleStoreWellSqlConfigForTests import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.refunds.RefundMapper import org.wordpress.android.fluxc.model.refunds.WCRefundModel import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NOT_FOUND import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.INVALID_ID import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult import org.wordpress.android.fluxc.network.rest.wpcom.wc.refunds.RefundRestClient import org.wordpress.android.fluxc.persistence.WCRefundSqlUtils import org.wordpress.android.fluxc.persistence.WellSqlConfig import org.wordpress.android.fluxc.store.WCRefundStore import org.wordpress.android.fluxc.test import org.wordpress.android.fluxc.tools.initCoroutineEngine @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner::class) class RefundStoreTest { private val restClient = mock<RefundRestClient>() private val site = mock<SiteModel>() private val mapper = RefundMapper() private lateinit var store: WCRefundStore private val orderId = 1L private val refundId = REFUND_RESPONSE.refundId private val error = WooError(INVALID_ID, NOT_FOUND, "Invalid order ID") @Before fun setUp() { val appContext = RuntimeEnvironment.application.applicationContext val config = SingleStoreWellSqlConfigForTests( appContext, listOf(WCRefundSqlUtils.RefundBuilder::class.java), WellSqlConfig.ADDON_WOOCOMMERCE ) WellSql.init(config) config.reset() store = WCRefundStore( restClient, initCoroutineEngine(), mapper ) } @Test fun `fetch all refunds of an order`() = test { val data = arrayOf(REFUND_RESPONSE, REFUND_RESPONSE) val result = fetchAllTestRefunds() assertThat(result.model?.size).isEqualTo(data.size) assertThat(result.model?.first()).isEqualTo(mapper.map(data.first())) val invalidRequestResult = store.fetchAllRefunds(site, 2) assertThat(invalidRequestResult.model).isNull() assertThat(invalidRequestResult.error).isEqualTo(error) } @Test fun `get all refunds of an order`() = test { fetchAllTestRefunds() val refunds = store.getAllRefunds(site, orderId) assertThat(refunds.size).isEqualTo(1) assertThat(refunds.first()).isEqualTo(mapper.map(REFUND_RESPONSE)) val invalidRequestResult = store.getAllRefunds(site, 2) assertThat(invalidRequestResult.size).isEqualTo(0) } @Test fun `fetch specific refund`() = test { val refund = fetchSpecificTestRefund() assertThat(refund.model).isEqualTo(mapper.map(REFUND_RESPONSE)) } @Test fun `get specific refund`() = test { fetchSpecificTestRefund() val refund = store.getRefund(site, orderId, refundId) assertThat(refund).isEqualTo(mapper.map(REFUND_RESPONSE)) } private suspend fun fetchSpecificTestRefund(): WooResult<WCRefundModel> { val fetchRefundsPayload = WooPayload( REFUND_RESPONSE ) whenever(restClient.fetchRefund(site, orderId, refundId)).thenReturn( fetchRefundsPayload ) whenever(restClient.fetchRefund(site, 2, refundId)).thenReturn( WooPayload(error) ) return store.fetchRefund(site, orderId, refundId) } private suspend fun fetchAllTestRefunds(): WooResult<List<WCRefundModel>> { val data = arrayOf(REFUND_RESPONSE, REFUND_RESPONSE) val fetchRefundsPayload = WooPayload( data ) whenever( restClient.fetchAllRefunds( site, orderId, WCRefundStore.DEFAULT_PAGE, WCRefundStore.DEFAULT_PAGE_SIZE ) ).thenReturn( fetchRefundsPayload ) whenever( restClient.fetchAllRefunds( site, 2, WCRefundStore.DEFAULT_PAGE, WCRefundStore.DEFAULT_PAGE_SIZE ) ).thenReturn( WooPayload(error) ) return store.fetchAllRefunds(site, orderId) } }
gpl-2.0
f5313e3aef35b0761e8dec6acdf986ac
34.468085
81
0.673665
4.799424
false
true
false
false
Kotlin/dokka
core/src/main/kotlin/model/properties/PropertyContainer.kt
1
2769
package org.jetbrains.dokka.model.properties data class PropertyContainer<C : Any> internal constructor( @PublishedApi internal val map: Map<ExtraProperty.Key<C, *>, ExtraProperty<C>> ) { operator fun <D : C> plus(prop: ExtraProperty<D>): PropertyContainer<D> = PropertyContainer(map + (prop.key to prop)) // TODO: Add logic for caching calculated properties inline operator fun <reified T : Any> get(key: ExtraProperty.Key<C, T>): T? = when (val prop = map[key]) { is T? -> prop else -> throw ClassCastException("Property for $key stored under not matching key type.") } inline fun <reified T : Any> allOfType(): List<T> = map.values.filterIsInstance<T>() fun <D : C> addAll(extras: Collection<ExtraProperty<D>>): PropertyContainer<D> = PropertyContainer(map + extras.map { p -> p.key to p }) operator fun <D : C> minus(prop: ExtraProperty.Key<C, *>): PropertyContainer<D> = PropertyContainer(map.filterNot { it.key == prop }) companion object { fun <T : Any> empty(): PropertyContainer<T> = PropertyContainer(emptyMap()) fun <T : Any> withAll(vararg extras: ExtraProperty<T>?) = empty<T>().addAll(extras.filterNotNull()) fun <T : Any> withAll(extras: Collection<ExtraProperty<T>>) = empty<T>().addAll(extras) } } operator fun <D: Any> PropertyContainer<D>.plus(prop: ExtraProperty<D>?): PropertyContainer<D> = if (prop == null) this else PropertyContainer(map + (prop.key to prop)) interface WithExtraProperties<C : Any> { val extra: PropertyContainer<C> fun withNewExtras(newExtras: PropertyContainer<C>): C } fun <C> C.mergeExtras(left: C, right: C): C where C : Any, C : WithExtraProperties<C> { val aggregatedExtras: List<List<ExtraProperty<C>>> = (left.extra.map.values + right.extra.map.values) .groupBy { it.key } .values .map { it.distinct() } val (unambiguous, toMerge) = aggregatedExtras.partition { it.size == 1 } @Suppress("UNCHECKED_CAST") val strategies: List<MergeStrategy<C>> = toMerge.map { (l, r) -> (l.key as ExtraProperty.Key<C, ExtraProperty<C>>).mergeStrategyFor(l, r) } strategies.filterIsInstance<MergeStrategy.Fail>().firstOrNull()?.error?.invoke() val replaces: List<ExtraProperty<C>> = strategies.filterIsInstance<MergeStrategy.Replace<C>>().map { it.newProperty } val needingFullMerge: List<(preMerged: C, left: C, right: C) -> C> = strategies.filterIsInstance<MergeStrategy.Full<C>>().map { it.merger } val newExtras = PropertyContainer((unambiguous.flatten() + replaces).associateBy { it.key }) return needingFullMerge.fold(withNewExtras(newExtras)) { acc, merger -> merger(acc, left, right) } }
apache-2.0
77630970aa985af31bd8173c6f7ad5c9
42.265625
110
0.666306
3.9
false
false
false
false
Shynixn/BlockBall
blockball-bukkit-plugin/src/main/java/com/github/shynixn/blockball/bukkit/logic/business/service/BungeeCordConnectionServiceImpl.kt
1
3974
@file:Suppress("UNCHECKED_CAST", "UnstableApiUsage") package com.github.shynixn.blockball.bukkit.logic.business.service import com.github.shynixn.blockball.api.business.service.BungeeCordConnectionService import com.github.shynixn.blockball.api.business.service.BungeeCordService import com.github.shynixn.blockball.api.business.service.PersistenceLinkSignService import com.github.shynixn.blockball.bukkit.logic.business.extension.toLocation import com.github.shynixn.blockball.core.logic.business.extension.thenAcceptSafely import com.google.common.io.ByteArrayDataInput import com.google.common.io.ByteStreams import com.google.inject.Inject import org.bukkit.block.Sign import org.bukkit.entity.Player import org.bukkit.plugin.Plugin import org.bukkit.plugin.messaging.PluginMessageListener /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class BungeeCordConnectionServiceImpl @Inject constructor( private val plugin: Plugin, private val bungeeCordService: BungeeCordService, private val persistenceLinkSignService: PersistenceLinkSignService ) : BungeeCordConnectionService, PluginMessageListener { private var channelsRegistered = false /** * Restarts the channel listeners on this connection service. */ override fun restartChannelListeners() { if (channelsRegistered) { return } plugin.server.messenger.registerIncomingPluginChannel(plugin, "BungeeCord", this) bungeeCordService.restartConnectionHandling() channelsRegistered = true } /** * Gets called when a plugin message gets received. */ override fun onPluginMessageReceived(channel: String, player: Player, content: ByteArray) { if (channel != "BungeeCord") { return } val input: ByteArrayDataInput = ByteStreams.newDataInput(content) val type = input.readUTF() if (type != "ServerIP") { return } val serverName = input.readUTF() bungeeCordService.getServerSignLines(serverName, input.readUTF(), input.readShort().toInt()).thenAcceptSafely { lines -> updateSigns(serverName, lines) } } /** * Updates all signs of the given server. */ private fun updateSigns(serverName: String, lines: Array<String>) { val serverSigns = persistenceLinkSignService.getAll().filter { s -> s.server == serverName }.toList() for (sign in serverSigns) { val blockState = sign.position.toLocation().block.state if (blockState !is Sign) { persistenceLinkSignService.remove(sign) continue } for (i in 0..3) { blockState.setLine(i, lines[i]) } blockState.update() } } }
apache-2.0
53dd45e3791d88b84c7e51503ba25454
34.491071
128
0.706341
4.59422
false
false
false
false
jmesserli/discord-bernbot
discord-bot/src/main/kotlin/nu/peg/discord/service/internal/DefaultAuditService.kt
1
1340
package nu.peg.discord.service.internal import nu.peg.discord.audit.AuditEventEmbed import nu.peg.discord.config.DiscordProperties import nu.peg.discord.service.AuditService import nu.peg.discord.service.MessageSendService import nu.peg.discord.util.getLogger import org.springframework.stereotype.Service import sx.blah.discord.handle.obj.IChannel import java.awt.Color import javax.inject.Inject @Service class DefaultAuditService @Inject constructor( private val properties: DiscordProperties, private val messageSendService: MessageSendService, private val channelService: DefaultChannelService ) : AuditService { companion object { private val LOGGER = getLogger(DefaultAuditService::class) } private val auditChannel: IChannel? by lazy { if (properties.bot == null || properties.bot!!.auditChannel == null) null else channelService.findByName(properties.bot!!.auditChannel!!) } override fun log(message: String) { log(AuditEventEmbed(Color.BLACK, "Unnamed Audit Event", message)) } override fun log(eventEmbed: AuditEventEmbed) { if (auditChannel == null) { LOGGER.info("Audit channel could not be found, ignoring call to log") return } messageSendService.send(auditChannel!!, eventEmbed) } }
mit
6dc10b2cf5d1acbecfc3c52ed0652aaf
32.525
81
0.727612
4.407895
false
false
false
false
toastkidjp/Yobidashi_kt
todo/src/main/java/jp/toastkid/todo/model/Board.kt
2
638
/* * 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.todo.model import androidx.room.Entity import androidx.room.PrimaryKey /** * @author toastkidjp */ @Entity class Board( @PrimaryKey(autoGenerate = true) var id: Int ) { var name: String = "" var description: String = "" var created: Long = 0L var modified: Long = 0L }
epl-1.0
712b330466428e2619380d4dcf37c96b
20.3
88
0.695925
3.890244
false
false
false
false
cyrillrx/android_libraries
core/src/test/java/com/cyrillrx/utils/SerializerTest.kt
1
1783
package com.cyrillrx.utils import org.junit.Assert import org.junit.Test /** * @author Cyril Leroux * * Created 04/04/2017. */ class SerializerTest { data class DataObject(val key1: String, val key2: String) @Test fun serialize() { val data = DataObject("toto", "<tag />") val actual = data.serialize() val expected = """{"key1":"toto","key2":"\u003ctag /\u003e"}""" Assert.assertEquals(expected, actual) } @Test fun deserialize() { val serialized = """{"key1":"toto","key2":"\u003ctag /\u003e"}""" val data: DataObject = serialized.deserialize() Assert.assertEquals("toto", data.key1) Assert.assertEquals("<tag />", data.key2) val serialized2 = """{"key1":"toto","key2":"<tag />"}""" val data2: DataObject = serialized2.deserialize() Assert.assertEquals("toto", data2.key1) Assert.assertEquals("<tag />", data2.key2) } @Test fun serializeNoEscaping() { val data = DataObject("toto", "<tag />") val actual = data.serializeNoEscaping() val expected = """{"key1":"toto","key2":"<tag />"}""" Assert.assertEquals(expected, actual) } @Test fun deserializeNoEscaping() { val serialized = """{"key1":"toto","key2":"\u003ctag /\u003e"}""" val data: DataObject = serialized.deserializeNoEscaping() Assert.assertEquals("toto", data.key1) Assert.assertEquals("<tag />", data.key2) } @Test fun prettyPrint() { val data = DataObject("toto", "<tag />") val actual = data.prettyPrint() val expected = """{ "key1": "toto", "key2": "<tag />" }""" Assert.assertEquals(expected, actual) } }
mit
11dd71d764d9b4333b2b38c21651edac
21.871795
73
0.564778
3.962222
false
true
false
false
orbit/orbit
src/orbit-shared/src/main/kotlin/orbit/shared/net/Message.kt
1
1753
/* Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved. This file is part of the Orbit Project <https://www.orbit.cloud>. See license in LICENSE. */ package orbit.shared.net import orbit.shared.addressable.AddressableReference import orbit.shared.mesh.NodeId import orbit.shared.router.Route data class Message( val content: MessageContent, val messageId: Long? = null, val source: NodeId? = null, val target: MessageTarget? = null, val attempts: Long = 0 ) val Message.destination: String get() { return when (this.content) { is MessageContent.InvocationRequest -> this.content.destination.key.toString() is MessageContent.InvocationResponse -> this.target?.toString() ?: "" else -> "" } } enum class InvocationReason(val value: Int) { invocation(0), rerouted(1); companion object { fun fromInt(value: Int) = values().first { it.value == value } } } sealed class MessageTarget { data class Unicast(val targetNode: NodeId) : MessageTarget() data class RoutedUnicast(val route: Route) : MessageTarget() } sealed class MessageContent { data class Error(val description: String?) : MessageContent() object ConnectionInfoRequest : MessageContent() data class ConnectionInfoResponse(val nodeId: NodeId) : MessageContent() data class InvocationRequest( val destination: AddressableReference, val method: String, val arguments: String, val reason: InvocationReason = InvocationReason.invocation ) : MessageContent() data class InvocationResponse(val data: String) : MessageContent() data class InvocationResponseError(val description: String?, val platform: String?) : MessageContent() }
bsd-3-clause
33875b4355ce3f39e86469187344989e
30.321429
106
0.706788
4.371571
false
false
false
false
rei-m/android_hyakuninisshu
state/src/main/java/me/rei_m/hyakuninisshu/state/training/action/AggregateResultsAction.kt
1
1245
/* * Copyright (c) 2020. 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.hyakuninisshu.state.training.action import me.rei_m.hyakuninisshu.state.core.Action import me.rei_m.hyakuninisshu.state.training.model.TrainingResult /** * 練習の結果を集計するアクション. */ sealed class AggregateResultsAction(override val error: Throwable? = null) : Action { class Success(val trainingResult: TrainingResult) : AggregateResultsAction() { override fun toString() = "$name(trainingResult=$trainingResult)" } class Failure(e: Throwable) : AggregateResultsAction(e) { override fun toString() = "$name(error=$error)" } override val name = "AggregateResultsAction" }
apache-2.0
0d30e38703d3acac8043714c2a44523e
35.818182
112
0.739918
3.970588
false
false
false
false
rei-m/android_hyakuninisshu
domain/src/test/java/me/rei_m/hyakuninisshu/domain/karuta/model/KarutaImageNoTest.kt
1
1379
/* * Copyright (c) 2020. 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.hyakuninisshu.domain.karuta.model import org.assertj.core.api.Assertions.assertThat import org.junit.Test class KarutaImageNoTest { @Test fun createWith001() { val (value) = KarutaImageNo("001") assertThat(value).isEqualTo("001") } @Test fun createWith050() { val (value) = KarutaImageNo("050") assertThat(value).isEqualTo("050") } @Test fun createWith100() { val (value) = KarutaImageNo("100") assertThat(value).isEqualTo("100") } @Test(expected = IllegalArgumentException::class) fun createWith000() { KarutaImageNo("000") } @Test(expected = IllegalArgumentException::class) fun createWith101() { KarutaImageNo("101") } }
apache-2.0
79373bdfaa4947df98ecbe6d247d5239
26.039216
75
0.672951
4.191489
false
true
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/core/HttpTransaction.kt
1
826
package org.http4k.core import org.http4k.routing.RequestWithRoute import org.http4k.routing.ResponseWithRoute import java.time.Duration data class HttpTransaction( val request: Request, val response: Response, val duration: Duration, val labels: Map<String, String> = when { response is ResponseWithRoute -> mapOf(ROUTING_GROUP_LABEL to response.xUriTemplate.toString()) request is RequestWithRoute -> mapOf(ROUTING_GROUP_LABEL to request.xUriTemplate.toString()) else -> emptyMap() } ) { fun label(name: String, value: String) = copy(labels = labels + (name to value)) fun label(name: String) = labels[name] val routingGroup = labels[ROUTING_GROUP_LABEL] ?: "UNMAPPED" companion object { internal const val ROUTING_GROUP_LABEL = "routingGroup" } }
apache-2.0
28ebb4bfa1078858bd81738e17b41225
32.04
103
0.705811
3.859813
false
false
false
false
danfma/kodando
kodando-rxjs/src/test/kotlin/kodando/rxjs/tests/operator/ConcatOperatorSpec.kt
1
1277
package kodando.rxjs.tests.operator import kodando.jest.Spec import kodando.jest.expect import kodando.runtime.async.await import kodando.rxjs.observable.concat import kodando.rxjs.observable.fromArray import kodando.rxjs.observable.of import kodando.rxjs.operators.toArray object ConcatOperatorSpec : Spec() { init { describe("The concat operator") { it("usage 1") byCheckingAfter { val one = of(1, 2, 3) val two = of(4, 5, 6) val result = concat(one, two) val produced = await(result.toArray().toPromise()) expect(produced).toEqual(arrayOf(1, 2, 3, 4, 5, 6)) } it("usage 2") byCheckingAfter { val one = fromArray(arrayOf(1, 2)) val two = fromArray(arrayOf(3, 4)) val three = fromArray(arrayOf(5, 6)) val result = concat(one, two, three) val produced = await(result.toArray().toPromise()) expect(produced).toEqual(arrayOf(1, 2, 3, 4, 5, 6)) } it("usage 3") byCheckingAfter { val one = fromArray(arrayOf(1, 2, 3)) val two = fromArray(arrayOf(4, 5, 6)) val result = concat(one, two) val produced = await(result.toArray().toPromise()) expect(produced).toEqual(arrayOf(1, 2, 3, 4, 5, 6)) } } } }
mit
c5cd2bce1a5e40c6bae21606b42aa8cf
28.022727
59
0.620204
3.607345
false
false
false
false
sai-harish/Tower
Android/src/org/droidplanner/android/fragments/widget/telemetry/MiniWidgetAttitudeSpeedInfo.kt
1
5531
package org.droidplanner.android.fragments.widget.telemetry import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.preference.PreferenceManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.o3dr.services.android.lib.drone.attribute.AttributeEvent import com.o3dr.services.android.lib.drone.attribute.AttributeType import com.o3dr.services.android.lib.drone.property.Attitude import com.o3dr.services.android.lib.drone.property.Speed import org.droidplanner.android.R import org.droidplanner.android.fragments.widget.TowerWidget import org.droidplanner.android.fragments.widget.TowerWidgets import org.droidplanner.android.view.AttitudeIndicator import java.util.* /** * Created by Fredia Huya-Kouadio on 8/27/15. */ public class MiniWidgetAttitudeSpeedInfo : TowerWidget() { companion object { private val filter = initFilter() private fun initFilter(): IntentFilter { val temp = IntentFilter() temp.addAction(AttributeEvent.ATTITUDE_UPDATED) temp.addAction(AttributeEvent.SPEED_UPDATED) temp.addAction(AttributeEvent.GPS_POSITION) temp.addAction(AttributeEvent.ALTITUDE_UPDATED) temp.addAction(AttributeEvent.HOME_UPDATED) return temp } } private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { AttributeEvent.ATTITUDE_UPDATED -> onOrientationUpdate() AttributeEvent.SPEED_UPDATED, AttributeEvent.ALTITUDE_UPDATED -> onSpeedUpdate() } } } private var attitudeIndicator: AttitudeIndicator? = null private var roll: TextView? = null private var yaw: TextView? = null private var pitch: TextView? = null private var horizontalSpeed: TextView? = null private var verticalSpeed: TextView? = null private var headingModeFPV: Boolean = false private val MIN_VERTICAL_SPEED_MPS = 0.10 //Meters Per Second override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_mini_widget_attitude_speed_info, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) attitudeIndicator = view.findViewById(R.id.aiView) as AttitudeIndicator? roll = view.findViewById(R.id.rollValueText) as TextView? yaw = view.findViewById(R.id.yawValueText) as TextView? pitch = view.findViewById(R.id.pitchValueText) as TextView? horizontalSpeed = view.findViewById(R.id.horizontal_speed_telem) as TextView? verticalSpeed = view.findViewById(R.id.vertical_speed_telem) as TextView? } override fun onStart() { super.onStart() val prefs = PreferenceManager.getDefaultSharedPreferences(context) headingModeFPV = prefs.getBoolean("pref_heading_mode", false) } override fun getWidgetType() = TowerWidgets.ATTITUDE_SPEED_INFO override fun onApiConnected() { updateAllTelem() broadcastManager.registerReceiver(receiver, filter) } override fun onApiDisconnected() { broadcastManager.unregisterReceiver(receiver) } private fun updateAllTelem() { onOrientationUpdate() onSpeedUpdate() } private fun onOrientationUpdate() { if (!isAdded) return val drone = drone val attitude = drone.getAttribute<Attitude>(AttributeType.ATTITUDE) ?: return val r = attitude.roll.toFloat() val p = attitude.pitch.toFloat() var y = attitude.yaw.toFloat() if (!headingModeFPV and (y < 0)) { y += 360 } attitudeIndicator?.setAttitude(r, p, y) roll?.text = String.format(Locale.US, "%3.0f\u00B0", r) pitch?.text = String.format(Locale.US, "%3.0f\u00B0", p) yaw?.text = String.format(Locale.US, "%3.0f\u00B0", y) } private fun onSpeedUpdate() { if (!isAdded) return val drone = drone val speed = drone.getAttribute<Speed>(AttributeType.SPEED) ?: return val groundSpeedValue = speed.groundSpeed val verticalSpeedValue = speed.verticalSpeed val speedUnitProvider = speedUnitProvider horizontalSpeed?.text = getString(R.string.horizontal_speed_telem, speedUnitProvider.boxBaseValueToTarget(groundSpeedValue).toString()) verticalSpeed?.text = getString(R.string.vertical_speed_telem, speedUnitProvider.boxBaseValueToTarget(verticalSpeedValue).toString()) if (verticalSpeedValue >= MIN_VERTICAL_SPEED_MPS){ verticalSpeed?.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_debug_step_up, 0, 0, 0); }else if(verticalSpeedValue <= -(MIN_VERTICAL_SPEED_MPS)){ verticalSpeed?.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_debug_step_down, 0, 0, 0); }else{ verticalSpeed?.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_debug_step_none, 0, 0, 0); } } }
gpl-3.0
a3f38bf4bda95bf3e02f03f9d2023323
34.642384
143
0.678901
4.526187
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/cardviewer/Gesture.kt
1
3473
/* * Copyright (c) 2021 David Allison <[email protected]> * * 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 com.ichi2.anki.cardviewer import android.content.Context import android.content.SharedPreferences import android.os.Build import com.ichi2.anki.R import com.ichi2.anki.cardviewer.TapGestureMode.FOUR_POINT import com.ichi2.anki.cardviewer.TapGestureMode.NINE_POINT /** * https://www.fileformat.info/info/unicode/char/235d/index.htm (similar to a finger) * Supported on API 23 */ const val GESTURE_PREFIX = "\u235D" /** Supported on API 21: https://emojipedia.org/google/android-5.0/backhand-index-pointing-up/ */ const val LEGACY_GESTURE_PREFIX = "\uD83D\uDC46" fun interface GestureListener { fun onGesture(gesture: Gesture) } enum class Gesture( @get:JvmName("getResourceId") val resourceId: Int, ) { SWIPE_UP(R.string.gestures_swipe_up), SWIPE_DOWN(R.string.gestures_swipe_down), SWIPE_LEFT(R.string.gestures_swipe_left), SWIPE_RIGHT(R.string.gestures_swipe_right), LONG_TAP(R.string.gestures_long_tap), DOUBLE_TAP(R.string.gestures_double_tap), TAP_TOP_LEFT(R.string.gestures_corner_tap_top_left), TAP_TOP(R.string.gestures_tap_top), TAP_TOP_RIGHT(R.string.gestures_corner_tap_top_right), TAP_LEFT(R.string.gestures_tap_left), TAP_CENTER(R.string.gestures_corner_tap_middle_center), TAP_RIGHT(R.string.gestures_tap_right), TAP_BOTTOM_LEFT(R.string.gestures_corner_tap_bottom_left), TAP_BOTTOM(R.string.gestures_tap_bottom), TAP_BOTTOM_RIGHT(R.string.gestures_corner_tap_bottom_right); fun toDisplayString(context: Context): String = getDisplayPrefix() + ' ' + context.getString(resourceId) private fun getDisplayPrefix(): String = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) LEGACY_GESTURE_PREFIX else GESTURE_PREFIX } /** * How the screen is segmented for tap gestures. * The modes are incompatible ([NINE_POINT] defines points which are ambiguous in [FOUR_POINT]). * @see FOUR_POINT */ enum class TapGestureMode { /** * The cardinal directions: up, down, left & right. * Draw a line from corner to corner diagonally, each touch target fully handles the * edge which it is associated with * four-point and nine-point are thus incompatible because the four-point center and corners * are ambiguous in a nine-point system and thus not interchangeable */ FOUR_POINT, /** * Divide the screen into 9 equally sized squares for touch targets. * Better for tablets * See: #7537 */ NINE_POINT; companion object { fun fromPreference(preferences: SharedPreferences): TapGestureMode = when (preferences.getBoolean("gestureCornerTouch", false)) { true -> NINE_POINT false -> FOUR_POINT } } }
gpl-3.0
b1ed967ccdff793e4c1710dfef1e2a04
36.75
100
0.710625
3.698616
false
false
false
false
sksamuel/elasticsearch-river-neo4j
streamops-session/streamops-session-pulsar/src/main/kotlin/com/octaldata/session/pulsar/PulsarRecordOps.kt
1
3989
@file:OptIn(ExperimentalTime::class) package com.octaldata.session.pulsar import com.octaldata.core.await import com.octaldata.domain.DeploymentConnectionConfig import com.octaldata.domain.DeploymentId import com.octaldata.domain.DeploymentName import com.octaldata.domain.structure.DataRecord import com.octaldata.domain.structure.DataRecordUrn import com.octaldata.domain.topics.TopicName import com.octaldata.session.Producer import com.octaldata.session.QueryMode import com.octaldata.session.RecordOps import com.octaldata.session.Seek import com.sksamuel.tabby.results.catching import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.withContext import mu.KotlinLogging import org.apache.pulsar.client.api.BatchReceivePolicy import org.apache.pulsar.client.api.MessageId import org.apache.pulsar.client.api.PulsarClient import org.apache.pulsar.client.impl.MessageIdImpl import java.util.UUID import java.util.concurrent.TimeUnit import kotlin.time.Duration import kotlin.time.ExperimentalTime import kotlin.time.TimeSource class PulsarRecordOps( private val id: DeploymentId, private val name: DeploymentName, private val config: DeploymentConnectionConfig.Pulsar ) : RecordOps { private val logger = KotlinLogging.logger { } private val client = PulsarClient.builder() .serviceUrl(config.brokerServiceUrl) .build(); override suspend fun record(urn: DataRecordUrn): Result<DataRecord?> = catching { val (topic, partitionIndex, ledgerId, entryId) = parseUrn(urn).bind() val subname = "octal_engine_" + UUID.randomUUID().toString() val consumer = client.newConsumer() .topic(topic.value) .subscriptionName(subname) .subscribe() consumer.seekAsync(MessageIdImpl(ledgerId, entryId, partitionIndex)).await() consumer.receiveAsync().await()?.toDataRecord() } override suspend fun producer(topicName: TopicName, batchSize: Int): Result<Producer> { return Result.failure(Exception("Unsupported on pulsar")) } override suspend fun insert(topicName: TopicName, partition: Int?, urn: DataRecordUrn): Result<Boolean> { return Result.failure(Exception("Unsupported on pulsar")) } override suspend fun open( topicName: TopicName, timeout: Duration?, consumerName: String?, seek: Seek, mode: QueryMode, ): Result<Flow<DataRecord>> = runCatching { val subname = consumerName ?: ("octal_engine_" + UUID.randomUUID().toString()) val consumer = client.newConsumer() .topic(topicName.value) .subscriptionName(subname) .isAckReceiptEnabled(false) .enableBatchIndexAcknowledgment(false) .batchReceivePolicy( BatchReceivePolicy.builder() .maxNumBytes(1024 * 1024 * 10) .maxNumMessages(1000) .timeout(2, TimeUnit.SECONDS) .build() ) .subscribe() // in pulsar consumers start at the end of the stream by default when (seek) { Seek.Earliest -> consumer.seek(MessageId.earliest) Seek.Latest -> consumer.seek(MessageId.latest) is Seek.Offset -> TODO() } flow { var mark = TimeSource.Monotonic.markNow().plus(timeout ?: Duration.INFINITE) while (true) { // the 'batchReceive' call blocks val messages = withContext(Dispatchers.IO) { consumer.batchReceive() } messages.forEach { message -> emit(message.toDataRecord()) } } }.catch { logger.error(it) { "Unhandled error" } consumer.close() //config.withAdminClient { admin -> admin.deleteConsumerGroup(ConsumerGroupId(groupId)) } }.onCompletion { consumer.close() } } }
apache-2.0
0bea84b408a8b543ebda93d7fdbcca10
34.309735
108
0.695162
4.407735
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/fragment/dialogFragment/ConversationOptionsDialogFragment.kt
1
4262
/* * Copyright (c) 2017. Toshi Inc * * 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 com.toshi.view.fragment.dialogFragment import android.app.Dialog import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import com.toshi.R import com.toshi.model.local.ConversationInfo import com.toshi.view.adapter.ConversationOptionsAdapter import kotlinx.android.synthetic.main.fragment_conversation_options.options class ConversationOptionsDialogFragment : DialogFragment() { companion object { const val TAG = "ConversationOptionsDialogFragment" private const val IS_MUTED = "isMuted" private const val IS_BLOCKED = "isBlocked" fun newInstance(conversationInfo: ConversationInfo): ConversationOptionsDialogFragment { val bundle = Bundle() bundle.apply { putBoolean(IS_MUTED, conversationInfo.isMuted) putBoolean(IS_BLOCKED, conversationInfo.isBlocked) } return ConversationOptionsDialogFragment().apply { arguments = bundle } } } private var listener: ((Option) -> Unit)? = null private var isMuted = false private var isBlocked = false private lateinit var optionList: List<String> fun setItemClickListener(listener: (Option) -> Unit): ConversationOptionsDialogFragment { this.listener = listener return this } override fun onCreateDialog(state: Bundle?): Dialog { val dialog = super.onCreateDialog(state) dialog.window?.requestFeature(Window.FEATURE_NO_TITLE) dialog.setCanceledOnTouchOutside(true) return dialog } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_conversation_options, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { getOptionList() initView() } private fun getOptionList() { optionList = createOptionListFromBundle() } private fun createOptionListFromBundle(): List<String> { isMuted = arguments?.getBoolean(IS_MUTED) ?: false isBlocked = arguments?.getBoolean(IS_BLOCKED) ?: false val options = context?.resources?.getStringArray(R.array.conversation_options)?.toMutableList() ?: return emptyList() if (isMuted) options[0] = context?.getString(R.string.unmute).orEmpty() if (isBlocked) options[1] = context?.getString(R.string.unblock).orEmpty() return options.toList() } private fun initView() { options.adapter = ConversationOptionsAdapter(optionList, { handleOptionClicked(it) }) options.layoutManager = LinearLayoutManager(context) } private fun handleOptionClicked(option: String) { val index = optionList.indexOf(option) val chosenOption = when { index == 0 && isMuted -> Option.UNMUTE index == 0 && !isMuted -> Option.MUTE index == 1 && isBlocked -> Option.UNBLOCK index == 1 && !isBlocked -> Option.BLOCK index == 2 -> Option.DELETE else -> null } chosenOption?.let { listener?.invoke(chosenOption) } dismiss() } override fun onPause() { super.onPause() dismissAllowingStateLoss() } } enum class Option { MUTE, UNMUTE, BLOCK, UNBLOCK, DELETE }
gpl-3.0
8c45002bda317bfd50c7232f911a3294
35.42735
116
0.679962
4.751394
false
false
false
false
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/speakercall/SpeakersCallViewModel.kt
1
6095
package org.fossasia.openevent.general.speakercall import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.fossasia.openevent.general.R import org.fossasia.openevent.general.auth.AuthHolder import org.fossasia.openevent.general.auth.AuthService import org.fossasia.openevent.general.auth.User import org.fossasia.openevent.general.common.SingleLiveEvent import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.event.EventService import org.fossasia.openevent.general.sessions.Session import org.fossasia.openevent.general.sessions.SessionService import org.fossasia.openevent.general.speakers.Speaker import org.fossasia.openevent.general.speakers.SpeakerService import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers import timber.log.Timber class SpeakersCallViewModel( private val eventService: EventService, private val resource: Resource, private val authHolder: AuthHolder, private val authService: AuthService, private val speakerService: SpeakerService, private val sessionService: SessionService ) : ViewModel() { private val compositeDisposable = CompositeDisposable() private val mutableSpeakersCall = MutableLiveData<SpeakersCall>() val speakersCall: LiveData<SpeakersCall> = mutableSpeakersCall private val mutableSessions = MutableLiveData<List<Session>>() val sessions: LiveData<List<Session>> = mutableSessions private val mutableMessage = SingleLiveEvent<String>() val message: SingleLiveEvent<String> = mutableMessage private val mutableProgress = MutableLiveData(true) val progress: LiveData<Boolean> = mutableProgress private val mutableSpeaker = MutableLiveData<Speaker>() val speaker: LiveData<Speaker> = mutableSpeaker private val mutableUser = MutableLiveData<User>() val user: LiveData<User> = mutableUser private val mutableEmptySpeakersCall = MutableLiveData<Boolean>() val emptySpeakersCall: LiveData<Boolean> = mutableEmptySpeakersCall fun isLoggedIn(): Boolean = authHolder.isLoggedIn() fun loadMyUserAndSpeaker(eventId: Long, eventIdentifier: String) { compositeDisposable += authService.getProfile() .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.doFinally { mutableProgress.value = false }.subscribe({ user -> mutableUser.value = user loadMySpeaker(user, eventId, eventIdentifier) }) { Timber.e(it, "Failure") mutableMessage.value = resource.getString(R.string.failure) } } fun loadMySpeaker(user: User, eventId: Long, eventIdentifier: String) { val query = """[{ | 'and':[{ | 'name':'event', | 'op':'has', | 'val': { | 'name': 'identifier', | 'op': 'eq', | 'val': '$eventIdentifier' | } | }, { | 'name':'email', | 'op':'eq', | 'val':'${user.email}' | }] |}]""".trimMargin().replace("'", "\"") compositeDisposable += speakerService.getSpeakerProfileOfEmailAndEvent(user, eventId, query) .withDefaultSchedulers() .doOnSubscribe { mutableMessage.value = resource.getString(R.string.loading_speaker_profile_message) }.subscribe({ mutableSpeaker.value = it loadMySessions(it.id, eventIdentifier) }, { mutableMessage.value = resource.getString(R.string.no_speaker_profile_created_message) }) } private fun loadMySessions(speakerId: Long, eventIdentifier: String) { val query = """[{ | 'and':[{ | 'name':'event', | 'op':'has', | 'val': { | 'name': 'identifier', | 'op': 'eq', | 'val': '$eventIdentifier' | } | }] |}]""".trimMargin().replace("'", "\"") compositeDisposable += sessionService.getSessionsUnderSpeakerAndEvent(speakerId, query) .withDefaultSchedulers() .subscribe({ mutableSessions.value = it }, { mutableMessage.value = resource.getString(R.string.no_sessions_created_message) Timber.e(it, "Fail on loading session of this user") }) } fun loadSpeakersCall(eventId: Long) { if (eventId == -1L) { mutableMessage.value = resource.getString(R.string.error_fetching_event_section_message, resource.getString(R.string.speakers_call)) mutableEmptySpeakersCall.value = true mutableProgress.value = false return } compositeDisposable += eventService.getSpeakerCall(eventId) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true } .doFinally { mutableProgress.value = false } .subscribe({ mutableSpeakersCall.value = it mutableEmptySpeakersCall.value = false }, { mutableMessage.value = resource.getString(R.string.error_fetching_event_section_message, resource.getString(R.string.speakers_call)) mutableEmptySpeakersCall.value = true Timber.e(it, "Error fetching speakers call for event $eventId") }) } override fun onCleared() { super.onCleared() compositeDisposable.clear() } }
apache-2.0
23c670330ee08c91c6391e6362713a20
39.633333
104
0.60361
5.341805
false
false
false
false
sabi0/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddSdkDialog.kt
2
12068
/* * 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. */ package com.jetbrains.python.sdk.add import com.intellij.openapi.Disposable import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Splitter import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.popup.ListItemDescriptorAdapter import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.JBCardLayout import com.intellij.ui.components.JBList import com.intellij.ui.popup.list.GroupedItemsListRenderer import com.intellij.util.ExceptionUtil import com.intellij.util.PlatformUtils import com.intellij.util.ui.JBUI import com.jetbrains.python.packaging.PyExecutionException import com.jetbrains.python.sdk.PreferredSdkComparator import com.jetbrains.python.sdk.PythonSdkType import com.jetbrains.python.sdk.add.PyAddSdkDialog.Companion.create import com.jetbrains.python.sdk.add.PyAddSdkDialogFlowAction.* import com.jetbrains.python.sdk.detectVirtualEnvs import com.jetbrains.python.sdk.isAssociatedWithModule import icons.PythonIcons import java.awt.CardLayout import java.awt.event.ActionEvent import javax.swing.Action import javax.swing.JComponent import javax.swing.JPanel /** * The dialog may look like the normal dialog with OK, Cancel and Help buttons * or the wizard dialog with Next, Previous, Finish, Cancel and Help buttons. * * Use [create] to instantiate the dialog. * * @author vlan */ class PyAddSdkDialog private constructor(private val project: Project?, private val module: Module?, private val existingSdks: List<Sdk>, private val newProjectPath: String?) : DialogWrapper(project) { /** * This is the main panel that supplies sliding effect for the wizard states. */ private val mainPanel: JPanel = JPanel(JBCardLayout()) private var selectedPanel: PyAddSdkView? = null private var panels: List<PyAddSdkView> = emptyList() init { title = "Add Python Interpreter" } override fun createCenterPanel(): JComponent { val sdks = existingSdks .filter { it.sdkType is PythonSdkType && !PythonSdkType.isInvalid(it) } .sortedWith(PreferredSdkComparator()) val panels = arrayListOf<PyAddSdkView>(createVirtualEnvPanel(project, module, sdks, newProjectPath), createAnacondaPanel(project, module), PyAddSystemWideInterpreterPanel(module, existingSdks)) val extendedPanels = PyAddSdkProvider.EP_NAME.extensions .mapNotNull { it.createView(project = project, module = module, newProjectPath = newProjectPath, existingSdks = existingSdks) .registerIfDisposable() } panels.addAll(extendedPanels) mainPanel.add(SPLITTER_COMPONENT_CARD_PANE, createCardSplitter(panels)) return mainPanel } private fun <T> T.registerIfDisposable(): T = apply { (this as? Disposable)?.let { Disposer.register(disposable, it) } } private var navigationPanelCardLayout: CardLayout? = null private var southPanel: JPanel? = null override fun createSouthPanel(): JComponent { val regularDialogSouthPanel = super.createSouthPanel() val wizardDialogSouthPanel = createWizardSouthPanel() navigationPanelCardLayout = CardLayout() val result = JPanel(navigationPanelCardLayout).apply { add(regularDialogSouthPanel, REGULAR_CARD_PANE) add(wizardDialogSouthPanel, WIZARD_CARD_PANE) } southPanel = result return result } private fun createWizardSouthPanel(): JPanel { assert(value = style != DialogStyle.COMPACT, lazyMessage = { "${PyAddSdkDialog::class.java} is not ready for ${DialogStyle.COMPACT} dialog style" }) return doCreateSouthPanel(leftButtons = listOf(), rightButtons = listOf(previousButton.value, nextButton.value, cancelButton.value)) } private val nextAction: Action = object : DialogWrapperAction("Next") { override fun doAction(e: ActionEvent) { selectedPanel?.let { if (it.actions.containsKey(NEXT)) onNext() else if (it.actions.containsKey(FINISH)) { onFinish() } } } } private val nextButton = lazy { createJButtonForAction(nextAction) } private val previousAction = object : DialogWrapperAction("Previous") { override fun doAction(e: ActionEvent) = onPrevious() } private val previousButton = lazy { createJButtonForAction(previousAction) } private val cancelButton = lazy { createJButtonForAction(cancelAction) } override fun postponeValidation(): Boolean = false override fun doValidateAll(): List<ValidationInfo> = selectedPanel?.validateAll() ?: emptyList() fun getOrCreateSdk(): Sdk? = selectedPanel?.getOrCreateSdk() private fun createCardSplitter(panels: List<PyAddSdkView>): Splitter { this.panels = panels return Splitter(false, 0.25f).apply { val cardLayout = CardLayout() val cardPanel = JPanel(cardLayout).apply { preferredSize = JBUI.size(640, 480) for (panel in panels) { add(panel.component, panel.panelName) panel.addStateListener(object : PyAddSdkStateListener { override fun onComponentChanged() { show(mainPanel, panel.component) selectedPanel?.let { updateWizardActionButtons(it) } } override fun onActionsStateChanged() { selectedPanel?.let { updateWizardActionButtons(it) } } }) } } val cardsList = JBList(panels).apply { val descriptor = object : ListItemDescriptorAdapter<PyAddSdkView>() { override fun getTextFor(value: PyAddSdkView) = StringUtil.toTitleCase(value.panelName) override fun getIconFor(value: PyAddSdkView) = value.icon } cellRenderer = object : GroupedItemsListRenderer<PyAddSdkView>(descriptor) { override fun createItemComponent() = super.createItemComponent().apply { border = JBUI.Borders.empty(4, 4, 4, 10) } } addListSelectionListener { selectedPanel = selectedValue cardLayout.show(cardPanel, selectedValue.panelName) southPanel?.let { if (selectedValue.actions.containsKey(NEXT)) { navigationPanelCardLayout?.show(it, WIZARD_CARD_PANE) rootPane.defaultButton = nextButton.value updateWizardActionButtons(selectedValue) } else { navigationPanelCardLayout?.show(it, REGULAR_CARD_PANE) rootPane.defaultButton = getButton(okAction) } } selectedValue.onSelected() } selectedPanel = panels.getOrNull(0) selectedIndex = 0 } firstComponent = cardsList secondComponent = cardPanel } } private fun createVirtualEnvPanel(project: Project?, module: Module?, existingSdks: List<Sdk>, newProjectPath: String?): PyAddSdkPanel { val newVirtualEnvPanel = when { allowCreatingNewEnvironments(project) -> PyAddNewVirtualEnvPanel(project, module, existingSdks, newProjectPath) else -> null } val existingVirtualEnvPanel = PyAddExistingVirtualEnvPanel(project, module, existingSdks, newProjectPath) val panels = listOf(newVirtualEnvPanel, existingVirtualEnvPanel) .filterNotNull() val defaultPanel = when { detectVirtualEnvs(module, existingSdks).any { it.isAssociatedWithModule(module) } -> existingVirtualEnvPanel newVirtualEnvPanel != null -> newVirtualEnvPanel else -> existingVirtualEnvPanel } return PyAddSdkGroupPanel("Virtualenv environment", PythonIcons.Python.Virtualenv, panels, defaultPanel) } private fun createAnacondaPanel(project: Project?, module: Module?): PyAddSdkPanel { val newCondaEnvPanel = when { allowCreatingNewEnvironments(project) -> PyAddNewCondaEnvPanel(project, module, existingSdks, newProjectPath) else -> null } val panels = listOf(newCondaEnvPanel, PyAddExistingCondaEnvPanel(project, module, existingSdks, newProjectPath)) .filterNotNull() return PyAddSdkGroupPanel("Conda environment", PythonIcons.Python.Anaconda, panels, panels[0]) } /** * Navigates to the next step of the current wizard view. */ private fun onNext() { selectedPanel?.let { it.next() // sliding effect swipe(mainPanel, it.component, JBCardLayout.SwipeDirection.FORWARD) updateWizardActionButtons(it) } } /** * Navigates to the previous step of the current wizard view. */ private fun onPrevious() { selectedPanel?.let { it.previous() // sliding effect if (it.actions.containsKey(PREVIOUS)) { val stepContent = it.component val stepContentName = stepContent.hashCode().toString() (mainPanel.layout as JBCardLayout).swipe(mainPanel, stepContentName, JBCardLayout.SwipeDirection.BACKWARD) } else { // this is the first wizard step (mainPanel.layout as JBCardLayout).swipe(mainPanel, SPLITTER_COMPONENT_CARD_PANE, JBCardLayout.SwipeDirection.BACKWARD) } updateWizardActionButtons(it) } } /** * Tries to create the SDK and closes the dialog if the creation succeeded. * * @see [doOKAction] */ override fun doOKAction() { try { selectedPanel?.complete() } catch (e: CreateSdkInterrupted) { return } catch (e: Exception) { val cause = ExceptionUtil.findCause(e, PyExecutionException::class.java) if (cause == null) { Messages.showErrorDialog(e.localizedMessage, "Error") } else { showProcessExecutionErrorDialog(project, cause) } return } close(OK_EXIT_CODE) } private fun onFinish() { doOKAction() } private fun updateWizardActionButtons(it: PyAddSdkView) { previousButton.value.isEnabled = false it.actions.forEach { (action, isEnabled) -> val actionButton = when (action) { PREVIOUS -> previousButton.value NEXT -> nextButton.value.apply { text = "Next" } FINISH -> nextButton.value.apply { text = "Finish" } else -> null } actionButton?.isEnabled = isEnabled } } companion object { private fun allowCreatingNewEnvironments(project: Project?) = project != null || !PlatformUtils.isPyCharm() || PlatformUtils.isPyCharmEducational() private const val SPLITTER_COMPONENT_CARD_PANE = "Splitter" private const val REGULAR_CARD_PANE = "Regular" private const val WIZARD_CARD_PANE = "Wizard" @JvmStatic fun create(project: Project?, module: Module?, existingSdks: List<Sdk>, newProjectPath: String?): PyAddSdkDialog { return PyAddSdkDialog(project = project, module = module, existingSdks = existingSdks, newProjectPath = newProjectPath).apply { init() } } } } class CreateSdkInterrupted: Exception()
apache-2.0
5fd76eb2a7db57c6adfecbd67d0c9131
34.59882
133
0.677577
4.937807
false
false
false
false
mediathekview/MediathekView
src/main/java/mediathek/tool/Version.kt
1
1903
package mediathek.tool import mediathek.config.Konstanten import org.apache.logging.log4j.LogManager data class Version(val major: Int, val minor: Int, val patch: Int) { companion object { val INVALID_VERSION = Version(0, 0, 0) private val logger = LogManager.getLogger() @JvmStatic fun fromString(versionsstring: String): Version { val versions = versionsstring.replace("-SNAPSHOT", "").split(".", ignoreCase = true) return if (versions.size == 3) { try { Version( Integer.parseInt(versions[0]), Integer.parseInt(versions[1]), Integer.parseInt(versions[2]) ) } catch (ex: Exception) { logger.error("Fehler beim Parsen der Version: {}", versionsstring, ex) INVALID_VERSION } } else INVALID_VERSION } } override fun toString(): String { return if (Konstanten.APP_IS_NIGHTLY) String.format("%d.%d.%d-nightly", major, minor, patch) else String.format("%d.%d.%d", major, minor, patch) } /** * Gibt die Version als gewichtete Zahl zurück. * * @return gewichtete Zahl als Integer */ private fun toNumber(): Int { return major * 100 + minor * 10 + patch } /** * Check if other version is newer than we are. * @param other the other version to check. * @return true if other is newer, otherwise false. */ fun isOlderThan(other: Version): Boolean { return other.toNumber() > this.toNumber() } /** * Check if this version is invalid. * @return true if invalid, false otherwise. */ fun isInvalid(): Boolean { return this == INVALID_VERSION } }
gpl-3.0
1eebe37dead800804b482cc8826e05e8
29.693548
96
0.545741
4.485849
false
false
false
false
cempo/SimpleTodoList
app/src/main/java/com/makeevapps/simpletodolist/App.kt
1
1592
package com.makeevapps.simpletodolist import android.app.Application import com.crashlytics.android.Crashlytics import com.crashlytics.android.answers.Answers import com.makeevapps.simpletodolist.di.AppComponent import com.makeevapps.simpletodolist.enums.ThemeStyle import com.makeevapps.simpletodolist.utils.BaseThemeUtils import com.orhanobut.logger.AndroidLogAdapter import com.orhanobut.logger.Logger import com.orhanobut.logger.PrettyFormatStrategy import io.fabric.sdk.android.Fabric import javax.inject.Inject class App : Application() { @Inject lateinit var themeUtils: BaseThemeUtils companion object { lateinit var component: AppComponent lateinit var instance: App } override fun onCreate() { super.onCreate() instance = this component = AppComponent.buildAppComponent(this) component.inject(this) val formatStrategy = PrettyFormatStrategy.newBuilder() //.methodCount(3) // (Optional) How many method line to show. Default 2 //.methodOffset(5) // (Optional) Hides internal method calls up to offset. Default 5 .tag("TAKE_WITH_MOBILE") // (Optional) Global tag for every log. Default PRETTY_LOGGER .build() Logger.addLogAdapter(object : AndroidLogAdapter(formatStrategy) { override fun isLoggable(priority: Int, tag: String?): Boolean = BuildConfig.DEBUG }) Fabric.with(this, Crashlytics(), Answers()) } fun getCurrentThemeStyle(): ThemeStyle = themeUtils.getThemeStyle() }
mit
5060f409a7fd550cba8b98d1ff203e97
35.204545
107
0.707915
4.795181
false
false
false
false
Kushki/kushki-android
app/src/main/java/com/kushkipagos/kushkidemo/MainActivity.kt
1
13463
package com.kushkipagos.kushkidemo import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import android.widget.Button import android.widget.EditText import android.widget.Spinner import android.widget.TextView import com.kushkipagos.views.Security3DSActivity import com.kushkipagos.kushkidemo.classes.Web3DSView import com.kushkipagos.kushkidemo.services.* import com.kushkipagos.models.* import com.kushkipagos.models.TransferSubscriptions import kotlinx.coroutines.* import java.io.UnsupportedEncodingException import java.net.URLEncoder import java.util.concurrent.ExecutionException import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class MainActivity : AppCompatActivity() { lateinit var webView: WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) webView = findViewById(R.id.webView) val emailText = findViewById<View>(R.id.emailText) as EditText val userType = findViewById<View>(R.id.user_type) as Spinner val documentType = findViewById<View>(R.id.document_type) as Spinner val documentType2 = findViewById<View>(R.id.document_type2) as Spinner val reference = findViewById<View>(R.id.reference) as EditText val email = findViewById<View>(R.id.email) as EditText val description = findViewById<View>(R.id.description) as EditText val documentNumber_2 = findViewById<View>(R.id.documentNumber_2) as EditText val firstName = findViewById<View>(R.id.firstName) as EditText val lastName = findViewById<View>(R.id.lastName) as EditText val accountNumber = findViewById<View>(R.id.accountNumber) as EditText val name = findViewById<View>(R.id.name) as EditText val lastNameCash = findViewById<View>(R.id.lastNameCash) as EditText val identification = findViewById<View>(R.id.identification) as EditText val emailSubscriptionAsync = findViewById<View>(R.id.emailSubscriptionAsync) as EditText val currency = findViewById<View>(R.id.currency) as EditText val callbackUrl = findViewById<View>(R.id.callbackUrl) as EditText val cardNumber = findViewById<View>(R.id.cardNumber) as EditText val subscriptionId = findViewById<EditText>(R.id.subscriptionIdInput) val tokenChargeButton = findViewById<View>(R.id.SendTokenChargeButton) as Button tokenChargeButton.setOnClickListener { RequestTokenChargeAsyncTask(applicationContext).execute( subscriptionId.text.toString() ) } val siftTokenButton = findViewById<View>(R.id.SendSiftTokenBtn) as Button siftTokenButton.setOnClickListener { RequestSiftScienceSessionAsyncTask(applicationContext).execute( buildSiftCard() ) } val merchantSettingsInfo = findViewById<View>(R.id.getMerchantSettingsInfo) as Button merchantSettingsInfo.setOnClickListener { RequestMerchantSettingsTask(applicationContext).execute() } val transactionButton = findViewById<View>(R.id.transactionButton) as Button val textValidation3DS = findViewById<View>(R.id.textValidation3DS) as TextView val requestTransactionToken = RequestTransactionTokenAsyncTask(applicationContext, this) val requestSecureValidation = RequestCardSecureValidationAsyncTask(applicationContext) transactionButton.setOnClickListener { GlobalScope.launch { val transactionResult = requestTransactionToken.requestToken(buildCard()) withContext(Dispatchers.Main) { if (transactionResult.validated3DS != null) { if (transactionResult.security!!.specificationVersion.startsWith("2.")) { if (transactionResult.validated3DS!!.validated) { if (transactionResult.validated3DS!!.sandbox) { withContext(Dispatchers.Main) { textValidation3DS.text = "Sandbox Information: \nValidation 3DS: ${true} \nToken: ${transactionResult.token}" } } else { GlobalScope.launch { val secureValidation = requestSecureValidation.requestOTPValidation( OTPValidation(transactionResult.secureId, "") ) withContext(Dispatchers.Main) { textValidation3DS.text = "Validation 3DS: ${secureValidation.is3DSValidationOk} \nToken: ${transactionResult.token}" } } } } else { textValidation3DS.text = "Validation 3DS: ${transactionResult.validated3DS!!.validated} ${transactionResult.validated3DS!!.message}" } } else { textValidation3DS.text = transactionResult.validated3DS!!.message initWebView(transactionResult.secureId, textValidation3DS) loadWebUrl( webView, transactionResult.security!!.paReq, transactionResult.security!!.acsURL ) } } else { textValidation3DS.text = "Token request (not 3DS): ${transactionResult.message} ${transactionResult.token}" } } } } val subscriptionButton = findViewById<View>(R.id.sendSubscriptionButton) as Button subscriptionButton.setOnClickListener { RequestSubscriptionTokenAsyncTask(applicationContext).execute( buildCard() ) } val cardAsyncButton = findViewById<View>(R.id.sendCardAsyncButton) as Button cardAsyncButton.setOnClickListener { RequestCardAsyncTokenAsyncTask(applicationContext).execute( emailText.text.toString() ) } val cashButton = findViewById<View>(R.id.sendCashButton) as Button cashButton.setOnClickListener { RequestCashAsyncTokenAsyncTask(applicationContext).execute( name.text.toString(), lastNameCash.text.toString(), identification.text.toString() ) } val transferButton = findViewById<View>(R.id.sendTransferTokenButton) as Button transferButton.setOnClickListener { RequestTransferTokenAsyncTask(applicationContext).execute( Transfer( Amount(12.2, 0.0, 1.2), "www.kushki.com", mapUser(userType.selectedItem.toString())!!, documentType.selectedItem.toString(), reference.text.toString(), email.text.toString(), "CLP", description.text.toString() ) ) } val transferSubscriptionButton = findViewById<View>(R.id.sendTransferSubscriptionTokenButton) as Button transferSubscriptionButton.setOnClickListener { RequestTransferSubscriptionTokenAsyncTask(applicationContext).execute( TransferSubscriptions( documentNumber_2.text.toString(), "1", firstName.text.toString(), lastName.text.toString(), accountNumber.text.toString(), documentType2.selectedItem.toString(), "123", 12, email.text.toString(), "CLP" ) ) } val SecureValidationInfoButton = findViewById<View>(R.id.sendSecureValidationButton) as Button SecureValidationInfoButton.setOnClickListener { try { RequestSecureValidationInfoAsyncTask(applicationContext).execute( buildRequestSecure() ) } catch (e: InterruptedException) { println(e) } catch (e: ExecutionException) { println(e) } } val cardSubscriptionAsyncButton = findViewById<View>(R.id.SendCardSubscriptionAsyncTokenButton) as Button cardSubscriptionAsyncButton.setOnClickListener { RequestCardSubscriptionAsyncTokenAsyncTask(applicationContext).execute( emailSubscriptionAsync.text.toString(), currency.text.toString(), callbackUrl.text.toString(), cardNumber.text.toString() ) } } @Throws(UnsupportedEncodingException::class) private fun loadWebUrl(webView: WebView, payload: String, acsUrl: String) { val termUrl = "https://www.youtube.com" // CUSTOM_TERM_URL val postData = "PaReq=" + URLEncoder.encode( payload, "UTF-8" ) + "&TermUrl=" + URLEncoder.encode(termUrl, "UTF-8"); webView.postUrl(acsUrl, postData.toByteArray()); } @Throws(InterruptedException::class, ExecutionException::class) private fun initWebView(secureId: String, textView: TextView) { val webSettings = webView.settings webSettings.javaScriptEnabled = true webSettings.setSupportMultipleWindows(true) webSettings.defaultTextEncodingName = "utf-8" webView.webViewClient = Web3DSView(applicationContext, secureId, textView) } @Throws(InterruptedException::class, ExecutionException::class) private fun buildRequestSecure(): AskQuestionnaire { val documentType2 = findViewById<View>(R.id.document_type2) as Spinner val documentNumber_2 = findViewById<View>(R.id.documentNumber_2) as EditText val firstName = findViewById<View>(R.id.firstName) as EditText val lastName = findViewById<View>(R.id.lastName) as EditText val accountNumber = findViewById<View>(R.id.accountNumber) as EditText val email = findViewById<View>(R.id.email) as EditText val expeditionDocumentDate = findViewById<View>(R.id.expeditionDocumentDate) as EditText val cityCode = findViewById<View>(R.id.cityCode) as EditText val stateCode = findViewById<View>(R.id.stateCode) as EditText val phone = findViewById<View>(R.id.phone) as EditText val transferSubscription = RequestTransferSubscriptionTokenAsyncTask( applicationContext ) transferSubscription.execute( TransferSubscriptions( documentNumber_2.text.toString(), "1", firstName.text.toString(), lastName.text.toString(), accountNumber.text.toString(), documentType2.selectedItem.toString(), "01", 12, email.text.toString(), "CLP" ) ) val subscription = transferSubscription._result!! val secureService: String = subscription.secureService val secureId: String = subscription.secureId return AskQuestionnaire( secureId, secureService, "1", stateCode.text.toString(), phone.text.toString(), "15/12/1958", "20000000107415376000" ) } private fun buildCard(): Card { val nameText = findViewById<View>(R.id.nameText) as EditText val numberText = findViewById<View>(R.id.numberText) as EditText val monthText = findViewById<View>(R.id.monthText) as EditText val yearText = findViewById<View>(R.id.yearText) as EditText val cvvText = findViewById<View>(R.id.cvvText) as EditText return Card( nameText.text.toString(), numberText.text.toString(), cvvText.text.toString(), monthText.text.toString(), yearText.text.toString() ) } private fun buildSiftCard(): Card? { val cardNameSift = findViewById<EditText>(R.id.cardHolderInput) val cardNumberSift = findViewById<EditText>(R.id.cardNumberInput) val cardCvvSift = findViewById<EditText>(R.id.cardCvvInput) val cardExpiryYearSift = findViewById<EditText>(R.id.cardYearInput) val cardExpiryMonthSift = findViewById<EditText>(R.id.cardMonthInput) return Card( cardNameSift.text.toString(), cardNumberSift.text.toString(), cardCvvSift.text.toString(), cardExpiryMonthSift.text.toString(), cardExpiryYearSift.text.toString() ) } private fun mapUser(usertType: String): String { return if (usertType == "Natural") "0" else "1" } }
mit
bec41bee75f62419d24a6a1b2ac899ce
46.914591
149
0.611231
5.402488
false
false
false
false
FHannes/intellij-community
platform/lang-impl/src/com/intellij/psi/formatter/IndentRangesCalculator.kt
36
1615
/* * Copyright 2000-2016 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.psi.formatter import com.intellij.openapi.editor.Document import com.intellij.openapi.util.TextRange import com.intellij.util.text.CharArrayUtil class IndentRangesCalculator(private val document: Document, private val textRange: TextRange) { private val startOffset = textRange.startOffset private val endOffset = textRange.endOffset fun calcIndentRanges(): List<TextRange> { val startLine = document.getLineNumber(startOffset) val endLine = document.getLineNumber(endOffset) val chars = document.charsSequence val indentRanges = mutableListOf<TextRange>() for (line in startLine..endLine) { val lineStartOffset = document.getLineStartOffset(line) val lineEndOffset = document.getLineEndOffset(line) val firstNonWsChar = CharArrayUtil.shiftForward(chars, lineStartOffset, lineEndOffset + 1, " \t") indentRanges.add(TextRange(lineStartOffset, firstNonWsChar)) } return indentRanges } }
apache-2.0
6998ca6ef8f15c3f402d6160e71d23ea
34.911111
103
0.739319
4.52381
false
false
false
false
AgileVentures/MetPlus_resumeCruncher
web/src/test/kotlin/org/metplus/cruncher/web/TestConfiguration.kt
1
4091
package org.metplus.cruncher.web import org.metplus.cruncher.job.* import org.metplus.cruncher.rating.* import org.metplus.cruncher.resume.* import org.metplus.cruncher.settings.GetSettings import org.metplus.cruncher.settings.SaveSettings import org.metplus.cruncher.settings.SettingsRepository import org.metplus.cruncher.settings.SettingsRepositoryFake import org.metplus.cruncher.web.security.services.LocalTokenService import org.metplus.cruncher.web.security.services.TokenService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.SpringBootConfiguration import org.springframework.context.annotation.Bean import org.springframework.web.servlet.config.annotation.EnableWebMvc @SpringBootConfiguration @EnableWebMvc open class TestConfiguration { @Bean open fun getSettingsRepository(): SettingsRepository = SettingsRepositoryFake() @Bean open fun getJobRepository(): JobsRepository = JobRepositoryFake() @Bean open fun getResumeRepository(): ResumeRepository = ResumeRepositoryFake() @Bean open fun getResumeFileRepository(): ResumeFileRepository = ResumeFileRepositoryFake() @Bean open fun getSettings(): GetSettings = GetSettings(getSettingsRepository()) @Bean open fun saveSettings(): SaveSettings = SaveSettings(getSettingsRepository()) @Bean open fun createJob( @Autowired jobsRepository: JobsRepository, @Autowired crunchJobProcessSpy: ProcessCruncher<Job> ): CreateJob = CreateJob(jobsRepository, crunchJobProcessSpy) @Bean open fun updateJob(@Autowired jobsRepository: JobsRepository, @Autowired crunchJobProcessSpy: ProcessCruncher<Job> ): UpdateJob = UpdateJob(jobsRepository, crunchJobProcess()) @Bean open fun matchWithResume(@Autowired resumeRepository: ResumeRepository, @Autowired jobsRepository: JobsRepository, @Autowired matchers: MatcherList ): MatchWithResume = MatchWithResume(resumeRepository, jobsRepository, matchers) @Bean open fun allMatchers( @Autowired matcherStub: Matcher<Resume, Job> ): MatcherList { return MatcherList(listOf(matcherStub)) } @Bean open fun tokenService(): TokenService = LocalTokenService() @Bean open fun uploadResume( @Autowired resumeRepository: ResumeRepository, @Autowired resumeFileRepository: ResumeFileRepository, @Autowired crunchResumeProcess: ProcessCruncher<Resume> ): UploadResume = UploadResume(resumeRepository, resumeFileRepository, crunchResumeProcess) @Bean open fun downloadResume( @Autowired resumeRepository: ResumeRepository, @Autowired resumeFileRepository: ResumeFileRepository ): DownloadResume = DownloadResume(resumeRepository, resumeFileRepository) @Bean open fun matchWithJob(@Autowired resumeRepository: ResumeRepository, @Autowired jobsRepository: JobsRepository, @Autowired matcherList: MatcherList ): MatchWithJob = MatchWithJob(resumeRepository, jobsRepository, matcherList) @Bean open fun crunchResumeProcess(): ProcessCruncher<Resume> = CrunchResumeProcessSpy() @Bean open fun crunchJobProcess(): ProcessCruncher<Job> = CrunchJobProcessSpy() @Bean open fun matcher(): Matcher<Resume, Job> = MatcherStub() @Bean open fun reCrunchAllJobs( jobsRepository: JobsRepository, jobProcess: ProcessCruncher<Job>) = ReCrunchAllJobs(jobsRepository, jobProcess) @Bean open fun reCrunchAllResumes( resumeRepository: ResumeRepository, resumeProcess: ProcessCruncher<Resume>) = ReCrunchAllResumes(resumeRepository, resumeProcess) @Bean open fun compareResumeWithJob( jobsRepository: JobsRepository, resumeRepository: ResumeRepository, matcher: Matcher<Resume, Job> ) = CompareResumeWithJob(jobsRepository, resumeRepository, matcher) }
gpl-3.0
c0dabccc4f7414c95f639ac6c3997cce
36.541284
105
0.732095
5.627235
false
false
false
false
trmollet/tuto_kotlin
src/iv_properties/n33LazyProperty.kt
1
692
package iv_properties import util.TODO class LazyProperty(val initializer: () -> Int) { private val lazyValue: Int? = null get() { if (field == null) field = initializer() return field } val lazy: Int get() = lazyValue!! } fun todoTask33(): Nothing = TODO( """ Task 33. Add a custom getter to make the 'lazy' val really lazy. It should be initialized by the invocation of 'initializer()' at the moment of the first access. You can add as many additional properties as you need. Do not use delegated properties yet! """, references = { LazyProperty({ 42 }).lazy } )
mit
36a6c96f9581474e1c51c4daa83eb651
26.68
69
0.586705
4.552632
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-videochat-kotlin/app/src/main/java/com/quickblox/sample/videochat/kotlin/db/DbHelper.kt
1
1227
package com.quickblox.sample.videochat.kotlin.db import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.util.Log private val DB_NAME = "groupchatwebrtcDB" val DB_TABLE_NAME = "users" val DB_COLUMN_ID = "ID" val DB_COLUMN_USER_FULL_NAME = "userFullName" val DB_COLUMN_USER_LOGIN = "userLogin" val DB_COLUMN_USER_ID = "userID" val DB_COLUMN_USER_PASSWORD = "userPass" val DB_COLUMN_USER_TAG = "userTag" class DbHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, 1) { private val TAG = DbHelper::class.java.simpleName override fun onCreate(db: SQLiteDatabase) { Log.d(TAG, "--- onCreate database ---") db.execSQL("create table " + DB_TABLE_NAME + " (" + DB_COLUMN_ID + " integer primary key autoincrement," + DB_COLUMN_USER_ID + " integer," + DB_COLUMN_USER_LOGIN + " text," + DB_COLUMN_USER_PASSWORD + " text," + DB_COLUMN_USER_FULL_NAME + " text," + DB_COLUMN_USER_TAG + " text" + ");") } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { } }
bsd-3-clause
74b0095db4eec781101ba9c550b03f72
33.111111
82
0.638957
3.684685
false
false
false
false
gumil/basamto
app/src/main/kotlin/io/github/gumil/basamto/common/adapter/ItemAdapter.kt
1
3978
/* * The MIT License (MIT) * * Copyright 2017 Miguel Panelo * * 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 io.github.gumil.basamto.common.adapter import android.os.Handler import android.support.v7.widget.RecyclerView import android.view.ViewGroup import io.github.gumil.basamto.extensions.inflateLayout import io.reactivex.Observable import io.reactivex.Observer import io.reactivex.android.MainThreadDisposable internal class ItemAdapter<M>( private val defaultItem: ViewItem<M>, private val prefetchDistance: Int = 2 ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var footerItem: ViewItem<*>? = null private var _footerItem: ViewItem<*>? = null var list: List<M> get() = _list set(value) { _list = value.toMutableList() notifyDataSetChanged() } private var _list: MutableList<M> = mutableListOf() private var currentListSize = 0 var onPrefetch: (() -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = object : RecyclerView.ViewHolder(parent.inflateLayout(viewType)) {} override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (position < _list.size) { defaultItem.bind(holder.itemView, _list[position]) } if (_list.size > currentListSize && position == (_list.size - prefetchDistance)) { currentListSize = _list.size Handler().post { onPrefetch?.invoke() } } } override fun getItemCount(): Int = _list.size + (_footerItem?.let { 1 } ?: 0) override fun getItemViewType(position: Int): Int { return if (position == _list.size) { _footerItem?.layout ?: 0 } else { defaultItem.layout } } fun showFooter() { _footerItem = footerItem notifyItemInserted(currentListSize + 10) } fun addItems(items: List<M>) { _footerItem = null _list.addAll(items) notifyItemChanged(currentListSize) notifyItemRangeInserted(currentListSize + 1, currentListSize + items.size) } } internal class OnPrefetchObservable( private val adapter: ItemAdapter<*> ): Observable<Unit>() { override fun subscribeActual(observer: Observer<in Unit>?) { observer?.let { adapter.onPrefetch = Listener(adapter, it) } } internal class Listener( private val adapter: ItemAdapter<*>, private val observer: Observer<in Unit> ) : MainThreadDisposable(), Function0<Unit> { override fun invoke() { if (!isDisposed) { observer.onNext(Unit) } } override fun onDispose() { adapter.onPrefetch = null } } } internal fun <M> ItemAdapter<M>.prefetch() = OnPrefetchObservable(this)
mit
ed2923b12170c2ef0eecd720da070215
31.349593
96
0.661639
4.625581
false
false
false
false
didi/DoraemonKit
Android/dokit-plugin/src/main/kotlin/com/didichuxing/doraemonkit/plugin/DoKitExt.kt
2
7994
package com.didichuxing.doraemonkit.plugin import com.android.build.gradle.api.BaseVariant import com.android.dex.DexFormat import com.android.dx.command.dexer.Main import com.didiglobal.booster.kotlinx.NCPU import com.didiglobal.booster.kotlinx.redirect import com.didiglobal.booster.kotlinx.search import com.didiglobal.booster.kotlinx.touch import com.didiglobal.booster.transform.TransformContext import com.didiglobal.booster.transform.util.transform import org.apache.commons.compress.archivers.jar.JarArchiveEntry import org.apache.commons.compress.archivers.zip.ParallelScatterZipCreator import org.apache.commons.compress.archivers.zip.ZipArchiveEntry import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream import org.apache.commons.compress.parallel.InputStreamSupplier import org.objectweb.asm.Opcodes.* import org.objectweb.asm.tree.* import java.io.File import java.io.IOException import java.io.OutputStream import java.util.concurrent.* import java.util.jar.JarFile import java.util.zip.ZipEntry import java.util.zip.ZipFile /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/5/19-18:00 * 描 述:dokit 对象扩展 * 修订历史: * ================================================ */ fun MethodNode.isGetSetMethod(): Boolean { var ignoreCount = 0 val iterator = instructions.iterator() while (iterator.hasNext()) { val insnNode = iterator.next() val opcode = insnNode.opcode if (-1 == opcode) { continue } if (opcode != GETFIELD && opcode != GETSTATIC && opcode != H_GETFIELD && opcode != H_GETSTATIC && opcode != RETURN && opcode != ARETURN && opcode != DRETURN && opcode != FRETURN && opcode != LRETURN && opcode != IRETURN && opcode != PUTFIELD && opcode != PUTSTATIC && opcode != H_PUTFIELD && opcode != H_PUTSTATIC && opcode > SALOAD) { if (name.equals("<init>") && opcode == INVOKESPECIAL) { ignoreCount++ if (ignoreCount > 1) { return false } continue } return false } } return true } fun MethodNode.isSingleMethod(): Boolean { val iterator = instructions.iterator() while (iterator.hasNext()) { val insnNode = iterator.next() val opcode = insnNode.opcode if (-1 == opcode) { continue } else if (INVOKEVIRTUAL <= opcode && opcode <= INVOKEDYNAMIC) { return false } } return true } fun MethodNode.isEmptyMethod(): Boolean { val iterator = instructions.iterator() while (iterator.hasNext()) { val insnNode = iterator.next() val opcode = insnNode.opcode return if (-1 == opcode) { continue } else { false } } return true } fun MethodNode.isMainMethod(className: String): Boolean { if (this.name == "main" && this.desc == "([Ljava/lang/String;)V") { // "====isMainMethod====$className ${this.name} ${this.desc} ${this.access}".println() return true } return false } fun InsnList.getMethodExitInsnNodes(): Sequence<InsnNode>? { return this.iterator()?.asSequence()?.filterIsInstance(InsnNode::class.java)?.filter { it.opcode == RETURN || it.opcode == IRETURN || it.opcode == FRETURN || it.opcode == ARETURN || it.opcode == LRETURN || it.opcode == DRETURN || it.opcode == ATHROW } } fun BaseVariant.isRelease(): Boolean { if (this.name.contains("release") || this.name.contains("Release")) { return true } return false } fun TransformContext.isRelease(): Boolean { if (this.name.contains("release") || this.name.contains("Release")) { return true } return false } fun String.println() { if (DoKitExtUtil.dokitLogSwitchOpen()) { println("[dokit plugin]===>$this") } } fun File.lastPath(): String { return this.path.split("/").last() } val MethodInsnNode.ownerClassName: String get() = owner.replace('/', '.') val ClassNode.formatSuperName: String get() = superName.replace('/', '.') internal fun File.dex(output: File, api: Int = DexFormat.API_NO_EXTENDED_OPCODES): Int { val args = Main.Arguments().apply { numThreads = NCPU debug = true warnings = true emptyOk = true multiDex = true jarOutput = true optimize = false minSdkVersion = api fileNames = arrayOf(output.canonicalPath) outName = canonicalPath } return try { Main.run(args) } catch (t: Throwable) { t.printStackTrace() -1 } } /** * Transform this file or directory to the output by the specified transformer * * @param output The output location * @param transformer The byte data transformer */ fun File.dokitTransform(output: File, transformer: (ByteArray) -> ByteArray = { it -> it }) { when { isDirectory -> this.toURI().let { base -> this.search().parallelStream().forEach { it.transform(File(output, base.relativize(it.toURI()).path), transformer) } } isFile -> when (extension.toLowerCase()) { "jar" -> JarFile(this).use { it.dokitTransform(output, ::JarArchiveEntry, transformer) } "class" -> this.inputStream().use { it.transform(transformer).redirect(output) } else -> this.copyTo(output, true) } else -> throw IOException("Unexpected file: ${this.canonicalPath}") } } fun ZipFile.dokitTransform( output: File, entryFactory: (ZipEntry) -> ZipArchiveEntry = ::ZipArchiveEntry, transformer: (ByteArray) -> ByteArray = { it -> it } ) = output.touch().outputStream().buffered().use { this.dokitTransform(it, entryFactory, transformer) } fun ZipFile.dokitTransform( output: OutputStream, entryFactory: (ZipEntry) -> ZipArchiveEntry = ::ZipArchiveEntry, transformer: (ByteArray) -> ByteArray = { it -> it } ) { val entries = mutableSetOf<String>() val creator = ParallelScatterZipCreator( ThreadPoolExecutor( NCPU, NCPU, 0L, TimeUnit.MILLISECONDS, LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), RejectedExecutionHandler { runnable, _ -> runnable.run() }) ) //将jar包里的文件序列化输出 entries().asSequence().forEach { entry -> if (!entries.contains(entry.name)) { val zae = entryFactory(entry) val stream = InputStreamSupplier { when (entry.name.substringAfterLast('.', "")) { "class" -> getInputStream(entry).use { src -> try { src.transform(transformer).inputStream() } catch (e: Throwable) { System.err.println("Broken class: ${this.name}!/${entry.name}") getInputStream(entry) } } else -> getInputStream(entry) } } creator.addArchiveEntry(zae, stream) entries.add(entry.name) } else { System.err.println("Duplicated jar entry: ${this.name}!/${entry.name}") } } val zip = ZipArchiveOutputStream(output) zip.use { zipStream -> try { creator.writeTo(zipStream) zipStream.close() } catch (e: Exception) { zipStream.close() // e.printStackTrace() // "e===>${e.message}".println() System.err.println("Duplicated jar entry: ${this.name}!") } } }
apache-2.0
7f7bcacbc967456b95a96063273c3060
30.173228
343
0.58045
4.465877
false
false
false
false
apollo-rsps/apollo
game/plugin/shops/src/org/apollo/game/plugin/shops/builder/OperatorBuilder.kt
1
2729
package org.apollo.game.plugin.shops.builder import org.apollo.game.plugin.api.Definitions /** * A builder to provide the list of shop operators - the npcs that can be interacted with to access the shop. * * ``` * shop("General Store.") { * operated by "Shopkeeper"(522) and "Shop assistant"(523) and "Shop assistant"(524) * ... * } * ``` */ @ShopDslMarker class OperatorBuilder internal constructor(private val shopName: String) { /** * The [List] of shop operator ids. */ private val operators = mutableListOf<Int>() /** * Adds a shop operator, using the specified [name] to resolve the npc id. */ infix fun by(name: String): OperatorBuilder { val npc = requireNotNull(Definitions.npc(name)) { "Failed to resolve npc named `$name` when building shop $shopName." } operators += npc.id return this } /** * Adds a shop operator, using the specified [name] to resolve the npc id. * * An alias for [by]. */ infix fun and(name: String): OperatorBuilder = by(name) /** * Adds a shop operator, using the specified [name] to resolve the npc id. * * An alias for [by]. */ operator fun plus(name: String): OperatorBuilder = and(name) /** * Adds a shop operator with the specified npc id. Intended to be used with the overloaded String invokation * operator, solely to disambiguate between npcs with the same name (e.g. `"Shopkeeper"(500) vs * `"Shopkeeper"(501)`). Use [by(String)][by] if the npc name is unambiguous. */ infix fun by(pair: Pair<String, Int>): OperatorBuilder { operators += pair.second return this } /** * Adds a shop operator with the specified npc id. Intended to be used with the overloaded String invokation * operator, solely to disambiguate between npcs with the same name (e.g. `"Shopkeeper"(500) vs * `"Shopkeeper"(501)`). Use [by(String)][by] if the npc name is unambiguous. * * An alias for [by(Pair<String, Int>)][by]. */ infix fun and(pair: Pair<String, Int>): OperatorBuilder = by(pair) /** * Adds a shop operator with the specified npc id. Intended to be used with the overloaded String invokation * operator, solely to disambiguate between npcs with the same name (e.g. `"Shopkeeper"(500) vs * `"Shopkeeper"(501)`). Use [by(String)][by] if the npc name is unambiguous. * * An alias for [by(Pair<String, Int>)][by]. */ operator fun plus(pair: Pair<String, Int>): OperatorBuilder = by(pair) /** * Builds this [OperatorBuilder] into a [List] of operator npc ids. */ fun build(): List<Int> = operators }
isc
39aeecc90ca28882fcb840ac0e5cb928
32.292683
112
0.632833
4.031019
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/media/PlayerService.kt
1
6658
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.media import android.app.PendingIntent import android.app.Service import android.content.Intent import android.media.AudioManager import android.os.Bundle import android.os.IBinder import android.widget.MediaController import android.widget.Toast import androidx.core.app.NotificationCompat import com.nextcloud.client.account.User import com.nextcloud.client.network.ClientFactory import com.owncloud.android.R import com.owncloud.android.datamodel.OCFile import com.owncloud.android.ui.notifications.NotificationUtils import com.owncloud.android.utils.theme.ViewThemeUtils import dagger.android.AndroidInjection import java.util.Locale import javax.inject.Inject class PlayerService : Service() { companion object { const val EXTRA_USER = "USER" const val EXTRA_FILE = "FILE" const val EXTRA_AUTO_PLAY = "EXTRA_AUTO_PLAY" const val EXTRA_START_POSITION_MS = "START_POSITION_MS" const val ACTION_PLAY = "PLAY" const val ACTION_STOP = "STOP" const val ACTION_TOGGLE = "TOGGLE" const val ACTION_STOP_FILE = "STOP_FILE" } class Binder(val service: PlayerService) : android.os.Binder() { /** * This property returns current instance of media player interface. * It is not cached and it is suitable for polling. */ val player: MediaController.MediaPlayerControl get() = service.player } private val playerListener = object : Player.Listener { override fun onRunning(file: OCFile) { startForeground(file) } override fun onStart() { // empty } override fun onPause() { // empty } override fun onStop() { stopServiceAndRemoveNotification(null) } override fun onError(error: PlayerError) { Toast.makeText(this@PlayerService, error.message, Toast.LENGTH_SHORT).show() } } @Inject protected lateinit var audioManager: AudioManager @Inject protected lateinit var clientFactory: ClientFactory @Inject lateinit var viewThemeUtils: ViewThemeUtils private lateinit var player: Player private lateinit var notificationBuilder: NotificationCompat.Builder private var isRunning = false override fun onCreate() { super.onCreate() AndroidInjection.inject(this) player = Player(applicationContext, clientFactory, playerListener, audioManager) notificationBuilder = NotificationCompat.Builder(this) viewThemeUtils.androidx.themeNotificationCompatBuilder(this, notificationBuilder) val stop = Intent(this, PlayerService::class.java) stop.action = ACTION_STOP val pendingStop = PendingIntent.getService(this, 0, stop, PendingIntent.FLAG_IMMUTABLE) notificationBuilder.addAction(0, getString(R.string.player_stop).toUpperCase(Locale.getDefault()), pendingStop) val toggle = Intent(this, PlayerService::class.java) toggle.action = ACTION_TOGGLE val pendingToggle = PendingIntent.getService(this, 0, toggle, PendingIntent.FLAG_IMMUTABLE) notificationBuilder.addAction( 0, getString(R.string.player_toggle).toUpperCase(Locale.getDefault()), pendingToggle ) } override fun onBind(intent: Intent?): IBinder? { return Binder(this) } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { when (intent.action) { ACTION_PLAY -> onActionPlay(intent) ACTION_STOP -> onActionStop() ACTION_STOP_FILE -> onActionStopFile(intent.extras) ACTION_TOGGLE -> onActionToggle() } return START_NOT_STICKY } private fun onActionToggle() { if (player.isPlaying) { player.pause() } else { player.start() } } private fun onActionPlay(intent: Intent) { val user: User = intent.getParcelableExtra(EXTRA_USER)!! val file: OCFile = intent.getParcelableExtra(EXTRA_FILE)!! val startPos = intent.getLongExtra(EXTRA_START_POSITION_MS, 0) val autoPlay = intent.getBooleanExtra(EXTRA_AUTO_PLAY, true) val item = PlaylistItem(file = file, startPositionMs = startPos, autoPlay = autoPlay, user = user) player.play(item) } private fun onActionStop() { stopServiceAndRemoveNotification(null) } private fun onActionStopFile(args: Bundle?) { val file: OCFile = args?.getParcelable(EXTRA_FILE) ?: throw IllegalArgumentException("Missing file argument") stopServiceAndRemoveNotification(file) } private fun startForeground(currentFile: OCFile) { val ticker = String.format(getString(R.string.media_notif_ticker), getString(R.string.app_name)) val content = getString(R.string.media_state_playing, currentFile.getFileName()) notificationBuilder.setSmallIcon(R.drawable.ic_play_arrow) notificationBuilder.setWhen(System.currentTimeMillis()) notificationBuilder.setOngoing(true) notificationBuilder.setContentTitle(ticker) notificationBuilder.setContentText(content) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA) } startForeground(R.string.media_notif_ticker, notificationBuilder.build()) isRunning = true } private fun stopServiceAndRemoveNotification(file: OCFile?) { if (file == null) { player.stop() } else { player.stop(file) } if (isRunning) { stopForeground(true) stopSelf() isRunning = false } } }
gpl-2.0
fdad1177ff79b07cf9cfb739f04ca366
33.858639
119
0.680234
4.755714
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/course/DocumentListFragment.kt
1
2122
package de.xikolo.controllers.course import android.os.Bundle import android.view.View import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import butterknife.BindView import com.yatatsu.autobundle.AutoBundleField import de.xikolo.R import de.xikolo.controllers.base.ViewModelFragment import de.xikolo.extensions.observe import de.xikolo.viewmodels.course.DocumentListViewModel class DocumentListFragment : ViewModelFragment<DocumentListViewModel>() { @AutoBundleField lateinit var courseId: String @BindView(R.id.content_view) internal lateinit var recyclerView: RecyclerView private lateinit var documentListAdapter: DocumentListAdapter override fun createViewModel(): DocumentListViewModel { return DocumentListViewModel(courseId) } override val layoutResource = R.layout.fragment_course_documents override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val layoutManager = LinearLayoutManager(activity) recyclerView.layoutManager = layoutManager val dividerItemDecoration = DividerItemDecoration( recyclerView.context, layoutManager.orientation ) recyclerView.addItemDecoration(dividerItemDecoration) activity?.let { a -> documentListAdapter = DocumentListAdapter(a) recyclerView.adapter = documentListAdapter } viewModel.documentsForCourse .observe(viewLifecycleOwner) { showDocuments() } viewModel.localizations .observe(viewLifecycleOwner) { showDocuments() } } private fun showDocuments() { viewModel.documentsForCourse.value?.let { documents -> if (documents.isEmpty()) { showEmptyMessage(R.string.empty_message_documents_title) } else { showContent() documentListAdapter.documentList = documents.toMutableList() } } } }
bsd-3-clause
a15e3eaab4f46c55122b6a3d24ec261f
31.646154
76
0.717719
5.613757
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mcp/vanillagradle/VanillaGradleDecompileSourceProvider.kt
1
3620
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.vanillagradle import com.demonwav.mcdev.util.findModule import com.demonwav.mcdev.util.runGradleTaskWithCallback import com.intellij.codeInsight.AttachSourcesProvider import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback import com.intellij.openapi.externalSystem.task.TaskCallback import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.util.ActionCallback import com.intellij.psi.PsiFile import com.intellij.psi.PsiJavaFile import java.nio.file.Paths import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.gradle.util.GradleUtil class VanillaGradleDecompileSourceProvider : AttachSourcesProvider { override fun getActions( orderEntries: List<LibraryOrderEntry>, psiFile: PsiFile ): Collection<AttachSourcesProvider.AttachSourcesAction> { if (psiFile !is PsiJavaFile || !psiFile.packageName.startsWith("net.minecraft")) { return emptyList() } val module = psiFile.findModule() ?: return emptyList() val vgData = GradleUtil.findGradleModuleData(module)?.children ?.find { it.key == VanillaGradleData.KEY }?.data as? VanillaGradleData ?: return emptyList() return listOf(DecompileAction(vgData.decompileTaskName)) } private class DecompileAction(val decompileTaskName: String) : AttachSourcesProvider.AttachSourcesAction { override fun getName(): String = "Decompile Minecraft" override fun getBusyText(): String = "Decompiling Minecraft..." override fun perform(orderEntriesContainingFile: List<LibraryOrderEntry>): ActionCallback { val project = orderEntriesContainingFile.firstOrNull()?.ownerModule?.project ?: return ActionCallback.REJECTED val projectPath = project.basePath ?: return ActionCallback.REJECTED val callback = ActionCallback() val taskCallback = object : TaskCallback { override fun onSuccess() { val importSpec = ImportSpecBuilder(project, GradleConstants.SYSTEM_ID) .callback( object : ExternalProjectRefreshCallback { override fun onSuccess(externalProject: DataNode<ProjectData>?) = callback.setDone() override fun onFailure(errorMessage: String, errorDetails: String?) { callback.reject( if (errorDetails == null) errorMessage else "$errorMessage: $errorDetails" ) } } ) ExternalSystemUtil.refreshProject(projectPath, importSpec) } override fun onFailure() = callback.setRejected() } runGradleTaskWithCallback( project, Paths.get(projectPath), { settings -> settings.taskNames = listOf(decompileTaskName) }, taskCallback ) return callback } } }
mit
9a9951b28927800ce623aed799022987
41.093023
116
0.655525
5.700787
false
false
false
false
bozaro/git-as-svn
src/test/kotlin/svnserver/auth/cache/TestUserDB.kt
1
2008
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.auth.cache import svnserver.auth.Authenticator import svnserver.auth.PlainAuthenticator import svnserver.auth.User import svnserver.auth.UserDB /** * Testing UserDB implementation. * * @author Artem V. Navrotskiy */ internal class TestUserDB(vararg users: User) : UserDB { private val users = arrayOf(*users) private val report = StringBuilder() override fun check(username: String, password: String): User? { log("check: $username, $password") if (password == password(username)) { for (user in users) { if (user.username == username) { return user } } } return null } private fun log(message: String) { if (report.isNotEmpty()) report.append('\n') report.append(message) } fun password(username: String): String { return "~~~$username~~~" } override fun lookupByUserName(username: String): User? { log("lookupByUserName: $username") for (user in users) { if (user.username == username) { return user } } return null } override fun lookupByExternal(external: String): User? { log("lookupByExternal: $external") for (user in users) { if (user.externalId == external) { return user } } return null } fun report(): String { return report.toString() } override fun authenticators(): Collection<Authenticator> { return listOf(PlainAuthenticator(this)) } }
gpl-2.0
e30fa87db1306430e4e0fbb0f3d86962
27.28169
76
0.604582
4.393873
false
false
false
false
greggigon/TeamCity-Crowd-Plugin
teamcity-crowd-plugin-server/src/main/kotlin/teamcity/crowd/plugin/PluginCrowdClient.kt
1
3503
package teamcity.crowd.plugin import com.atlassian.crowd.exception.* import com.atlassian.crowd.model.group.Group import com.atlassian.crowd.model.user.User import com.atlassian.crowd.service.client.CrowdClient import com.intellij.openapi.diagnostic.Logger import teamcity.crowd.plugin.utils.LoggerFactory import com.atlassian.crowd.exception.ApplicationPermissionException import com.atlassian.crowd.exception.InvalidAuthenticationException import com.atlassian.crowd.service.client.ClientProperties import com.atlassian.crowd.service.factory.CrowdClientFactory interface PluginCrowdClient { fun loginUserWithPassword(username: String, password: String): User? fun getUserGroups(username: String): Collection<Group> companion object { const val APPLICATION_PERMISSIONS_MESSAGE = "Crowd client permissions are incorrect. Configuration details are incorrect." const val INVALID_AUTHENTICATION_MESSAGE = "Plugin can't authenticate with Crowd. Configuration details are incorrect." const val OPERATION_FAILED_MESSAGE = "Bummer. Something went wrong. Can't talk to Crowd at all." const val UNKNOWN_ERROR_MESSAGE = "Bummer. Failed with unknown reasons!" } } class TeamCityPluginCrowdClientFactory( private val crowdClientFactory: CrowdClientFactory, private val clientProperties: ClientProperties){ fun newInstance(): CrowdClient = crowdClientFactory.newInstance(clientProperties) } class TeamCityPluginCrowdClient(private val crowdClient: CrowdClient, loggerFactory: LoggerFactory) : PluginCrowdClient { private val logger: Logger = loggerFactory.getServerLogger() override fun loginUserWithPassword(username: String, password: String): User? { try { return crowdClient.authenticateUser(username, password) } catch (e: UserNotFoundException) { logger.warn("User with name [$username] doesn't exists.", e) } catch (e: InactiveAccountException) { logger.info("User account [$username] is inactive", e) } catch (e: ExpiredCredentialException) { logger.info("User [$username] credentials expired", e) } catch (e: ApplicationPermissionException) { logger.error(PluginCrowdClient.APPLICATION_PERMISSIONS_MESSAGE, e) } catch (e: InvalidAuthenticationException) { logger.error(PluginCrowdClient.INVALID_AUTHENTICATION_MESSAGE, e) } catch (e: OperationFailedException) { logger.error(PluginCrowdClient.OPERATION_FAILED_MESSAGE, e) } catch (e: Exception) { logger.error(PluginCrowdClient.UNKNOWN_ERROR_MESSAGE, e) } return null } override fun getUserGroups(username: String): Collection<Group> { try { return crowdClient.getGroupsForUser(username, 0, Integer.MAX_VALUE) } catch (e: UserNotFoundException) { logger.warn("User with name [$username] doesn't exists.", e) } catch (e: OperationFailedException) { logger.error(PluginCrowdClient.OPERATION_FAILED_MESSAGE, e) } catch (e: InvalidAuthenticationException) { logger.error(PluginCrowdClient.INVALID_AUTHENTICATION_MESSAGE, e) } catch (e: ApplicationPermissionException) { logger.error(PluginCrowdClient.APPLICATION_PERMISSIONS_MESSAGE, e) } catch (e: RuntimeException) { logger.error(PluginCrowdClient.UNKNOWN_ERROR_MESSAGE, e) } return emptyList() } }
gpl-3.0
5a98e9b8a4d4a003808a31dcd16a2f4c
45.105263
130
0.720525
4.899301
false
false
false
false
Andr3Carvalh0/mGBA
app/src/main/java/io/mgba/data/local/daos/GameDAO.kt
1
1212
package io.mgba.data.local.daos import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import io.mgba.data.local.model.Game @Dao interface GameDAO { @Insert(onConflict = OnConflictStrategy.REPLACE) @Transaction fun insert(game: Game) @Update @Transaction fun update(game: Game) @Delete @Transaction fun delete(games: Game) @Query("SELECT * FROM Games WHERE id = :game") fun get(game: String): Game @Query("DELETE FROM Games") @Transaction fun clearLibrary() @Query("SELECT * FROM Games WHERE name LIKE :query ORDER BY name") fun query(query: String): LiveData<List<Game>> @Query("SELECT * FROM Games WHERE favourite = 1 ORDER BY name") fun monitorFavouriteGames(): LiveData<List<Game>> @Query("SELECT * FROM Games WHERE platform = 1 ORDER BY name") fun monitorGameboyColorGames(): LiveData<List<Game>> @Query("SELECT * FROM Games WHERE platform = 2 ORDER BY name") fun monitorGameboyAdvancedGames(): LiveData<List<Game>> }
mpl-2.0
f86350e5fc71661aca453f10d8bee4cc
24.787234
70
0.718647
4.04
false
false
false
false
GoogleChromeLabs/android-web-payment
SamplePay/app/src/main/java/com/example/android/samplepay/PackageManagerUtils.kt
1
3762
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.samplepay import android.annotation.SuppressLint import android.app.Application import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.os.Build import java.security.MessageDigest /** * Parse Keystore fingerprint as a [ByteArray]. * * @param fingerprint The _SHA256_ fingerprint of the signing key. Bytes in 2-char hex expression * delimited with colons (e.g. * "F0:FD:6C:5B:41:0F:25:CB:25:C3:B5:33:46:C8:97:2F:AE:30:F8:EE:74:11:DF:91:04:80:AD:6B:2D:60:DB:83"). */ fun parseFingerprint(fingerprint: String): ByteArray { return fingerprint.split(":").map { it.toInt(16).toByte() }.toByteArray() } /** * Checks if the application specified with the [packageName] has the matching signing * [certificates]. * * @param packageName The package name. * @param certificates The signing certificates to be matched. */ fun PackageManager.hasSigningCertificates( packageName: String, certificates: Set<ByteArray> ): Boolean { return if (Build.VERSION.SDK_INT >= 28 && certificates.size == 1) { hasSigningCertificate(packageName, certificates.first(), PackageManager.CERT_INPUT_SHA256) } else { @SuppressLint("PackageManagerGetSignatures") @Suppress("DEPRECATION") val packageInfo = getPackageInfo(packageName, PackageManager.GET_SIGNATURES) val sha256 = MessageDigest.getInstance("SHA-256") @Suppress("DEPRECATION") val signatures = packageInfo.signatures.map { sha256.digest(it.toByteArray()) } // All the certificates have to match in case the APK is signed with multiple keys. signatures.size == certificates.size && signatures.all { s -> certificates.any { it.contentEquals(s) } } } } fun Application.authorizeCaller(packageName: String?): Boolean { return (packageName == "com.android.chrome" && packageManager.hasSigningCertificates( packageName, setOf(parseFingerprint(getString(R.string.chrome_stable_fingerprint))) )) || (packageName == "com.chrome.beta" && packageManager.hasSigningCertificates( packageName, setOf(parseFingerprint(getString(R.string.chrome_beta_fingerprint))) )) || (packageName == "com.chrome.dev" && packageManager.hasSigningCertificates( packageName, setOf(parseFingerprint(getString(R.string.chrome_dev_fingerprint))) )) || (packageName == "com.chrome.canary" && packageManager.hasSigningCertificates( packageName, setOf(parseFingerprint(getString(R.string.chrome_canary_fingerprint))) )) || (packageName == "org.chromium.chrome" && packageManager.hasSigningCertificates( packageName, setOf(parseFingerprint(getString(R.string.chromium_fingerprint))) )) } fun PackageManager.resolveServiceByFilter(intent: Intent): ResolveInfo? { return if (Build.VERSION.SDK_INT >= 33) { resolveService( intent, PackageManager.ResolveInfoFlags.of(PackageManager.GET_RESOLVED_FILTER.toLong()) ) } else { @Suppress("DEPRECATION") resolveService(intent, PackageManager.GET_RESOLVED_FILTER) } }
apache-2.0
16cd451fd0076d1593e23b0da48d7c50
40.8
102
0.717172
4.255656
false
false
false
false
matejdro/WearMusicCenter
mobile/src/main/java/com/matejdro/wearmusiccenter/view/actionlist/ActionListFragment.kt
1
10472
package com.matejdro.wearmusiccenter.view.actionlist import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.drawable.NinePatchDrawable import android.graphics.drawable.VectorDrawable import android.os.Bundle import android.os.PersistableBundle import android.os.Vibrator import android.provider.Settings import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.h6ah4i.android.widget.advrecyclerview.animator.DraggableItemAnimator import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange import com.h6ah4i.android.widget.advrecyclerview.draggable.RecyclerViewDragDropManager import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractDraggableItemViewHolder import com.matejdro.wearmusiccenter.R import com.matejdro.wearmusiccenter.actions.PhoneAction import com.matejdro.wearmusiccenter.config.CustomIconStorage import com.matejdro.wearmusiccenter.databinding.FragmentActionListBinding import com.matejdro.wearmusiccenter.di.InjectableViewModelFactory import com.matejdro.wearmusiccenter.util.IdentifiedItem import com.matejdro.wearmusiccenter.view.FabFragment import com.matejdro.wearmusiccenter.view.TitledActivity import com.matejdro.wearutils.miscutils.VibratorCompat import dagger.android.support.AndroidSupportInjection import javax.inject.Inject @SuppressLint("NotifyDataSetChanged") class ActionListFragment : Fragment(), FabFragment, RecyclerViewDragDropManager.OnItemDragEventListener { companion object { const val REQUEST_CODE_EDIT_WINDOW = 1031 private const val STATE_LAST_EDITED_ACTION_POSITION = "LastEditedActionPosition" } private val viewModel: ActionListViewModel by viewModels { viewModelFactory } private lateinit var binding: FragmentActionListBinding private lateinit var adapter: RecyclerView.Adapter<ListItemHolder> private lateinit var dragDropManager: RecyclerViewDragDropManager private lateinit var vibrator: Vibrator private var actions: List<IdentifiedItem<PhoneAction>> = emptyList() private var ignoreNextUpdate: Boolean = false private var lastEditedActionPosition = -1 @Inject lateinit var viewModelFactory: InjectableViewModelFactory<ActionListViewModel> @Inject lateinit var customIconStorage: CustomIconStorage override fun onCreate(savedInstanceState: Bundle?) { AndroidSupportInjection.inject(this) super.onCreate(savedInstanceState) if (savedInstanceState != null) { lastEditedActionPosition = savedInstanceState.getInt(STATE_LAST_EDITED_ACTION_POSITION) } vibrator = requireContext().getSystemService(Context.VIBRATOR_SERVICE) as Vibrator } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(STATE_LAST_EDITED_ACTION_POSITION, lastEditedActionPosition) super.onSaveInstanceState(outState) } override fun onStart() { super.onStart() val activity = activity if (activity is TitledActivity) { activity.updateActivityTitle(getString(R.string.actions_menu)) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = FragmentActionListBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recycler = binding.recycler dragDropManager = RecyclerViewDragDropManager() dragDropManager.setInitiateOnLongPress(true) dragDropManager.setInitiateOnMove(false) dragDropManager.setInitiateOnTouch(false) dragDropManager.onItemDragEventListener = this dragDropManager.setDraggingItemShadowDrawable(ResourcesCompat.getDrawable( resources, R.drawable.material_shadow_z3, null) as NinePatchDrawable) @Suppress("UNCHECKED_CAST") adapter = dragDropManager.createWrappedAdapter(ListItemAdapter()) as RecyclerView.Adapter<ListItemHolder> recycler.adapter = adapter recycler.itemAnimator = DraggableItemAnimator() recycler.layoutManager = LinearLayoutManager( context, LinearLayoutManager.VERTICAL, false ) recycler.addItemDecoration( DividerItemDecoration( context, DividerItemDecoration.VERTICAL ) ) dragDropManager.attachRecyclerView(recycler) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.actions.observe(viewLifecycleOwner, actionListListener) viewModel.openActionEditor.observe(viewLifecycleOwner, openEditDialogListener) } override fun onDestroy() { super.onDestroy() dragDropManager.release() } override fun onFabClicked() { val intent = Intent(context, ActionEditorActivity::class.java) startActivityForResult(intent, REQUEST_CODE_EDIT_WINDOW) } private val actionListListener = Observer<List<IdentifiedItem<PhoneAction>>> { if (it == null) { return@Observer } this.actions = it if (!ignoreNextUpdate) { adapter.notifyDataSetChanged() } ignoreNextUpdate = false } private val openEditDialogListener = Observer<Int?> { if (it == null || it < 0) { return@Observer } lastEditedActionPosition = it val intent = Intent(context, ActionEditorActivity::class.java) intent.putExtra(ActionEditorActivity.EXTRA_ACTION, actions[it].item.serialize()) startActivityForResult(intent, REQUEST_CODE_EDIT_WINDOW) } private fun buzz() { if (isHapticEnabled()) { VibratorCompat.vibrate(vibrator, 25) } } private fun isHapticEnabled(): Boolean { val contentResolver = requireActivity().contentResolver val setting = Settings.System.getInt(contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) return setting != 0 } override fun onItemDragStarted(position: Int) { buzz() } override fun onItemDragPositionChanged(fromPosition: Int, toPosition: Int) = Unit override fun onItemDragFinished(fromPosition: Int, toPosition: Int, result: Boolean) { buzz() } override fun onItemDragMoveDistanceUpdated(offsetX: Int, offsetY: Int) = Unit private inner class ListItemAdapter : RecyclerView.Adapter<ListItemHolder>(), DraggableItemAdapter<ListItemHolder> { init { setHasStableIds(true) } override fun onBindViewHolder(holder: ListItemHolder, position: Int) { val phoneAction = actions[position].item holder.text.text = phoneAction.title val icon = customIconStorage[phoneAction] if (icon is VectorDrawable) { holder.icon.setColorFilter(Color.BLACK) } else { holder.icon.clearColorFilter() } holder.icon.setImageDrawable(icon) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListItemHolder { val view = layoutInflater.inflate(R.layout.item_action_list, parent, false) return ListItemHolder(view) } override fun getItemCount(): Int = actions.size override fun getItemId(position: Int): Long = actions[position].id.toLong() override fun onGetItemDraggableRange(holder: ListItemHolder, position: Int): ItemDraggableRange? = null override fun onCheckCanDrop(draggingPosition: Int, dropPosition: Int): Boolean = true override fun onCheckCanStartDrag(holder: ListItemHolder, position: Int, x: Int, y: Int): Boolean { return true } override fun onMoveItem(fromPosition: Int, toPosition: Int) { ignoreNextUpdate = true viewModel.moveItem(fromPosition, toPosition) } override fun onItemDragStarted(position: Int) = Unit override fun onItemDragFinished(fromPosition: Int, toPosition: Int, result: Boolean) = Unit } private inner class ListItemHolder(itemView: View) : AbstractDraggableItemViewHolder(itemView) { val icon: ImageView = itemView.findViewById(R.id.icon) val text: TextView = itemView.findViewById(R.id.text) init { itemView.setOnClickListener { viewModel.editAction(adapterPosition) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_CODE_EDIT_WINDOW && resultCode == Activity.RESULT_OK && data != null) { if (data.getBooleanExtra(ActionEditorActivity.EXTRA_DELETING, false) && lastEditedActionPosition >= 0) { viewModel.deleteAction(lastEditedActionPosition) lastEditedActionPosition = -1 return } val actionBundle = data.getParcelableExtra<PersistableBundle>( ActionEditorActivity.EXTRA_ACTION) ?: return val newAction = PhoneAction.deserialize<PhoneAction>(requireContext(), actionBundle) ?: return if (lastEditedActionPosition < 0) { viewModel.addAction(newAction) } else { viewModel.actionEditFinished(newAction, lastEditedActionPosition) } lastEditedActionPosition = -1 } super.onActivityResult(requestCode, resultCode, data) } }
gpl-3.0
e5c05244e1ec9eb05abc26351524a0f3
35.361111
116
0.699962
5.386831
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/page/references/PageReferences.kt
1
463
package org.wikipedia.page.references import kotlinx.serialization.Serializable @Serializable class PageReferences(val selectedIndex: Int = 0, val tid: String? = null, val referencesGroup: List<Reference> = emptyList()) { @Serializable class Reference(val id: String? = null, val href: String? = null, val text: String = "", val html: String = "") }
apache-2.0
73515fcb0d512d198116fe151bae480f
29.866667
74
0.565875
4.873684
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/api/io/Domain.kt
1
4986
package pl.wendigo.chrome.api.io import kotlinx.serialization.json.Json /** * Input/Output operations for streams produced by DevTools. * * @link Protocol [IO](https://chromedevtools.github.io/devtools-protocol/tot/IO) domain documentation. */ class IODomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) : pl.wendigo.chrome.protocol.Domain("IO", """Input/Output operations for streams produced by DevTools.""", connection) { /** * Close the stream, discard any temporary backing storage. * * @link Protocol [IO#close](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-close) method documentation. */ fun close(input: CloseRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("IO.close", Json.encodeToJsonElement(CloseRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Read a chunk of the stream * * @link Protocol [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) method documentation. */ fun read(input: ReadRequest): io.reactivex.rxjava3.core.Single<ReadResponse> = connection.request("IO.read", Json.encodeToJsonElement(ReadRequest.serializer(), input), ReadResponse.serializer()) /** * Return UUID of Blob object specified by a remote object id. * * @link Protocol [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) method documentation. */ fun resolveBlob(input: ResolveBlobRequest): io.reactivex.rxjava3.core.Single<ResolveBlobResponse> = connection.request("IO.resolveBlob", Json.encodeToJsonElement(ResolveBlobRequest.serializer(), input), ResolveBlobResponse.serializer()) } /** * Represents request frame that can be used with [IO#close](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-close) operation call. * * Close the stream, discard any temporary backing storage. * @link [IO#close](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-close) method documentation. * @see [IODomain.close] */ @kotlinx.serialization.Serializable data class CloseRequest( /** * Handle of the stream to close. */ val handle: StreamHandle ) /** * Represents request frame that can be used with [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) operation call. * * Read a chunk of the stream * @link [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) method documentation. * @see [IODomain.read] */ @kotlinx.serialization.Serializable data class ReadRequest( /** * Handle of the stream to read. */ val handle: StreamHandle, /** * Seek to the specified offset before reading (if not specificed, proceed with offset following the last read). Some types of streams may only support sequential reads. */ val offset: Int? = null, /** * Maximum number of bytes to read (left upon the agent discretion if not specified). */ val size: Int? = null ) /** * Represents response frame that is returned from [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) operation call. * Read a chunk of the stream * * @link [IO#read](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read) method documentation. * @see [IODomain.read] */ @kotlinx.serialization.Serializable data class ReadResponse( /** * Set if the data is base64-encoded */ val base64Encoded: Boolean? = null, /** * Data that were read. */ val data: String, /** * Set if the end-of-file condition occured while reading. */ val eof: Boolean ) /** * Represents request frame that can be used with [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) operation call. * * Return UUID of Blob object specified by a remote object id. * @link [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) method documentation. * @see [IODomain.resolveBlob] */ @kotlinx.serialization.Serializable data class ResolveBlobRequest( /** * Object id of a Blob object wrapper. */ val objectId: pl.wendigo.chrome.api.runtime.RemoteObjectId ) /** * Represents response frame that is returned from [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) operation call. * Return UUID of Blob object specified by a remote object id. * * @link [IO#resolveBlob](https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob) method documentation. * @see [IODomain.resolveBlob] */ @kotlinx.serialization.Serializable data class ResolveBlobResponse( /** * UUID of the specified Blob. */ val uuid: String )
apache-2.0
29bdb804a0744a3805a1add63a4fa048
34.870504
292
0.718813
4.040519
false
false
false
false
JoachimR/Bible2net
app/src/main/java/de/reiss/bible2net/theword/note/export/NoteExportActivity.kt
1
1248
package de.reiss.bible2net.theword.note.export import android.content.Context import android.content.Intent import android.os.Bundle import de.reiss.bible2net.theword.R import de.reiss.bible2net.theword.architecture.AppActivity import de.reiss.bible2net.theword.databinding.NoteExportActivityBinding import de.reiss.bible2net.theword.util.extensions.findFragmentIn import de.reiss.bible2net.theword.util.extensions.replaceFragmentIn class NoteExportActivity : AppActivity() { companion object { fun createIntent(context: Context): Intent = Intent(context, NoteExportActivity::class.java) } private lateinit var binding: NoteExportActivityBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = NoteExportActivityBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.noteExportToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) if (findFragmentIn(R.id.note_export_fragment) == null) { replaceFragmentIn( container = R.id.note_export_fragment, fragment = NoteExportFragment.createInstance() ) } } }
gpl-3.0
73e13ba809a383a5d0c48a4aaa247d5f
34.657143
71
0.737179
4.709434
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solvingAssistant/LastDigit.kt
1
1668
package de.sudoq.model.solvingAssistant import de.sudoq.model.sudoku.Position import de.sudoq.model.sudoku.Sudoku import java.util.* //TODO make an optional<SolveAction> object LastDigit { fun findOne(sudoku: Sudoku): SolveAction? { /* for every constraint */ for (c in sudoku.sudokuType!!) if (c.hasUniqueBehavior()) { val v = Vector<Position>() for (p in c.getPositions()) if (sudoku.getCell(p)!!.isNotSolved) v.add(p) if (v.size == 1) { /* We found an instance where only one field is empty */ // val solutionField = v[0] //position that needs to be filled //make List with all values entered in this constraint val otherSolutions: MutableList<Int> = ArrayList() for (p in c.getPositions()) if (p !== solutionField) otherSolutions.add( sudoku.getCell( p )!!.currentValue ) //make list with all possible values val possibleSolutions: MutableList<Int> = ArrayList() for (i in sudoku.sudokuType!!.symbolIterator) possibleSolutions.add(i) /* cut away all other solutions */possibleSolutions.removeAll(otherSolutions) if (possibleSolutions.size == 1) { /* only one solution remains -> there were no doubles */ val solutionValue = possibleSolutions[0] return SolveActionLastDigit(solutionField, solutionValue, c.getPositions()) } } } return null } }
gpl-3.0
b488faba7fdcf8d9b3bc3eafb7a1bd2b
42.921053
95
0.56295
4.862974
false
false
false
false
google/dokka
core/src/main/kotlin/Analysis/CoreProjectFileIndex.kt
1
18950
package org.jetbrains.dokka import com.intellij.openapi.Disposable import com.intellij.openapi.components.BaseComponent import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkAdditionalData import com.intellij.openapi.projectRoots.SdkModificator import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.ProjectOrderEnumerator import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileFilter import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.messages.MessageBus import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.kotlin.cli.common.config.ContentRoot import org.jetbrains.kotlin.cli.common.config.KotlinSourceRoot import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot import org.jetbrains.kotlin.cli.jvm.config.JvmContentRoot import org.picocontainer.PicoContainer import java.io.File /** * Workaround for the lack of ability to create a ProjectFileIndex implementation using only * classes from projectModel-{api,impl}. */ class CoreProjectFileIndex(private val project: Project, contentRoots: List<ContentRoot>) : ProjectFileIndex, ModuleFileIndex { override fun iterateContent(p0: ContentIterator, p1: VirtualFileFilter?): Boolean { throw UnsupportedOperationException() } override fun iterateContentUnderDirectory(p0: VirtualFile, p1: ContentIterator, p2: VirtualFileFilter?): Boolean { throw UnsupportedOperationException() } override fun isInLibrary(p0: VirtualFile): Boolean { throw UnsupportedOperationException() } val sourceRoots = contentRoots.filter { it !is JvmClasspathRoot } val classpathRoots = contentRoots.filterIsInstance<JvmClasspathRoot>() val module: Module = object : UserDataHolderBase(), Module { override fun isDisposed(): Boolean { throw UnsupportedOperationException() } override fun getOptionValue(p0: String): String? { throw UnsupportedOperationException() } override fun clearOption(p0: String) { throw UnsupportedOperationException() } override fun getName(): String = "<Dokka module>" override fun getModuleWithLibrariesScope(): GlobalSearchScope { throw UnsupportedOperationException() } override fun getModuleWithDependentsScope(): GlobalSearchScope { throw UnsupportedOperationException() } override fun getModuleContentScope(): GlobalSearchScope { throw UnsupportedOperationException() } override fun isLoaded(): Boolean { throw UnsupportedOperationException() } override fun setOption(p0: String, p1: String?) { throw UnsupportedOperationException() } override fun getModuleWithDependenciesScope(): GlobalSearchScope { throw UnsupportedOperationException() } override fun getModuleWithDependenciesAndLibrariesScope(p0: Boolean): GlobalSearchScope { throw UnsupportedOperationException() } override fun getProject(): Project = [email protected] override fun getModuleContentWithDependenciesScope(): GlobalSearchScope { throw UnsupportedOperationException() } override fun getModuleFilePath(): String { throw UnsupportedOperationException() } override fun getModuleTestsWithDependentsScope(): GlobalSearchScope { throw UnsupportedOperationException() } override fun getModuleScope(): GlobalSearchScope { throw UnsupportedOperationException() } override fun getModuleScope(p0: Boolean): GlobalSearchScope { throw UnsupportedOperationException() } override fun getModuleRuntimeScope(p0: Boolean): GlobalSearchScope { throw UnsupportedOperationException() } override fun getModuleFile(): VirtualFile? { throw UnsupportedOperationException() } override fun <T : Any?> getExtensions(p0: ExtensionPointName<T>): Array<out T> { throw UnsupportedOperationException() } override fun getComponent(p0: String): BaseComponent? { throw UnsupportedOperationException() } override fun <T : Any?> getComponent(p0: Class<T>, p1: T): T { throw UnsupportedOperationException() } override fun <T : Any?> getComponent(interfaceClass: Class<T>): T? { if (interfaceClass == ModuleRootManager::class.java) { return moduleRootManager as T } throw UnsupportedOperationException() } override fun getDisposed(): Condition<*> { throw UnsupportedOperationException() } override fun <T : Any?> getComponents(p0: Class<T>): Array<out T> { throw UnsupportedOperationException() } override fun getPicoContainer(): PicoContainer { throw UnsupportedOperationException() } override fun hasComponent(p0: Class<*>): Boolean { throw UnsupportedOperationException() } override fun getMessageBus(): MessageBus { throw UnsupportedOperationException() } override fun dispose() { throw UnsupportedOperationException() } } private val sdk: Sdk = object : Sdk, RootProvider { override fun getFiles(rootType: OrderRootType): Array<out VirtualFile> = classpathRoots .map { StandardFileSystems.local().findFileByPath(it.file.path) } .filterNotNull() .toTypedArray() override fun addRootSetChangedListener(p0: RootProvider.RootSetChangedListener) { throw UnsupportedOperationException() } override fun addRootSetChangedListener(p0: RootProvider.RootSetChangedListener, p1: Disposable) { throw UnsupportedOperationException() } override fun getUrls(p0: OrderRootType): Array<out String> { throw UnsupportedOperationException() } override fun removeRootSetChangedListener(p0: RootProvider.RootSetChangedListener) { throw UnsupportedOperationException() } override fun getSdkModificator(): SdkModificator { throw UnsupportedOperationException() } override fun getName(): String = "<dokka SDK>" override fun getRootProvider(): RootProvider = this override fun getHomePath(): String? { throw UnsupportedOperationException() } override fun getVersionString(): String? { throw UnsupportedOperationException() } override fun getSdkAdditionalData(): SdkAdditionalData? { throw UnsupportedOperationException() } override fun clone(): Any { throw UnsupportedOperationException() } override fun getSdkType(): SdkTypeId { throw UnsupportedOperationException() } override fun getHomeDirectory(): VirtualFile? { throw UnsupportedOperationException() } override fun <T : Any?> getUserData(p0: Key<T>): T? { throw UnsupportedOperationException() } override fun <T : Any?> putUserData(p0: Key<T>, p1: T?) { throw UnsupportedOperationException() } } private val moduleSourceOrderEntry = object : ModuleSourceOrderEntry { override fun getFiles(p0: OrderRootType): Array<VirtualFile> { throw UnsupportedOperationException() } override fun getUrls(p0: OrderRootType): Array<String> { throw UnsupportedOperationException() } override fun <R : Any?> accept(p0: RootPolicy<R>, p1: R?): R { throw UnsupportedOperationException() } override fun getPresentableName(): String { throw UnsupportedOperationException() } override fun getOwnerModule(): Module = module override fun isValid(): Boolean { throw UnsupportedOperationException() } override fun compareTo(other: OrderEntry?): Int { throw UnsupportedOperationException() } override fun getRootModel(): ModuleRootModel = moduleRootManager override fun isSynthetic(): Boolean { throw UnsupportedOperationException() } } private val sdkOrderEntry = object : JdkOrderEntry { override fun getFiles(p0: OrderRootType): Array<VirtualFile> { throw UnsupportedOperationException() } override fun getUrls(p0: OrderRootType): Array<String> { throw UnsupportedOperationException() } override fun <R : Any?> accept(p0: RootPolicy<R>, p1: R?): R { throw UnsupportedOperationException() } override fun getJdkName(): String? { throw UnsupportedOperationException() } override fun getJdk(): Sdk = sdk override fun getPresentableName(): String { throw UnsupportedOperationException() } override fun getOwnerModule(): Module { throw UnsupportedOperationException() } override fun isValid(): Boolean { throw UnsupportedOperationException() } override fun getRootFiles(p0: OrderRootType): Array<out VirtualFile> { throw UnsupportedOperationException() } override fun getRootUrls(p0: OrderRootType): Array<out String> { throw UnsupportedOperationException() } override fun compareTo(other: OrderEntry?): Int { throw UnsupportedOperationException() } override fun isSynthetic(): Boolean { throw UnsupportedOperationException() } } inner class MyModuleRootManager : ModuleRootManager() { override fun getExternalSource(): ProjectModelExternalSource? { throw UnsupportedOperationException() } override fun getExcludeRoots(): Array<out VirtualFile> { throw UnsupportedOperationException() } override fun getContentEntries(): Array<out ContentEntry> { throw UnsupportedOperationException() } override fun getExcludeRootUrls(): Array<out String> { throw UnsupportedOperationException() } override fun <R : Any?> processOrder(p0: RootPolicy<R>?, p1: R): R { throw UnsupportedOperationException() } override fun getSourceRoots(p0: Boolean): Array<out VirtualFile> { throw UnsupportedOperationException() } override fun getSourceRoots(): Array<out VirtualFile> { throw UnsupportedOperationException() } override fun getSourceRoots(p0: JpsModuleSourceRootType<*>): MutableList<VirtualFile> { throw UnsupportedOperationException() } override fun getSourceRoots(p0: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> { throw UnsupportedOperationException() } override fun getContentRoots(): Array<out VirtualFile> { throw UnsupportedOperationException() } override fun orderEntries(): OrderEnumerator = ProjectOrderEnumerator(project, null).using(object : RootModelProvider { override fun getModules(): Array<out Module> = arrayOf(module) override fun getRootModel(p0: Module): ModuleRootModel = this@MyModuleRootManager }) override fun <T : Any?> getModuleExtension(p0: Class<T>): T { throw UnsupportedOperationException() } override fun getDependencyModuleNames(): Array<out String> { throw UnsupportedOperationException() } override fun getModule(): Module = [email protected] override fun isSdkInherited(): Boolean { throw UnsupportedOperationException() } override fun getOrderEntries(): Array<out OrderEntry> = arrayOf(moduleSourceOrderEntry, sdkOrderEntry) override fun getSourceRootUrls(): Array<out String> { throw UnsupportedOperationException() } override fun getSourceRootUrls(p0: Boolean): Array<out String> { throw UnsupportedOperationException() } override fun getSdk(): Sdk? { throw UnsupportedOperationException() } override fun getContentRootUrls(): Array<out String> { throw UnsupportedOperationException() } override fun getModuleDependencies(): Array<out Module> { throw UnsupportedOperationException() } override fun getModuleDependencies(p0: Boolean): Array<out Module> { throw UnsupportedOperationException() } override fun getModifiableModel(): ModifiableRootModel { throw UnsupportedOperationException() } override fun isDependsOn(p0: Module?): Boolean { throw UnsupportedOperationException() } override fun getFileIndex(): ModuleFileIndex { return this@CoreProjectFileIndex } override fun getDependencies(): Array<out Module> { throw UnsupportedOperationException() } override fun getDependencies(p0: Boolean): Array<out Module> { throw UnsupportedOperationException() } } val moduleRootManager = MyModuleRootManager() override fun getContentRootForFile(p0: VirtualFile): VirtualFile? { throw UnsupportedOperationException() } override fun getContentRootForFile(p0: VirtualFile, p1: Boolean): VirtualFile? { throw UnsupportedOperationException() } override fun getPackageNameByDirectory(p0: VirtualFile): String? { throw UnsupportedOperationException() } override fun isInLibrarySource(file: VirtualFile): Boolean = false override fun getClassRootForFile(file: VirtualFile): VirtualFile? = classpathRoots.firstOrNull { it.contains(file) }?.let { StandardFileSystems.local().findFileByPath(it.file.path) } override fun getOrderEntriesForFile(file: VirtualFile): List<OrderEntry> = if (classpathRoots.contains(file)) listOf(sdkOrderEntry) else emptyList() override fun isInLibraryClasses(file: VirtualFile): Boolean = classpathRoots.contains(file) override fun isExcluded(p0: VirtualFile): Boolean { throw UnsupportedOperationException() } override fun getSourceRootForFile(p0: VirtualFile): VirtualFile? { throw UnsupportedOperationException() } override fun isUnderIgnored(p0: VirtualFile): Boolean { throw UnsupportedOperationException() } override fun isLibraryClassFile(p0: VirtualFile): Boolean { throw UnsupportedOperationException() } override fun getModuleForFile(file: VirtualFile): Module? = if (sourceRoots.contains(file)) module else null private fun List<ContentRoot>.contains(file: VirtualFile): Boolean = any { it.contains(file) } override fun getModuleForFile(p0: VirtualFile, p1: Boolean): Module? { throw UnsupportedOperationException() } override fun isInSource(p0: VirtualFile): Boolean { throw UnsupportedOperationException() } override fun isIgnored(p0: VirtualFile): Boolean { throw UnsupportedOperationException() } override fun isContentSourceFile(p0: VirtualFile): Boolean { throw UnsupportedOperationException() } override fun isInSourceContent(file: VirtualFile): Boolean = sourceRoots.contains(file) override fun iterateContent(p0: ContentIterator): Boolean { throw UnsupportedOperationException() } override fun isInContent(p0: VirtualFile): Boolean { throw UnsupportedOperationException() } override fun iterateContentUnderDirectory(p0: VirtualFile, p1: ContentIterator): Boolean { throw UnsupportedOperationException() } override fun isInTestSourceContent(file: VirtualFile): Boolean = false override fun isUnderSourceRootOfType(p0: VirtualFile, p1: MutableSet<out JpsModuleSourceRootType<*>>): Boolean { throw UnsupportedOperationException() } override fun getOrderEntryForFile(p0: VirtualFile): OrderEntry? { throw UnsupportedOperationException() } } class CoreProjectRootManager(val projectFileIndex: CoreProjectFileIndex) : ProjectRootManager() { override fun orderEntries(): OrderEnumerator { throw UnsupportedOperationException() } override fun orderEntries(p0: MutableCollection<out Module>): OrderEnumerator { throw UnsupportedOperationException() } override fun getContentRootsFromAllModules(): Array<out VirtualFile>? { throw UnsupportedOperationException() } override fun setProjectSdk(p0: Sdk?) { throw UnsupportedOperationException() } override fun setProjectSdkName(p0: String?) { throw UnsupportedOperationException() } override fun getModuleSourceRoots(p0: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> { throw UnsupportedOperationException() } override fun getContentSourceRoots(): Array<out VirtualFile> { throw UnsupportedOperationException() } override fun getFileIndex(): ProjectFileIndex = projectFileIndex override fun getProjectSdkName(): String? { throw UnsupportedOperationException() } override fun getProjectSdk(): Sdk? { throw UnsupportedOperationException() } override fun getContentRoots(): Array<out VirtualFile> { throw UnsupportedOperationException() } override fun getContentRootUrls(): MutableList<String> { throw UnsupportedOperationException() } } fun ContentRoot.contains(file: VirtualFile) = when (this) { is JvmContentRoot -> { val path = if (file.fileSystem.protocol == StandardFileSystems.JAR_PROTOCOL) StandardFileSystems.getVirtualFileForJar(file)?.path ?: file.path else file.path File(path).startsWith(this.file.absoluteFile) } is KotlinSourceRoot -> File(file.path).startsWith(File(this.path).absoluteFile) else -> false }
apache-2.0
cb4a733c0b597efd10c93304704e4dfc
32.304042
127
0.670607
6.091289
false
false
false
false