repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
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
programmerr47/ganalytics
ganalytics-core/src/test/java/com/github/programmerr47/ganalytics/core/WrapperTest.kt
1
1101
package com.github.programmerr47.ganalytics.core import org.junit.Assert import kotlin.reflect.KClass interface WrapperTest { val testProvider: TestEventProvider } inline fun <T : Any> WrapperTest.run(wrapper: AnalyticsWrapper, clazz: KClass<T>, block: T.() -> Unit) = wrapper.create(clazz).run(block) inline fun WrapperTest.assertEquals(event: Event, interfaceMethod: () -> Unit) { interfaceMethod() Assert.assertEquals(event, testProvider.lastEvent) } interface StableWrapperTest : WrapperTest { val wrapper: AnalyticsWrapper } inline fun <T : Any> StableWrapperTest.run(clazz: KClass<T>, block: T.() -> Unit) = run(wrapper, clazz, block) abstract class SingleWrapperTest : StableWrapperTest { override val testProvider: TestEventProvider = TestEventProvider() override val wrapper: AnalyticsSingleWrapper = AnalyticsSingleWrapper(testProvider) } abstract class GroupWrapperTest : StableWrapperTest { override val testProvider: TestEventProvider = TestEventProvider() override val wrapper: AnalyticsGroupWrapper = AnalyticsGroupWrapper(testProvider) }
mit
6837382b2218ca09ffa5b3de9603fbaf
33.4375
110
0.771117
4.439516
false
true
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/announcement/AnnouncementCardView.kt
1
5042
package org.wikipedia.feed.announcement import android.content.Context import android.net.Uri import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat import org.wikipedia.R import org.wikipedia.databinding.ViewCardAnnouncementBinding import org.wikipedia.feed.model.Card import org.wikipedia.feed.view.DefaultFeedCardView import org.wikipedia.richtext.RichTextUtil import org.wikipedia.util.DimenUtil import org.wikipedia.util.StringUtil class AnnouncementCardView(context: Context) : DefaultFeedCardView<AnnouncementCard>(context) { interface Callback { fun onAnnouncementPositiveAction(card: Card, uri: Uri) fun onAnnouncementNegativeAction(card: Card) } private val binding = ViewCardAnnouncementBinding.inflate(LayoutInflater.from(context), this, true) var localCallback: Callback? = null init { binding.viewAnnouncementText.movementMethod = LinkMovementMethod.getInstance() binding.viewAnnouncementFooterText.movementMethod = LinkMovementMethod.getInstance() binding.viewAnnouncementActionPositive.setOnClickListener { onPositiveActionClick() } binding.viewAnnouncementDialogActionPositive.setOnClickListener { onPositiveActionClick() } binding.viewAnnouncementActionNegative.setOnClickListener { onNegativeActionClick() } binding.viewAnnouncementDialogActionNegative.setOnClickListener { onNegativeActionClick() } } override var card: AnnouncementCard? = null set(value) { field = value value?.let { if (!it.extract().isNullOrEmpty()) { binding.viewAnnouncementText.text = StringUtil.fromHtml(it.extract()) } if (!it.hasAction()) { binding.viewAnnouncementCardButtonsContainer.visibility = GONE } else { binding.viewAnnouncementCardButtonsContainer.visibility = VISIBLE binding.viewAnnouncementActionPositive.text = it.actionTitle() binding.viewAnnouncementDialogActionPositive.text = it.actionTitle() } if (!it.negativeText().isNullOrEmpty()) { binding.viewAnnouncementActionNegative.text = it.negativeText() binding.viewAnnouncementDialogActionNegative.text = it.negativeText() } else { binding.viewAnnouncementActionNegative.visibility = GONE binding.viewAnnouncementDialogActionNegative.visibility = GONE } if (it.hasImage()) { binding.viewAnnouncementHeaderImage.visibility = VISIBLE binding.viewAnnouncementHeaderImage.loadImage(it.image()) } else { binding.viewAnnouncementHeaderImage.visibility = GONE } if (it.imageHeight() > 0) { val params = binding.viewAnnouncementHeaderImage.layoutParams as MarginLayoutParams params.height = DimenUtil.roundedDpToPx(it.imageHeight().toFloat()) binding.viewAnnouncementHeaderImage.layoutParams = params } if (it.hasFooterCaption()) { binding.viewAnnouncementFooterText.text = StringUtil.fromHtml(it.footerCaption()) RichTextUtil.removeUnderlinesFromLinks(binding.viewAnnouncementFooterText) } else { binding.viewAnnouncementFooterText.visibility = GONE binding.viewAnnouncementFooterBorder.visibility = GONE } if (it.hasBorder()) { binding.viewAnnouncementContainer.strokeColor = ContextCompat.getColor(context, R.color.red30) binding.viewAnnouncementContainer.strokeWidth = 10 } else { binding.viewAnnouncementContainer.setDefaultBorder() } if (it.isArticlePlacement) { binding.viewAnnouncementCardButtonsContainer.visibility = GONE binding.viewAnnouncementCardDialogButtonsContainer.visibility = VISIBLE binding.viewAnnouncementContainer.layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) binding.viewAnnouncementContainer.radius = 0f } } } private fun onPositiveActionClick() { card?.let { callback?.onAnnouncementPositiveAction(it, it.actionUri()) localCallback?.onAnnouncementPositiveAction(it, it.actionUri()) } } private fun onNegativeActionClick() { card?.let { callback?.onAnnouncementNegativeAction(it) localCallback?.onAnnouncementNegativeAction(it) } } }
apache-2.0
c8f2f44d88f8dbc2f84b91d8820b4dfe
47.019048
114
0.645775
6.178922
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantElvisReturnNullInspection.kt
1
2673
// 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.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset class RedundantElvisReturnNullInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return returnExpressionVisitor(fun(returnExpression: KtReturnExpression) { if ((returnExpression.returnedExpression?.deparenthesize() as? KtConstantExpression)?.text != KtTokens.NULL_KEYWORD.value) return val binaryExpression = returnExpression.getStrictParentOfType<KtBinaryExpression>()?.takeIf { it == it.getStrictParentOfType<KtReturnExpression>()?.returnedExpression?.deparenthesize() } ?: return val right = binaryExpression.right?.deparenthesize()?.takeIf { it == returnExpression } ?: return if (binaryExpression.operationToken == KtTokens.ELSE_KEYWORD) return if (binaryExpression.left?.resolveToCall()?.resultingDescriptor?.returnType?.isMarkedNullable != true) return holder.registerProblem( binaryExpression, KotlinBundle.message("inspection.redundant.elvis.return.null.descriptor"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, TextRange(binaryExpression.operationReference.startOffset, right.endOffset).shiftLeft(binaryExpression.startOffset), RemoveRedundantElvisReturnNull() ) }) } private fun KtExpression.deparenthesize() = KtPsiUtil.deparenthesize(this) private class RemoveRedundantElvisReturnNull : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.redundant.elvis.return.null.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val binaryExpression = descriptor.psiElement as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return binaryExpression.replace(left) } } }
apache-2.0
f4d5e3d0405c108bc243a13138b4e02d
50.403846
141
0.738122
5.639241
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/KotlinVersionUtils.kt
2
7593
// 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. @file:JvmName("KotlinVersionUtils") @file:Suppress("deprecation_error") package org.jetbrains.kotlin.idea.codeInsight.gradle import org.jetbrains.kotlin.idea.codeInsight.gradle.GradleKotlinTestUtils.KotlinVersion import org.jetbrains.kotlin.idea.codeInsight.gradle.MultiplePluginVersionGradleImportingTestCase.KotlinVersionRequirement import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion import java.util.* import kotlin.Comparator val KotlinVersion.isWildcard: Boolean get() = this.classifier != null && this.classifier == WILDCARD_KOTLIN_VERSION_CLASSIFIER val KotlinVersion.isSnapshot: Boolean get() = this.classifier != null && this.classifier.lowercase() == "snapshot" val KotlinVersion.isDev: Boolean get() = this.classifier != null && this.classifier.lowercase().matches(Regex("""dev-?\d*""")) val KotlinVersion.isMilestone: Boolean get() = this.classifier != null && this.classifier.lowercase().matches(Regex("""m\d+(-release)?(-\d*)?""")) val KotlinVersion.isAlpha: Boolean get() = this.classifier != null && this.classifier.lowercase().matches(Regex("""alpha(\d*)?(-release)?-?\d*""")) val KotlinVersion.isBeta: Boolean get() = this.classifier != null && this.classifier.lowercase().matches(Regex("""beta(\d*)?(-release)?-?\d*""")) val KotlinVersion.isRC: Boolean get() = this.classifier != null && this.classifier.lowercase().matches(Regex("""(rc)(\d*)?(-release)?-?\d*""")) val KotlinVersion.isStable: Boolean get() = this.classifier == null || this.classifier.lowercase().matches(Regex("""(release-)?\d+""")) val KotlinVersion.isPreRelease: Boolean get() = !isStable enum class KotlinVersionMaturity { WILDCARD, SNAPSHOT, DEV, MILESTONE, ALPHA, BETA, RC, STABLE } operator fun KotlinVersion.compareTo(other: KotlinVersion): Int { if (this == other) return 0 (this.major - other.major).takeIf { it != 0 }?.let { return it } (this.minor - other.minor).takeIf { it != 0 }?.let { return it } (this.patch - other.patch).takeIf { it != 0 }?.let { return it } (this.maturity.ordinal - other.maturity.ordinal).takeIf { it != 0 }?.let { return it } if (this.classifier == null && other.classifier != null) { /* eg. 1.6.20 > 1.6.20-200 */ return 1 } if (this.classifier != null && other.classifier == null) { /* e.g. 1.6.20-200 < 1.6.20 */ return -1 } val thisClassifierNumber = this.classifierNumber val otherClassifierNumber = other.classifierNumber if (thisClassifierNumber != null && otherClassifierNumber != null) { (thisClassifierNumber - otherClassifierNumber).takeIf { it != 0 }?.let { return it } } if (thisClassifierNumber != null && otherClassifierNumber == null) { /* e.g. 1.6.20-rc1 > 1.6.20-rc */ return 1 } if (thisClassifierNumber == null && otherClassifierNumber != null) { /* e.g. 1.6.20-rc < 1.6.20-rc1 */ return -1 } val thisBuildNumber = this.buildNumber val otherBuildNumber = other.buildNumber if (thisBuildNumber != null && otherBuildNumber != null) { (thisBuildNumber - otherBuildNumber).takeIf { it != 0 }?.let { return it } } if (thisBuildNumber == null && otherBuildNumber != null) { /* e.g. 1.6.20-M1 > 1.6.20-M1-200 */ return 1 } if (thisBuildNumber != null && otherBuildNumber == null) { /* e.g. 1.6.20-M1-200 < 1.6.20-M1 */ return -1 } return 0 } val KotlinVersion.buildNumber: Int? get() { if (classifier == null) return null /* Handle classifiers that only consist of version + build number. This is used for stable releases like: 1.6.20-1 1.6.20-22 1.6. */ val buildNumberOnlyClassifierRegex = Regex("\\d+") if (buildNumberOnlyClassifierRegex.matches(classifier)) { return classifier.toIntOrNull() } val classifierRegex = Regex("""(.+?)(\d*)?-?(\d*)?""") val classifierMatch = classifierRegex.matchEntire(classifier) ?: return null return classifierMatch.groupValues.getOrNull(3)?.toIntOrNull() } val KotlinVersion.classifierNumber: Int? get() { if (classifier == null) return null /* Classifiers with only a buildNumber assigned */ val buildNumberOnlyClassifierRegex = Regex("\\d+") if (buildNumberOnlyClassifierRegex.matches(classifier)) { return null } val classifierRegex = Regex("""(.+?)(\d*)?-?(\d*)?""") val classifierMatch = classifierRegex.matchEntire(classifier) ?: return null return classifierMatch.groupValues.getOrNull(2)?.toIntOrNull() } fun KotlinVersionRequirement.matches(kotlinVersionString: String): Boolean { return matches(KotlinToolingVersion(kotlinVersionString)) } fun KotlinVersionRequirement.matches(version: KotlinToolingVersion): Boolean { return when (this) { is KotlinVersionRequirement.Exact -> matches(version) is KotlinVersionRequirement.Range -> matches(version) } } fun KotlinVersionRequirement.Exact.matches(version: KotlinToolingVersion): Boolean { return this.version.compareTo(version) == 0 } fun KotlinVersionRequirement.Range.matches(version: KotlinToolingVersion): Boolean { if (lowestIncludedVersion != null && version < lowestIncludedVersion) return false if (highestIncludedVersion != null && version > highestIncludedVersion) return false return true } fun parseKotlinVersionRequirement(value: String): KotlinVersionRequirement { if (value.endsWith("+")) { return KotlinVersionRequirement.Range( lowestIncludedVersion = KotlinToolingVersion(value.removeSuffix("+")), highestIncludedVersion = null ) } if (value.contains("<=>")) { val split = value.split(Regex("""\s*<=>\s*""")) require(split.size == 2) { "Illegal Kotlin version requirement: $value. Example: '1.4.0 <=> 1.5.0'" } return KotlinVersionRequirement.Range( lowestIncludedVersion = KotlinToolingVersion(split[0]), highestIncludedVersion = KotlinToolingVersion(split[1]) ) } return KotlinVersionRequirement.Exact(KotlinToolingVersion(value)) } fun parseKotlinVersion(value: String): KotlinVersion { fun throwInvalid(): Nothing { throw IllegalArgumentException("Invalid Kotlin version: $value") } val baseVersion = value.split("-", limit = 2)[0] val classifier = value.split("-", limit = 2).getOrNull(1) val baseVersionSplit = baseVersion.split(".") if (!(baseVersionSplit.size == 2 || baseVersionSplit.size == 3)) throwInvalid() return KotlinVersion( major = baseVersionSplit[0].toIntOrNull() ?: throwInvalid(), minor = baseVersionSplit[1].toIntOrNull() ?: throwInvalid(), patch = baseVersionSplit.getOrNull(2)?.let { it.toIntOrNull() ?: throwInvalid() } ?: 0, classifier = classifier ) } private const val WILDCARD_KOTLIN_VERSION_CLASSIFIER = "*" fun KotlinVersion.toWildcard(): KotlinVersion { return KotlinVersion( major, minor, patch, classifier = WILDCARD_KOTLIN_VERSION_CLASSIFIER ) } val KotlinToolingVersion.isHmppEnabledByDefault get() = this >= KotlinToolingVersion("1.6.20-dev-6442")
apache-2.0
8026c1f0fd1a022161acb57e6d8f826c
34.152778
158
0.655604
4.396642
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveMethod/MoveKotlinMethodHandler.kt
4
6532
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.moveMethod import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.MoveHandlerDelegate import com.intellij.refactoring.util.CommonRefactoringUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral private const val optionName = "kotlin.enable.move.method.refactoring" private val refactoringIsDisabled: Boolean get() = !Registry.`is`(optionName) && !isUnitTestMode() class MoveKotlinMethodHandler : MoveHandlerDelegate() { private fun showErrorHint(project: Project, dataContext: DataContext?, @Nls message: String) { val editor = dataContext?.let { CommonDataKeys.EDITOR.getData(it) } CommonRefactoringUtil.showErrorHint(project, editor, message, KotlinBundle.message("title.move.method"), null) } private fun invokeMoveMethodRefactoring( project: Project, method: KtNamedFunction, targetContainer: KtClassOrObject?, dataContext: DataContext? ) { if (method.containingClassOrObject == null) return val errorMessageKey = when { !method.manager.isInProject(method) -> "text.move.method.is.not.supported.for.non.project.methods" method.mentionsTypeParameters() -> "text.move.method.is.not.supported.for.generic.classes" method.hasModifier(KtTokens.OVERRIDE_KEYWORD) || method.hasModifier(KtTokens.OPEN_KEYWORD) -> "text.move.method.is.not.supported.when.method.is.a.part.of.inheritance.hierarchy" else -> null } if (errorMessageKey != null) { showErrorHint(project, dataContext, KotlinBundle.message(errorMessageKey)) return } MoveKotlinMethodDialog( method, collectSuitableVariables(method), targetContainer ).show() } private fun collectSuitableVariables(method: KtNamedFunction): Map<KtNamedDeclaration, KtClass> { val sourceClassOrObject = method.containingClassOrObject ?: return emptyMap() val allVariables = mutableListOf<KtNamedDeclaration>() allVariables.addAll(method.valueParameters) allVariables.addAll(sourceClassOrObject.declarations.filterIsInstance<KtProperty>()) allVariables.addAll(sourceClassOrObject.primaryConstructorParameters.filter { parameter -> parameter.hasValOrVar() }) val variableToClassMap = LinkedHashMap<KtNamedDeclaration, KtClass>() for (variable in allVariables) { variable.type()?.let { type -> if (type.arguments.isEmpty()) { val ktClass = type.constructor.declarationDescriptor?.findPsi() as? KtClass if (ktClass != null && method.manager.isInProject(ktClass)) { variableToClassMap[variable] = ktClass } } } } return variableToClassMap } override fun canMove(elements: Array<PsiElement?>, targetContainer: PsiElement?, reference: PsiReference?): Boolean { if (refactoringIsDisabled) return false if (elements.size != 1) return false val method = elements[0] as? KtNamedFunction ?: return false val sourceContainer = method.containingClassOrObject return (targetContainer == null || super.canMove(elements, targetContainer, reference)) && sourceContainer != null && !sourceContainer.isObjectLiteral() } override fun isValidTarget(psiElement: PsiElement?, sources: Array<out PsiElement>): Boolean { if (refactoringIsDisabled) return false return psiElement is KtClassOrObject && !psiElement.hasModifier(KtTokens.ANNOTATION_KEYWORD) } override fun doMove(project: Project, elements: Array<out PsiElement>, targetContainer: PsiElement?, callback: MoveCallback?) { if (refactoringIsDisabled) return if (elements.size != 1) return val method = elements[0] as? KtNamedFunction ?: return val sourceContainer = method.containingClassOrObject if (sourceContainer == null || sourceContainer.isObjectLiteral()) return invokeMoveMethodRefactoring(project, elements[0] as KtNamedFunction, targetContainer as? KtClassOrObject, null) } override fun tryToMove( element: PsiElement, project: Project, dataContext: DataContext?, reference: PsiReference?, editor: Editor? ): Boolean { if (refactoringIsDisabled) return false if (element is KtNamedFunction) { element.containingClassOrObject?.let { sourceContainer -> if (!sourceContainer.isObjectLiteral()) { invokeMoveMethodRefactoring(project, element, null, dataContext) return true } } } return false } private fun KtNamedFunction.mentionsTypeParameters(): Boolean { var ktClassOrObject = containingClassOrObject val typeParameters = mutableListOf<KtTypeParameter>() while (ktClassOrObject != null) { typeParameters.addAll(ktClassOrObject.typeParameters) ktClassOrObject = if (ktClassOrObject.hasModifier(KtTokens.INNER_KEYWORD)) ktClassOrObject.containingClassOrObject else null } return collectDescendantsOfType<KtUserType>().any { userType -> userType.referenceExpression?.mainReference?.resolve() in typeParameters } } override fun getActionName(elements: Array<out PsiElement>): String = KotlinBundle.message("action.move.method") }
apache-2.0
ec106a924a8a14db88e0dc0f6c6a9ac2
47.029412
158
0.706981
5.327896
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/imports/KotlinImportOptimizer.kt
2
14997
// 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.imports import com.intellij.lang.ImportOptimizer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.references.fe10.Fe10SyntheticPropertyAccessorReference import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings import org.jetbrains.kotlin.idea.references.* import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope import org.jetbrains.kotlin.resolve.scopes.utils.* import org.jetbrains.kotlin.types.error.ErrorFunctionDescriptor class KotlinImportOptimizer : ImportOptimizer { override fun supports(file: PsiFile) = file is KtFile override fun processFile(file: PsiFile): ImportOptimizer.CollectingInfoRunnable { val ktFile = (file as? KtFile) ?: return DO_NOTHING val (add, remove, imports) = prepareImports(ktFile) ?: return DO_NOTHING return object : ImportOptimizer.CollectingInfoRunnable { override fun getUserNotificationInfo(): String = if (remove == 0) KotlinBundle.message("import.optimizer.text.zero") else KotlinBundle.message( "import.optimizer.text.non.zero", remove, KotlinBundle.message("import.optimizer.text.import", remove), add, KotlinBundle.message("import.optimizer.text.import", add) ) override fun run() = replaceImports(ktFile, imports) } } // The same as com.intellij.pom.core.impl.PomModelImpl.isDocumentUncommitted // Which is checked in com.intellij.pom.core.impl.PomModelImpl.startTransaction private val KtFile.isDocumentUncommitted: Boolean get() { val documentManager = PsiDocumentManager.getInstance(project) val cachedDocument = documentManager.getCachedDocument(this) return cachedDocument != null && documentManager.isUncommited(cachedDocument) } private fun prepareImports(file: KtFile): OptimizeInformation? { ApplicationManager.getApplication().assertReadAccessAllowed() // Optimize imports may be called after command // And document can be uncommitted after running that command // In that case we will get ISE: Attempt to modify PSI for non-committed Document! if (file.isDocumentUncommitted) return null val moduleInfo = file.moduleInfoOrNull if (moduleInfo !is ModuleSourceInfo && moduleInfo !is ScriptModuleInfo) return null val oldImports = file.importDirectives if (oldImports.isEmpty()) return null //TODO: keep existing imports? at least aliases (comments) val descriptorsToImport = collectDescriptorsToImport(file, true) val imports = prepareOptimizedImports(file, descriptorsToImport) ?: return null val intersect = imports.intersect(oldImports.map { it.importPath }) return OptimizeInformation( add = imports.size - intersect.size, remove = oldImports.size - intersect.size, imports = imports ) } private data class OptimizeInformation(val add: Int, val remove: Int, val imports: List<ImportPath>) private class CollectUsedDescriptorsVisitor(file: KtFile, val progressIndicator: ProgressIndicator? = null) : KtVisitorVoid() { //private val elementsSize: Int = if (progressIndicator != null) { // var size = 0 // file.accept(object : KtVisitorVoid() { // override fun visitElement(element: PsiElement) { // size += 1 // element.acceptChildren(this) // } // }) // // size //} else { // 0 //} private var elementProgress: Int = 0 private val currentPackageName = file.packageFqName private val aliases: Map<FqName, List<Name>> = file.importDirectives .asSequence() .filter { !it.isAllUnder && it.alias != null } .mapNotNull { it.importPath } .groupBy(keySelector = { it.fqName }, valueTransform = { it.importedName as Name }) private val descriptorsToImport = hashSetOf<OptimizedImportsBuilder.ImportableDescriptor>() private val namesToImport = hashMapOf<FqName, MutableSet<Name>>() private val abstractRefs = ArrayList<OptimizedImportsBuilder.AbstractReference>() private val unresolvedNames = hashSetOf<Name>() val data: OptimizedImportsBuilder.InputData get() = OptimizedImportsBuilder.InputData( descriptorsToImport, namesToImport, abstractRefs, unresolvedNames, ) override fun visitElement(element: PsiElement) { ProgressIndicatorProvider.checkCanceled() elementProgress += 1 //progressIndicator?.apply { // if (elementsSize != 0) { // fraction = elementProgress / elementsSize.toDouble() // } //} element.acceptChildren(this) } override fun visitImportList(importList: KtImportList) { } override fun visitPackageDirective(directive: KtPackageDirective) { } override fun visitKtElement(element: KtElement) { super.visitKtElement(element) if (element is KtLabelReferenceExpression) return val references = element.references.ifEmpty { return } val bindingContext = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val isResolved = hasResolvedDescriptor(element, bindingContext) for (reference in references) { if (reference !is KtReference) continue ProgressIndicatorProvider.checkCanceled() abstractRefs.add(AbstractReferenceImpl(reference)) val names = reference.resolvesByNames if (!isResolved) { unresolvedNames += names } for (target in reference.targets(bindingContext)) { val importableDescriptor = target.getImportableDescriptor() val importableFqName = target.importableFqName ?: continue val parentFqName = importableFqName.parent() if (target is PackageViewDescriptor && parentFqName == FqName.ROOT) continue // no need to import top-level packages if (target !is PackageViewDescriptor && parentFqName == currentPackageName && (importableFqName !in aliases)) continue if (!reference.canBeResolvedViaImport(target, bindingContext)) continue if (importableDescriptor.name in names && isAccessibleAsMember(importableDescriptor, element, bindingContext)) { continue } val descriptorNames = (aliases[importableFqName].orEmpty() + importableFqName.shortName()).intersect(names) namesToImport.getOrPut(importableFqName) { hashSetOf() } += descriptorNames descriptorsToImport += OptimizedImportsBuilder.ImportableDescriptor(importableDescriptor, importableFqName) } } } private fun isAccessibleAsMember(target: DeclarationDescriptor, place: KtElement, bindingContext: BindingContext): Boolean { if (target.containingDeclaration !is ClassDescriptor) return false fun isInScope(scope: HierarchicalScope): Boolean { return when (target) { is FunctionDescriptor -> scope.findFunction(target.name, NoLookupLocation.FROM_IDE) { it == target } != null && bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true is PropertyDescriptor -> scope.findVariable(target.name, NoLookupLocation.FROM_IDE) { it == target } != null && bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true is ClassDescriptor -> scope.findClassifier(target.name, NoLookupLocation.FROM_IDE) == target && bindingContext[BindingContext.DEPRECATED_SHORT_NAME_ACCESS, place] != true else -> false } } val resolutionScope = place.getResolutionScope(bindingContext, place.getResolutionFacade()) val noImportsScope = resolutionScope.replaceImportingScopes(null) if (isInScope(noImportsScope)) return true // classes not accessible through receivers, only their constructors return if (target is ClassDescriptor) false else resolutionScope.getImplicitReceiversHierarchy().any { isInScope(it.type.memberScope.memberScopeAsImportingScope()) } } private class AbstractReferenceImpl(private val reference: KtReference) : OptimizedImportsBuilder.AbstractReference { override val element: KtElement get() = reference.element override val dependsOnNames: Collection<Name> get() { val resolvesByNames = reference.resolvesByNames if (reference is KtInvokeFunctionReference) { val additionalNames = (reference.element.calleeExpression as? KtNameReferenceExpression)?.mainReference?.resolvesByNames if (additionalNames != null) { return resolvesByNames + additionalNames } } return resolvesByNames } override fun resolve(bindingContext: BindingContext) = reference.resolveToDescriptors(bindingContext) override fun toString() = when (reference) { is Fe10SyntheticPropertyAccessorReference -> { reference.toString().replace( "Fe10SyntheticPropertyAccessorReference", if (reference.getter) "Getter" else "Setter" ) } else -> reference.toString().replace("Fe10", "") } } } companion object { fun collectDescriptorsToImport(file: KtFile, inProgressBar: Boolean = false): OptimizedImportsBuilder.InputData { val progressIndicator = if (inProgressBar) ProgressIndicatorProvider.getInstance().progressIndicator else null progressIndicator?.text = KotlinBundle.message("import.optimizer.progress.indicator.text.collect.imports.for", file.name) progressIndicator?.isIndeterminate = false val visitor = CollectUsedDescriptorsVisitor(file, progressIndicator) file.accept(visitor) return visitor.data } fun prepareOptimizedImports(file: KtFile, data: OptimizedImportsBuilder.InputData): List<ImportPath>? { val settings = file.kotlinCustomSettings val options = OptimizedImportsBuilder.Options( settings.NAME_COUNT_TO_USE_STAR_IMPORT, settings.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS, isInPackagesToUseStarImport = { fqName -> fqName.asString() in settings.PACKAGES_TO_USE_STAR_IMPORTS } ) return OptimizedImportsBuilder(file, data, options, file.languageVersionSettings.apiVersion).buildOptimizedImports() } fun replaceImports(file: KtFile, imports: List<ImportPath>) { val manager = PsiDocumentManager.getInstance(file.project) manager.getDocument(file)?.let { manager.commitDocument(it) } val importList = file.importList ?: return val oldImports = importList.imports val psiFactory = KtPsiFactory(file.project) for (importPath in imports) { importList.addBefore( psiFactory.createImportDirective(importPath), oldImports.lastOrNull() ) // insert into the middle to keep collapsed state } // remove old imports after adding new ones to keep imports folding state for (import in oldImports) { import.delete() } } private fun KtReference.targets(bindingContext: BindingContext): Collection<DeclarationDescriptor> { //class qualifiers that refer to companion objects should be considered (containing) class references return bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, element as? KtReferenceExpression]?.let { listOf(it) } ?: resolveToDescriptors(bindingContext) } private val DO_NOTHING = object : ImportOptimizer.CollectingInfoRunnable { override fun run() = Unit override fun getUserNotificationInfo() = KotlinBundle.message("import.optimizer.notification.text.unused.imports.not.found") } } } private fun hasResolvedDescriptor(element: KtElement, bindingContext: BindingContext): Boolean = if (element is KtCallElement) element.getResolvedCall(bindingContext) != null else element.mainReference?.resolveToDescriptors(bindingContext)?.let { descriptors -> descriptors.isNotEmpty() && descriptors.none { it is ErrorFunctionDescriptor } } == true
apache-2.0
ca4d13e649219fd54e5af57ad46c1178
46.309148
140
0.654598
5.862783
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/kms/src/main/kotlin/com/kotlin/kms/CreateAlias.kt
1
1857
// snippet-sourcedescription:[CreateAlias.kt demonstrates how to create an AWS Key Management Service (AWS KMS) alias.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[AWS Key Management Service] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.kms // snippet-start:[kms.kotlin_create_alias.import] import aws.sdk.kotlin.services.kms.KmsClient import aws.sdk.kotlin.services.kms.model.CreateAliasRequest import kotlin.system.exitProcess // snippet-end:[kms.kotlin_create_alias.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <targetKeyId> <aliasName> Where: targetKeyId - The key ID or the Amazon Resource Name (ARN) of the KMS key. aliasName - An alias name to create (for example, alias/myAlias). """ if (args.size != 2) { println(usage) exitProcess(0) } val targetKeyId = args[0] val aliasName = args[1] createCustomAlias(targetKeyId, aliasName) } // snippet-start:[kms.kotlin_create_alias.main] suspend fun createCustomAlias(targetKeyIdVal: String?, aliasNameVal: String?) { val request = CreateAliasRequest { aliasName = aliasNameVal targetKeyId = targetKeyIdVal } KmsClient { region = "us-west-2" }.use { kmsClient -> kmsClient.createAlias(request) println("$aliasNameVal was successfully created") } } // snippet-end:[kms.kotlin_create_alias.main]
apache-2.0
334934beebdf2669ed1dcf7b06ea188b
29.474576
119
0.673129
3.967949
false
false
false
false
DreierF/MyTargets
app/src/androidTest/java/de/dreier/mytargets/test/utils/matchers/MatcherUtils.kt
1
4758
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.test.utils.matchers import android.content.res.Resources import androidx.test.espresso.Espresso.onView import androidx.test.espresso.ViewInteraction import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.BoundedMatcher import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom import androidx.appcompat.widget.Toolbar import android.view.View import android.view.ViewGroup import android.widget.TextView import org.hamcrest.CoreMatchers.`is` import org.hamcrest.Description import org.hamcrest.Matcher object MatcherUtils { fun getParentViewById(view: View, parentViewId: Int): View? { if (view.id == parentViewId) { return view } else if (view.parent != null && view.parent is ViewGroup) { return getParentViewById(view.parent as View, parentViewId) } return null } fun isInViewHierarchy(view: View, viewToFind: View): Boolean { if (view === viewToFind) { return true } else if (view.parent != null && view.parent is ViewGroup) { return isInViewHierarchy(view.parent as View, viewToFind) } return false } fun matchToolbarTitle(title: CharSequence): ViewInteraction { return onView(isAssignableFrom(Toolbar::class.java)) .check(ViewAssertions.matches(withToolbarTitle(`is`(title)))) } fun withToolbarTitle( textMatcher: Matcher<CharSequence>): Matcher<Any> { return object : BoundedMatcher<Any, Toolbar>(Toolbar::class.java) { public override fun matchesSafely(toolbar: Toolbar): Boolean { return textMatcher.matches(toolbar.title) } override fun describeTo(description: Description) { description.appendText("with toolbar title: ") textMatcher.describeTo(description) } } } fun getMatchingParent(view: View?, matcher: Matcher<View>): View? { if (view == null) { return null } if (matcher.matches(view)) { return view } else if (view.parent != null && view.parent is ViewGroup) { return getMatchingParent(view.parent as View, matcher) } return null } /** * Returns a matcher that matches a descendant of [TextView] that is displaying the string * associated with the given resource id. * * @param resourceId the string resource the text view is expected to hold. */ fun containsStringRes(resourceId: Int): Matcher<View> { return object : BoundedMatcher<View, TextView>(TextView::class.java) { private var resourceName: String? = null private var expectedText: String? = null override fun describeTo(description: Description) { description.appendText("contains string from resource id: ") description.appendValue(resourceId) if (resourceName != null) { description.appendText("[") description.appendText(resourceName) description.appendText("]") } if (expectedText != null) { description.appendText(" value: ") description.appendText(expectedText) } } public override fun matchesSafely(textView: TextView): Boolean { if (expectedText == null) { try { expectedText = textView.resources.getString(resourceId) resourceName = textView.resources.getResourceEntryName(resourceId) } catch (ignored: Resources.NotFoundException) { /* view could be from a context unaware of the resource id. */ } } val actualText = textView.text // FYI: actualText may not be string ... its just a char sequence convert to string. return expectedText != null && actualText != null && actualText.toString().contains(expectedText!!) } } } }
gpl-2.0
5afd1edf96a1a801692afc8b922f1309
37.064
100
0.62169
5.194323
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/training/environment/EnvironmentFragment.kt
1
5234
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets 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. */ package de.dreier.mytargets.features.training.environment import android.content.Intent import androidx.databinding.DataBindingUtil import android.os.Bundle import androidx.appcompat.widget.SwitchCompat import android.view.* import android.view.View.GONE import android.view.View.VISIBLE import com.evernote.android.state.State import de.dreier.mytargets.R import de.dreier.mytargets.base.fragments.FragmentBase import de.dreier.mytargets.base.navigation.NavigationController.Companion.ITEM import de.dreier.mytargets.databinding.FragmentEnvironmentBinding import de.dreier.mytargets.features.settings.SettingsManager import de.dreier.mytargets.shared.models.EWeather import de.dreier.mytargets.shared.models.Environment import de.dreier.mytargets.utils.ToolbarUtils class EnvironmentFragment : FragmentBase() { @State var environment: Environment? = null private lateinit var binding: FragmentEnvironmentBinding private var switchView: SwitchCompat? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil .inflate(inflater, R.layout.fragment_environment, container, false) ToolbarUtils.setSupportActionBar(this, binding.toolbar) ToolbarUtils.showHomeAsUp(this) setHasOptionsMenu(true) // Weather binding.sunny.setOnClickListener { setWeather(EWeather.SUNNY) } binding.partlyCloudy.setOnClickListener { setWeather(EWeather.PARTLY_CLOUDY) } binding.cloudy.setOnClickListener { setWeather(EWeather.CLOUDY) } binding.lightRain.setOnClickListener { setWeather(EWeather.LIGHT_RAIN) } binding.rain.setOnClickListener { setWeather(EWeather.RAIN) } if (savedInstanceState == null) { environment = arguments!!.getParcelable(ITEM) } setWeather(environment!!.weather) binding.windSpeed.setItemId(environment!!.windSpeed.toLong()) binding.windDirection.setItemId(environment!!.windDirection.toLong()) binding.location.setText(environment!!.location) binding.windDirection.setOnClickListener { selectedItem, _ -> navigationController.navigateToWindDirection(selectedItem!!) } binding.windSpeed.setOnClickListener { selectedItem, _ -> navigationController.navigateToWindSpeed(selectedItem!!) } return binding.root } private fun setWeather(weather: EWeather) { environment!!.weather = weather binding.sunny.setImageResource(EWeather.SUNNY.getDrawable(weather)) binding.partlyCloudy.setImageResource(EWeather.PARTLY_CLOUDY.getDrawable(weather)) binding.cloudy.setImageResource(EWeather.CLOUDY.getDrawable(weather)) binding.lightRain.setImageResource(EWeather.LIGHT_RAIN.getDrawable(weather)) binding.rain.setImageResource(EWeather.RAIN.getDrawable(weather)) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.environment_switch, menu) val item = menu.findItem(R.id.action_switch) switchView = item.actionView.findViewById(R.id.action_switch_control) switchView!!.setOnCheckedChangeListener { _, checked -> setOutdoor(checked) } setOutdoor(!environment!!.indoor) switchView!!.isChecked = !environment!!.indoor } private fun setOutdoor(checked: Boolean) { switchView!!.setText(if (checked) R.string.outdoor else R.string.indoor) binding.indoorPlaceholder.visibility = if (checked) GONE else VISIBLE binding.weatherLayout.visibility = if (checked) VISIBLE else GONE } override fun onSaveInstanceState(outState: Bundle) { environment = saveItem() super.onSaveInstanceState(outState) } fun onSave() { val e = saveItem() SettingsManager.indoor = e.indoor navigationController.setResultSuccess(e) navigationController.finish() } private fun saveItem(): Environment { val e = Environment() e.indoor = !switchView!!.isChecked e.weather = environment!!.weather e.windSpeed = binding.windSpeed.selectedItem!!.id.toInt() e.windDirection = binding.windDirection.selectedItem!!.id.toInt() e.location = binding.location.text.toString() return e } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) binding.windSpeed.onActivityResult(requestCode, resultCode, data) binding.windDirection.onActivityResult(requestCode, resultCode, data) } }
gpl-2.0
f79aaf223211ee41782e01c008b68456
39.573643
90
0.724876
4.841813
false
false
false
false
flesire/ontrack
ontrack-ui/src/test/java/net/nemerosa/ontrack/boot/resources/CoreResourceModuleTest.kt
1
78414
package net.nemerosa.ontrack.boot.resources import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.json.JsonUtils import net.nemerosa.ontrack.model.security.* import net.nemerosa.ontrack.model.structure.* import net.nemerosa.ontrack.ui.controller.MockURIBuilder import net.nemerosa.ontrack.ui.resource.* import org.junit.Before import org.junit.Test import java.io.IOException import java.net.URI import java.time.LocalDateTime import java.util.Arrays import net.nemerosa.ontrack.json.JsonUtils.array import net.nemerosa.ontrack.json.JsonUtils.`object` import net.nemerosa.ontrack.model.structure.TestFixtures.SIGNATURE import net.nemerosa.ontrack.model.structure.TestFixtures.SIGNATURE_OBJECT import org.junit.Assert.assertEquals import org.mockito.Mockito.mock import org.mockito.Mockito.`when` class CoreResourceModuleTest { private var mapper: ResourceObjectMapper? = null private var securityService: SecurityService? = null private var structureService: StructureService? = null private var projectFavouriteService: ProjectFavouriteService? = null private var branchFavouriteService: BranchFavouriteService? = null @Before fun before() { securityService = mock(SecurityService::class.java) structureService = mock(StructureService::class.java) val resourceDecorationContributorService = mock(ResourceDecorationContributorService::class.java) projectFavouriteService = mock(ProjectFavouriteService::class.java) branchFavouriteService = mock(BranchFavouriteService::class.java) mapper = ResourceObjectMapperFactory().resourceObjectMapper( listOf<ResourceModule>(DefaultResourceModule( listOf( ConnectedAccountResourceDecorator(), ProjectResourceDecorator(resourceDecorationContributorService, projectFavouriteService), BranchResourceDecorator(resourceDecorationContributorService, structureService, branchFavouriteService), PromotionLevelResourceDecorator(), ValidationStampResourceDecorator(), BuildResourceDecorator(resourceDecorationContributorService), PromotionRunResourceDecorator(), ValidationRunResourceDecorator(), BuildFilterResourceDecorator(), AccountResourceDecorator(), AccountGroupResourceDecorator(), GlobalPermissionResourceDecorator(), ProjectPermissionResourceDecorator(), JobStatusResourceDecorator(), PredefinedValidationStampResourceDecorator() ) )), DefaultResourceContext(MockURIBuilder(), securityService) ) } @Test @Throws(JsonProcessingException::class) fun project_granted_for_update() { val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)).withSignature(SIGNATURE) `when`(securityService!!.isProjectFunctionGranted(1, ProjectEdit::class.java)).thenReturn(true) assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_update", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#saveProject:1,") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_disable", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#disableProject:1") .with("_page", "urn:test:#:entity:PROJECT:1") .end(), p ) } @Test @Throws(JsonProcessingException::class) fun project_not_favourite() { val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) `when`(securityService!!.isLogged).thenReturn(true) assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_favourite", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#favouriteProject:1") .with("_page", "urn:test:#:entity:PROJECT:1") .end(), p ) } @Test @Throws(JsonProcessingException::class) fun project_no_favourite_link_if_not_logged() { val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end(), p ) } @Test @Throws(JsonProcessingException::class) fun project_favourite() { val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) `when`(securityService!!.isLogged).thenReturn(true) `when`(projectFavouriteService!!.isProjectFavourite(p)).thenReturn(true) assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_unfavourite", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#unfavouriteProject:1") .with("_page", "urn:test:#:entity:PROJECT:1") .end(), p ) } @Test @Throws(JsonProcessingException::class) fun project_granted_for_update_and_disabled() { val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)).withDisabled(true) .withSignature(SIGNATURE) `when`(securityService!!.isProjectFunctionGranted(1, ProjectEdit::class.java)).thenReturn(true) assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", true) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_update", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#saveProject:1,") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_enable", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#enableProject:1") .with("_page", "urn:test:#:entity:PROJECT:1") .end(), p ) } @Test @Throws(JsonProcessingException::class) fun branch_no_build_granted_for_template_definition() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)) .withSignature(SIGNATURE) `when`(securityService!!.isProjectFunctionGranted(1, BranchTemplateMgt::class.java)).thenReturn(true) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "CLASSIC") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end() ) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_templateDefinition", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getTemplateDefinition:1") .with("_templateInstanceConnect", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#connectTemplateInstance:1") .with("_page", "urn:test:#:entity:BRANCH:1") .end(), b ) } @Test @Throws(JsonProcessingException::class) fun branch_instance_for_template_definition() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)).withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)) .withType(BranchType.TEMPLATE_INSTANCE) .withSignature(SIGNATURE) `when`(securityService!!.isProjectFunctionGranted(1, BranchTemplateMgt::class.java)).thenReturn(true) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "TEMPLATE_INSTANCE") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end() ) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_templateInstance", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getTemplateInstance:1") .with("_templateInstanceDisconnect", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#disconnectTemplateInstance:1") .with("_templateInstanceSync", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#syncTemplateInstance:1") .with("_page", "urn:test:#:entity:BRANCH:1") .end(), b ) } @Test @Throws(JsonProcessingException::class) fun branch_with_builds_for_template_definition() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)) .withSignature(SIGNATURE) `when`(structureService!!.getBuildCount(b)).thenReturn(1) `when`(securityService!!.isProjectFunctionGranted(1, BranchTemplateMgt::class.java)).thenReturn(true) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "CLASSIC") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end() ) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_templateInstanceConnect", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#connectTemplateInstance:1") .with("_page", "urn:test:#:entity:BRANCH:1") .end(), b ) } @Test @Throws(JsonProcessingException::class) fun branch_definition_granted() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)) .withType(BranchType.TEMPLATE_DEFINITION) .withSignature(SIGNATURE) `when`(securityService!!.isProjectFunctionGranted(1, BranchTemplateMgt::class.java)).thenReturn(true) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "TEMPLATE_DEFINITION") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end() ) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_templateDefinition", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getTemplateDefinition:1") .with("_templateSync", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#syncTemplateDefinition:1") .with("_templateInstanceCreate", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#singleTemplateInstanceForm:1") .with("_page", "urn:test:#:entity:BRANCH:1") .end(), b ) } @Test @Throws(JsonProcessingException::class) fun branch_sync_granted_for_controller() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)) .withType(BranchType.TEMPLATE_DEFINITION) .withSignature(SIGNATURE) `when`(securityService!!.isProjectFunctionGranted(1, BranchTemplateSync::class.java)).thenReturn(true) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "TEMPLATE_DEFINITION") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end() ) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_templateSync", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#syncTemplateDefinition:1") .with("_templateInstanceCreate", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#singleTemplateInstanceForm:1") .with("_page", "urn:test:#:entity:BRANCH:1") .end(), b ) } @Test @Throws(JsonProcessingException::class) fun branch_definition_not_granted() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)) .withType(BranchType.TEMPLATE_DEFINITION) .withSignature(SIGNATURE) `when`(securityService!!.isProjectFunctionGranted(1, BranchTemplateMgt::class.java)).thenReturn(false) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "TEMPLATE_DEFINITION") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end() ) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_page", "urn:test:#:entity:BRANCH:1") .end(), b ) } @Test @Throws(JsonProcessingException::class) fun branch_no_grant() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)).withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)).withSignature(SIGNATURE) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "CLASSIC") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end() ) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_page", "urn:test:#:entity:BRANCH:1") .end(), b ) } @Test @Throws(JsonProcessingException::class) fun build_view() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)).withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)).withSignature(SIGNATURE) val signatureTime = LocalDateTime.of(2015, 6, 17, 11, 41) val build = Build.of(b, NameDescription.nd("1", "Build 1"), Signature.of(signatureTime, "test")).withId(ID.of(1)) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "1") .with("description", "Build 1") .with("signature", `object`() .with("time", "2015-06-17T11:41:00Z") .with("user", `object`().with("name", "test").end()) .end() ) .with("branch", `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "CLASSIC") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end() ) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_page", "urn:test:#:entity:BRANCH:1") .end() ) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#getBuild:1") .with("_lastPromotionRuns", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionRunController#getLastPromotionRuns:1") .with("_promotionRuns", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionRunController#getPromotionRuns:1") .with("_validationRuns", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationRunController#getValidationRuns:1") .with("_validationStampRunViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationRunController#getValidationStampRunViews:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BUILD,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BUILD,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:BUILD,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BUILD,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BUILD,1,0,10") .with("_previous", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#getPreviousBuild:1") .with("_next", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#getNextBuild:1") .with("_buildLinksFrom", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#getBuildLinksFrom:1") .with("_buildLinksTo", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#getBuildLinksTo:1") .with("_runInfo", "urn:test:net.nemerosa.ontrack.boot.ui.RunInfoController#getRunInfo:build,1") .with("_page", "urn:test:#:entity:BUILD:1") .end(), build ) } @Test @Throws(JsonProcessingException::class) fun project_not_granted_for_update() { val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) .withSignature(SIGNATURE) assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end(), p ) } @Test @Throws(JsonProcessingException::class) fun promotion_level_image_link_and_ignored_branch() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)).withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)).withSignature(SIGNATURE) val pl = PromotionLevel.of(b, NameDescription("PL", "Promotion level")).withId(ID.of(1)).withSignature(SIGNATURE) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "PL") .with("description", "Promotion level") .with("image", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevel:1") .with("_branch", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_image", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelImage_:,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROMOTION_LEVEL,1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROMOTION_LEVEL,1") .with("_runs", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionRunView:1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROMOTION_LEVEL,1,0,10") .with("_page", "urn:test:#:entity:PROMOTION_LEVEL:1") .end(), pl, Branch::class.java ) } @Test @Throws(JsonProcessingException::class) fun promotion_level_image_link_and_include_branch() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)).withSignature(SIGNATURE) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)).withSignature(SIGNATURE) val pl = PromotionLevel.of(b, NameDescription("PL", "Promotion level")) .withId(ID.of(1)) .withSignature(SIGNATURE) // Serialization assertResourceJson( mapper!!, `object`() .with("id", 1) .with("name", "PL") .with("description", "Promotion level") .with("branch", `object`() .with("id", 1) .with("name", "B") .with("description", "Branch") .with("disabled", false) .with("type", "CLASSIC") .with("project", `object`() .with("id", 1) .with("name", "P") .with("description", "Project") .with("disabled", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_branchStatusViews", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getBranchStatusViews:1") .with("_buildSearch", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildSearchForm:1") .with("_buildDiffActions", "urn:test:net.nemerosa.ontrack.boot.ui.BuildController#buildDiffActions:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROJECT,1") .with("_extra", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getInformation:PROJECT,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:PROJECT,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROJECT,1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROJECT,1,0,10") .with("_page", "urn:test:#:entity:PROJECT:1") .end()) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_page", "urn:test:#:entity:BRANCH:1") .end()) .with("image", false) .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevel:1") .with("_branch", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_image", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelImage_:,1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:PROMOTION_LEVEL,1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:PROMOTION_LEVEL,1") .with("_runs", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionRunView:1") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:PROMOTION_LEVEL,1,0,10") .with("_page", "urn:test:#:entity:PROMOTION_LEVEL:1") .end(), pl ) } @Test @Throws(JsonProcessingException::class) fun resource_collection_with_filtering() { val project = Project.of(NameDescription("PRJ", "Project")).withId(ID.of(1)) val branches = Arrays.asList( Branch.of(project, NameDescription("B1", "Branch 1")).withId(ID.of(1)).withSignature(SIGNATURE), Branch.of(project, NameDescription("B2", "Branch 2")).withId(ID.of(2)).withSignature(SIGNATURE) ) val resourceCollection = Resources.of( branches, URI.create("urn:branch") ) assertResourceJson( mapper!!, `object`() .with("_self", "urn:branch") .with("resources", array() .with(`object`() .with("id", 1) .with("name", "B1") .with("description", "Branch 1") .with("disabled", false) .with("type", "CLASSIC") .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:1") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:1") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:1") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:1") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:1") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,1") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,1") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:1") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:1") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,1") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:1") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:1") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:1,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,1,0,10") .with("_page", "urn:test:#:entity:BRANCH:1") .end()) .with(`object`() .with("id", 2) .with("name", "B2") .with("description", "Branch 2") .with("disabled", false) .with("type", "CLASSIC") .with("signature", SIGNATURE_OBJECT) .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranch:2") .with("_project", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectController#getProject:1") .with("_promotionLevels", "urn:test:net.nemerosa.ontrack.boot.ui.PromotionLevelController#getPromotionLevelListForBranch:2") .with("_validationStamps", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampListForBranch:2") .with("_validationStampViews", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampController#getValidationStampViewListForBranch:2") .with("_allValidationStampFilters", "urn:test:net.nemerosa.ontrack.boot.ui.ValidationStampFilterController#getAllBranchValidationStampFilters:2") .with("_branches", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchListForProject:1") .with("_properties", "urn:test:net.nemerosa.ontrack.boot.ui.PropertyController#getProperties:BRANCH,2") .with("_actions", "urn:test:net.nemerosa.ontrack.boot.ui.ProjectEntityExtensionController#getActions:BRANCH,2") .with("_status", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#getBranchStatusView:2") .with("_view", "urn:test:net.nemerosa.ontrack.boot.ui.BranchController#buildView:2") .with("_decorations", "urn:test:net.nemerosa.ontrack.boot.ui.DecorationsController#getDecorations:BRANCH,2") .with("_buildFilterResources", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilters:2") .with("_buildFilterForms", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#buildFilterForms:2") .with("_buildFilterSave", "urn:test:net.nemerosa.ontrack.boot.ui.BuildFilterController#createFilter:2,") .with("_events", "urn:test:net.nemerosa.ontrack.boot.ui.EventController#getEvents:BRANCH,2,0,10") .with("_page", "urn:test:#:entity:BRANCH:2") .end()) .end()) .end(), resourceCollection ) } @Test @Throws(JsonProcessingException::class) fun account_group_links() { assertResourceJson( mapper!!, `object`() .with("id", 0) .with("name", "Admins") .with("description", "Administrators") .with("_self", "urn:test:net.nemerosa.ontrack.boot.ui.AccountController#getGroup:0") .with("_update", "urn:test:net.nemerosa.ontrack.boot.ui.AccountController#getGroupUpdateForm:0") .with("_delete", "urn:test:net.nemerosa.ontrack.boot.ui.AccountController#deleteGroup:0") .end(), AccountGroup.of("Admins", "Administrators") ) } @Test @Throws(IOException::class) fun promotion_run_delete_granted() { // Objects val p = Project.of(NameDescription("P", "Project")).withId(ID.of(1)) val b = Branch.of(p, NameDescription("B", "Branch")).withId(ID.of(1)).withType(BranchType.TEMPLATE_DEFINITION) val pl = PromotionLevel.of(b, NameDescription.nd("PL", "Promotion Level")).withId(ID.of(1)) val build = Build.of(b, NameDescription.nd("1", "Build 1"), Signature.of("test")).withId(ID.of(1)) val run = PromotionRun.of(build, pl, Signature.of("test"), "Run").withId(ID.of(1)) // Security `when`(securityService!!.isProjectFunctionGranted(1, PromotionRunDelete::class.java)).thenReturn(true) // Serialization val node = mapper!!.objectMapper.readTree(mapper!!.write(run)) // Checks the _delete link is present val delete = JsonUtils.get(node, "_delete") assertEquals("urn:test:net.nemerosa.ontrack.boot.ui.PromotionRunController#deletePromotionRun:1", delete) } companion object { @Throws(JsonProcessingException::class) fun assertResourceJson(mapper: ResourceObjectMapper, expectedJson: JsonNode, o: Any) { assertEquals( mapper.objectMapper.writeValueAsString(expectedJson), mapper.write(o) ) } @Throws(JsonProcessingException::class) fun assertResourceJson(mapper: ResourceObjectMapper, expectedJson: JsonNode, o: Any, view: Class<*>) { assertEquals( mapper.objectMapper.writeValueAsString(expectedJson), mapper.write(o, view) ) } } }
mit
6d484ad66a7a914e2239bc6d5cb0bea5
77.335664
185
0.57102
4.977087
false
true
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/DualNode.kt
1
1669
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* @DependsOn(Node::class) class DualNode : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<Node>() } .and { it.instanceFields.size >= 2 } .and { c -> c.instanceFields.count { it.type == c.type } == 2 } @MethodParameters() class removeDual : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } } @DependsOn(removeDual::class) class nextDual : OrderMapper.InMethod.Field(removeDual::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == GETFIELD } } @DependsOn(nextDual::class) class previousDual : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.id != field<nextDual>().id } .and { it.type == type<DualNode>() } } class keyDual : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == LONG_TYPE } } }
mit
e0d6574435554046434f561fe4cb85e4
39.731707
86
0.723188
4.031401
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt
2
62356
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.codeInsight.template.* import com.intellij.codeInsight.template.impl.TemplateImpl import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.UnfairTextRange import com.intellij.psi.* import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.MutablePackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.base.psi.isMultiLine import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind import org.jetbrains.kotlin.idea.refactoring.* import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.DialogWithEditor import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.getDefaultInitializer import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope import org.jetbrains.kotlin.resolve.scopes.LexicalScopeImpl import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeProjectionImpl import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.* import kotlin.math.max /** * Represents a single choice for a type (e.g. parameter type or return type). */ class TypeCandidate(val theType: KotlinType, scope: HierarchicalScope? = null) { val typeParameters: Array<TypeParameterDescriptor> var renderedTypes: List<String> = emptyList() private set var renderedTypeParameters: List<RenderedTypeParameter>? = null private set fun render(typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor?) { renderedTypes = theType.renderShort(typeParameterNameMap) renderedTypeParameters = typeParameters.map { RenderedTypeParameter(it, it.containingDeclaration == fakeFunction, typeParameterNameMap.getValue(it)) } } init { val typeParametersInType = theType.getTypeParameters() if (scope == null) { typeParameters = typeParametersInType.toTypedArray() renderedTypes = theType.renderShort(Collections.emptyMap()) } else { typeParameters = getTypeParameterNamesNotInScope(typeParametersInType, scope).toTypedArray() } } override fun toString() = theType.toString() } data class RenderedTypeParameter( val typeParameter: TypeParameterDescriptor, val fake: Boolean, val text: String ) fun List<TypeCandidate>.getTypeByRenderedType(renderedTypes: List<String>): KotlinType? = firstOrNull { it.renderedTypes == renderedTypes }?.theType class CallableBuilderConfiguration( val callableInfos: List<CallableInfo>, val originalElement: KtElement, val currentFile: KtFile = originalElement.containingKtFile, val currentEditor: Editor? = null, val isExtension: Boolean = false, val enableSubstitutions: Boolean = true ) sealed class CallablePlacement { class WithReceiver(val receiverTypeCandidate: TypeCandidate) : CallablePlacement() class NoReceiver(val containingElement: PsiElement) : CallablePlacement() } class CallableBuilder(val config: CallableBuilderConfiguration) { private var finished: Boolean = false val currentFileContext = config.currentFile.analyzeWithContent() private lateinit var _currentFileModule: ModuleDescriptor val currentFileModule: ModuleDescriptor get() { if (!_currentFileModule.isValid) { updateCurrentModule() } return _currentFileModule } init { updateCurrentModule() } val pseudocode: Pseudocode? by lazy { config.originalElement.getContainingPseudocode(currentFileContext) } private val typeCandidates = HashMap<TypeInfo, List<TypeCandidate>>() var placement: CallablePlacement? = null private val elementsToShorten = ArrayList<KtElement>() private fun updateCurrentModule() { _currentFileModule = config.currentFile.analyzeWithAllCompilerChecks().moduleDescriptor } fun computeTypeCandidates(typeInfo: TypeInfo): List<TypeCandidate> = typeCandidates.getOrPut(typeInfo) { typeInfo.getPossibleTypes(this).map { TypeCandidate(it) } } private fun computeTypeCandidates( typeInfo: TypeInfo, substitutions: List<KotlinTypeSubstitution>, scope: HierarchicalScope ): List<TypeCandidate> { if (!typeInfo.substitutionsAllowed) return computeTypeCandidates(typeInfo) return typeCandidates.getOrPut(typeInfo) { val types = typeInfo.getPossibleTypes(this).asReversed() // We have to use semantic equality here data class EqWrapper(val _type: KotlinType) { override fun equals(other: Any?) = this === other || other is EqWrapper && KotlinTypeChecker.DEFAULT.equalTypes(_type, other._type) override fun hashCode() = 0 // no good way to compute hashCode() that would agree with our equals() } val newTypes = LinkedHashSet(types.map(::EqWrapper)) for (substitution in substitutions) { // each substitution can be applied or not, so we offer all options val toAdd = newTypes.map { it._type.substitute(substitution, typeInfo.variance) } // substitution.byType are type arguments, but they cannot already occur in the type before substitution val toRemove = newTypes.filter { substitution.byType in it._type } newTypes.addAll(toAdd.map(::EqWrapper)) newTypes.removeAll(toRemove) } if (newTypes.isEmpty()) { newTypes.add(EqWrapper(currentFileModule.builtIns.anyType)) } newTypes.map { TypeCandidate(it._type, scope) }.asReversed() } } private fun buildNext(iterator: Iterator<CallableInfo>) { if (iterator.hasNext()) { val context = Context(iterator.next()) runWriteAction { context.buildAndRunTemplate { buildNext(iterator) } } ApplicationManager.getApplication().invokeLater { context.showDialogIfNeeded() } } else { runWriteAction { ShortenReferences.DEFAULT.process(elementsToShorten) } } } fun build(onFinish: () -> Unit = {}) { try { assert(config.currentEditor != null) { "Can't run build() without editor" } check(!finished) { "Current builder has already finished" } buildNext(config.callableInfos.iterator()) } finally { finished = true onFinish() } } private inner class Context(val callableInfo: CallableInfo) { val skipReturnType: Boolean val ktFileToEdit: KtFile val containingFileEditor: Editor val containingElement: PsiElement val dialogWithEditor: DialogWithEditor? val receiverClassDescriptor: ClassifierDescriptor? val typeParameterNameMap: Map<TypeParameterDescriptor, String> val receiverTypeCandidate: TypeCandidate? val mandatoryTypeParametersAsCandidates: List<TypeCandidate> val substitutions: List<KotlinTypeSubstitution> var finished: Boolean = false init { // gather relevant information val placement = placement var nullableReceiver = false when (placement) { is CallablePlacement.NoReceiver -> { containingElement = placement.containingElement receiverClassDescriptor = with(placement.containingElement) { when (this) { is KtClassOrObject -> currentFileContext[BindingContext.CLASS, this] is PsiClass -> getJavaClassDescriptor() else -> null } } } is CallablePlacement.WithReceiver -> { val theType = placement.receiverTypeCandidate.theType nullableReceiver = theType.isMarkedNullable receiverClassDescriptor = theType.constructor.declarationDescriptor val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } containingElement = if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile } else -> throw IllegalArgumentException("Placement wan't initialized") } val receiverType = receiverClassDescriptor?.defaultType?.let { if (nullableReceiver) it.makeNullable() else it } val project = config.currentFile.project if (containingElement.containingFile != config.currentFile) { NavigationUtil.activateFileWithPsiElement(containingElement) } dialogWithEditor = if (containingElement is KtElement) { ktFileToEdit = containingElement.containingKtFile containingFileEditor = if (ktFileToEdit != config.currentFile) { FileEditorManager.getInstance(project).selectedTextEditor!! } else { config.currentEditor!! } null } else { val dialog = object : DialogWithEditor(project, KotlinBundle.message("fix.create.from.usage.dialog.title"), "") { override fun doOKAction() { project.executeWriteCommand(KotlinBundle.message("premature.end.of.template")) { TemplateManagerImpl.getTemplateState(editor)?.gotoEnd(false) } super.doOKAction() } } containingFileEditor = dialog.editor with(containingFileEditor.settings) { additionalColumnsCount = config.currentEditor!!.settings.getRightMargin(project) additionalLinesCount = 5 } ktFileToEdit = PsiDocumentManager.getInstance(project).getPsiFile(containingFileEditor.document) as KtFile ktFileToEdit.analysisContext = config.currentFile dialog } val scope = getDeclarationScope() receiverTypeCandidate = receiverType?.let { TypeCandidate(it, scope) } val fakeFunction: FunctionDescriptor? // figure out type substitutions for type parameters val substitutionMap = LinkedHashMap<KotlinType, KotlinType>() if (config.enableSubstitutions) { collectSubstitutionsForReceiverTypeParameters(receiverType, substitutionMap) val typeArgumentsForFakeFunction = callableInfo.typeParameterInfos .map { val typeCandidates = computeTypeCandidates(it) assert(typeCandidates.size == 1) { "Ambiguous type candidates for type parameter $it: $typeCandidates" } typeCandidates.first().theType } .subtract(substitutionMap.keys) fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size) collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap) mandatoryTypeParametersAsCandidates = listOfNotNull(receiverTypeCandidate) + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it]!!, scope) } } else { fakeFunction = null mandatoryTypeParametersAsCandidates = Collections.emptyList() } substitutions = substitutionMap.map { KotlinTypeSubstitution(it.key, it.value) } callableInfo.parameterInfos.forEach { computeTypeCandidates(it.typeInfo, substitutions, scope) } val returnTypeCandidate = computeTypeCandidates(callableInfo.returnTypeInfo, substitutions, scope).singleOrNull() skipReturnType = when (callableInfo.kind) { CallableKind.FUNCTION -> returnTypeCandidate?.theType?.isUnit() ?: false CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> callableInfo.returnTypeInfo == TypeInfo.Empty || returnTypeCandidate?.theType?.isAnyOrNullableAny() ?: false CallableKind.CONSTRUCTOR -> true CallableKind.PROPERTY -> containingElement is KtBlockExpression } // figure out type parameter renames to avoid conflicts typeParameterNameMap = getTypeParameterRenames(scope) callableInfo.parameterInfos.forEach { renderTypeCandidates(it.typeInfo, typeParameterNameMap, fakeFunction) } if (!skipReturnType) { renderTypeCandidates(callableInfo.returnTypeInfo, typeParameterNameMap, fakeFunction) } receiverTypeCandidate?.render(typeParameterNameMap, fakeFunction) mandatoryTypeParametersAsCandidates.forEach { it.render(typeParameterNameMap, fakeFunction) } } private fun getDeclarationScope(): HierarchicalScope { if (config.isExtension || receiverClassDescriptor == null) { return currentFileModule.getPackage(config.currentFile.packageFqName).memberScope.memberScopeAsImportingScope() } if (receiverClassDescriptor is ClassDescriptorWithResolutionScopes) { return receiverClassDescriptor.scopeForMemberDeclarationResolution } assert(receiverClassDescriptor is JavaClassDescriptor) { "Unexpected receiver class: $receiverClassDescriptor" } val projections = ((receiverClassDescriptor as JavaClassDescriptor).declaredTypeParameters) .map { TypeProjectionImpl(it.defaultType) } val memberScope = receiverClassDescriptor.getMemberScope(projections) return LexicalScopeImpl( memberScope.memberScopeAsImportingScope(), receiverClassDescriptor, false, null, emptyList(), LexicalScopeKind.SYNTHETIC ) { receiverClassDescriptor.typeConstructor.parameters.forEach { addClassifierDescriptor(it) } } } private fun collectSubstitutionsForReceiverTypeParameters( receiverType: KotlinType?, result: MutableMap<KotlinType, KotlinType> ) { if (placement is CallablePlacement.NoReceiver) return val classTypeParameters = receiverType?.arguments ?: Collections.emptyList() val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.arguments ?: Collections.emptyList() assert(ownerTypeArguments.size == classTypeParameters.size) ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.type] = it.second.type } } private fun collectSubstitutionsForCallableTypeParameters( fakeFunction: FunctionDescriptor, typeArguments: Set<KotlinType>, result: MutableMap<KotlinType, KotlinType> ) { for ((typeArgument, typeParameter) in typeArguments.zip(fakeFunction.typeParameters)) { result[typeArgument] = typeParameter.defaultType } } @OptIn(FrontendInternals::class) private fun createFakeFunctionDescriptor(scope: HierarchicalScope, typeParameterCount: Int): FunctionDescriptor { val fakeFunction = SimpleFunctionDescriptorImpl.create( MutablePackageFragmentDescriptor(currentFileModule, FqName("fake")), Annotations.EMPTY, Name.identifier("fake"), CallableMemberDescriptor.Kind.SYNTHESIZED, SourceElement.NO_SOURCE ) val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val parameterNames = Fe10KotlinNameSuggester.suggestNamesForTypeParameters(typeParameterCount, validator) val typeParameters = (0 until typeParameterCount).map { TypeParameterDescriptorImpl.createWithDefaultBound( fakeFunction, Annotations.EMPTY, false, Variance.INVARIANT, Name.identifier(parameterNames[it]), it, ktFileToEdit.getResolutionFacade().frontendService() ) } return fakeFunction.initialize( null, null, emptyList(), typeParameters, Collections.emptyList(), null, null, DescriptorVisibilities.INTERNAL ) } private fun renderTypeCandidates( typeInfo: TypeInfo, typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor? ) { typeCandidates[typeInfo]?.forEach { it.render(typeParameterNameMap, fakeFunction) } } private fun isInsideInnerOrLocalClass(): Boolean { val classOrObject = containingElement.getNonStrictParentOfType<KtClassOrObject>() return classOrObject is KtClass && (classOrObject.isInner() || classOrObject.isLocal) } private fun createDeclarationSkeleton(): KtNamedDeclaration { with(config) { val assignmentToReplace = if (containingElement is KtBlockExpression && (callableInfo as? PropertyInfo)?.writable == true) { originalElement as KtBinaryExpression } else null val pointerOfAssignmentToReplace = assignmentToReplace?.createSmartPointer() val ownerTypeString = if (isExtension) { val renderedType = receiverTypeCandidate!!.renderedTypes.first() val isFunctionType = receiverTypeCandidate.theType.constructor.declarationDescriptor is FunctionClassDescriptor if (isFunctionType) "($renderedType)." else "$renderedType." } else "" val classKind = (callableInfo as? ClassWithPrimaryConstructorInfo)?.classInfo?.kind fun renderParamList(): String { val prefix = if (classKind == ClassKind.ANNOTATION_CLASS) "val " else "" val list = callableInfo.parameterInfos.indices.joinToString(", ") { i -> "${prefix}p$i: Any" } return if (callableInfo.parameterInfos.isNotEmpty() || callableInfo.kind == CallableKind.FUNCTION || callableInfo.kind == CallableKind.CONSTRUCTOR ) "($list)" else list } val paramList = when (callableInfo.kind) { CallableKind.FUNCTION, CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR, CallableKind.CONSTRUCTOR -> renderParamList() CallableKind.PROPERTY -> "" } val returnTypeString = if (skipReturnType || assignmentToReplace != null) "" else ": Any" val header = "$ownerTypeString${callableInfo.name.quoteIfNeeded()}$paramList$returnTypeString" val psiFactory = KtPsiFactory(currentFile) val modifiers = buildString { val modifierList = callableInfo.modifierList?.copied() ?: psiFactory.createEmptyModifierList() val visibilityKeyword = modifierList.visibilityModifierType() if (visibilityKeyword == null) { val defaultVisibility = if (callableInfo.isAbstract) "" else if (containingElement is KtClassOrObject && !(containingElement is KtClass && containingElement.isInterface()) && containingElement.isAncestor(config.originalElement) && callableInfo.kind != CallableKind.CONSTRUCTOR ) "private " else if (isExtension) "private " else "" append(defaultVisibility) } // TODO: Get rid of isAbstract if (callableInfo.isAbstract && containingElement is KtClass && !containingElement.isInterface() && !modifierList.hasModifier(KtTokens.ABSTRACT_KEYWORD) ) { modifierList.appendModifier(KtTokens.ABSTRACT_KEYWORD) } val text = modifierList.normalize().text if (text.isNotEmpty()) { append("$text ") } } val isExpectClassMember by lazy { containingElement is KtClassOrObject && containingElement.resolveToDescriptorIfAny()?.isExpect ?: false } val declaration: KtNamedDeclaration = when (callableInfo.kind) { CallableKind.FUNCTION, CallableKind.CONSTRUCTOR -> { val body = when { callableInfo is ConstructorInfo -> if (callableInfo.withBody) "{\n\n}" else "" callableInfo.isAbstract -> "" containingElement is KtClass && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" containingElement is KtObjectDeclaration && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" containingElement is KtObjectDeclaration && containingElement.isCompanion() && containingElement.parent.parent is KtClass && (containingElement.parent.parent as KtClass).hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" isExpectClassMember -> "" else -> "{\n\n}" } @Suppress("USELESS_CAST") // KT-10755 when { callableInfo is FunctionInfo -> psiFactory.createFunction("${modifiers}fun<> $header $body") as KtNamedDeclaration (callableInfo as ConstructorInfo).isPrimary -> { val constructorText = if (modifiers.isNotEmpty()) "${modifiers}constructor$paramList" else paramList psiFactory.createPrimaryConstructor(constructorText) as KtNamedDeclaration } else -> psiFactory.createSecondaryConstructor("${modifiers}constructor$paramList $body") as KtNamedDeclaration } } CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> { val classWithPrimaryConstructorInfo = callableInfo as ClassWithPrimaryConstructorInfo with(classWithPrimaryConstructorInfo.classInfo) { val classBody = when (kind) { ClassKind.ANNOTATION_CLASS, ClassKind.ENUM_ENTRY -> "" else -> "{\n\n}" } val safeName = name.quoteIfNeeded() when (kind) { ClassKind.ENUM_ENTRY -> { val targetParent = applicableParents.singleOrNull() if (!(targetParent is KtClass && targetParent.isEnum())) { throw KotlinExceptionWithAttachments("Enum class expected: ${targetParent?.let { it::class.java }}") .withPsiAttachment("targetParent", targetParent) } val hasParameters = targetParent.primaryConstructorParameters.isNotEmpty() psiFactory.createEnumEntry("$safeName${if (hasParameters) "()" else " "}") } else -> { val openMod = if (open && kind != ClassKind.INTERFACE) "open " else "" val innerMod = if (inner || isInsideInnerOrLocalClass()) "inner " else "" val typeParamList = when (kind) { ClassKind.PLAIN_CLASS, ClassKind.INTERFACE -> "<>" else -> "" } val ctor = classWithPrimaryConstructorInfo.primaryConstructorVisibility?.name?.let { " $it constructor" } ?: "" psiFactory.createDeclaration<KtClassOrObject>( "$openMod$innerMod${kind.keyword} $safeName$typeParamList$ctor$paramList$returnTypeString $classBody" ) } } } } CallableKind.PROPERTY -> { val isVar = (callableInfo as PropertyInfo).writable val const = if (callableInfo.isConst) "const " else "" val valVar = if (isVar) "var" else "val" val accessors = if (isExtension && !isExpectClassMember) { buildString { append("\nget() {}") if (isVar) { append("\nset() {}") } } } else "" psiFactory.createProperty("$modifiers$const$valVar<> $header$accessors") } } if (callableInfo is PropertyInfo) { callableInfo.annotations.forEach { declaration.addAnnotationEntry(it) } } val newInitializer = pointerOfAssignmentToReplace?.element if (newInitializer != null) { (declaration as KtProperty).initializer = newInitializer.right return newInitializer.replace(declaration) as KtCallableDeclaration } val container = if (containingElement is KtClass && callableInfo.isForCompanion) { containingElement.getOrCreateCompanionObject() } else containingElement val declarationInPlace = placeDeclarationInContainer(declaration, container, config.originalElement, ktFileToEdit) if (declarationInPlace is KtSecondaryConstructor) { val containingClass = declarationInPlace.containingClassOrObject!! val primaryConstructorParameters = containingClass.primaryConstructorParameters if (primaryConstructorParameters.isNotEmpty()) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(true) } else if ((receiverClassDescriptor as ClassDescriptor).getSuperClassOrAny().constructors .all { it.valueParameters.isNotEmpty() } ) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(false) } if (declarationInPlace.valueParameters.size > primaryConstructorParameters.size) { val hasCompatibleTypes = primaryConstructorParameters.zip(callableInfo.parameterInfos).all { (primary, secondary) -> val primaryType = currentFileContext[BindingContext.TYPE, primary.typeReference] ?: return@all false val secondaryType = computeTypeCandidates(secondary.typeInfo).firstOrNull()?.theType ?: return@all false secondaryType.isSubtypeOf(primaryType) } if (hasCompatibleTypes) { val delegationCallArgumentList = declarationInPlace.getDelegationCall().valueArgumentList primaryConstructorParameters.forEach { val name = it.name if (name != null) delegationCallArgumentList?.addArgument(psiFactory.createArgument(name)) } } } } return declarationInPlace } } private fun getTypeParameterRenames(scope: HierarchicalScope): Map<TypeParameterDescriptor, String> { val allTypeParametersNotInScope = LinkedHashSet<TypeParameterDescriptor>() mandatoryTypeParametersAsCandidates.asSequence() .plus(callableInfo.parameterInfos.asSequence().flatMap { typeCandidates[it.typeInfo]!!.asSequence() }) .flatMap { it.typeParameters.asSequence() } .toCollection(allTypeParametersNotInScope) if (!skipReturnType) { computeTypeCandidates(callableInfo.returnTypeInfo).asSequence().flatMapTo(allTypeParametersNotInScope) { it.typeParameters.asSequence() } } val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val typeParameterNames = allTypeParametersNotInScope.map { Fe10KotlinNameSuggester.suggestNameByName(it.name.asString(), validator) } return allTypeParametersNotInScope.zip(typeParameterNames).toMap() } private fun setupTypeReferencesForShortening( declaration: KtNamedDeclaration, parameterTypeExpressions: List<TypeExpression> ) { if (config.isExtension) { val receiverTypeText = receiverTypeCandidate!!.theType.renderLong(typeParameterNameMap).first() val replacingTypeRef = KtPsiFactory(declaration).createType(receiverTypeText) (declaration as KtCallableDeclaration).setReceiverTypeReference(replacingTypeRef)!! } val returnTypeRefs = declaration.getReturnTypeReferences() if (returnTypeRefs.isNotEmpty()) { val returnType = typeCandidates[callableInfo.returnTypeInfo]!!.getTypeByRenderedType( returnTypeRefs.map { it.text } ) if (returnType != null) { // user selected a given type replaceWithLongerName(returnTypeRefs, returnType) } } val valueParameters = declaration.getValueParameters() val parameterIndicesToShorten = ArrayList<Int>() assert(valueParameters.size == parameterTypeExpressions.size) for ((i, parameter) in valueParameters.asSequence().withIndex()) { val parameterTypeRef = parameter.typeReference if (parameterTypeRef != null) { val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType( listOf(parameterTypeRef.text) ) if (parameterType != null) { replaceWithLongerName(listOf(parameterTypeRef), parameterType) parameterIndicesToShorten.add(i) } } } } private fun postprocessDeclaration(declaration: KtNamedDeclaration) { if (callableInfo is PropertyInfo && callableInfo.isLateinitPreferred) { if (declaration.containingClassOrObject == null) return val propertyDescriptor = declaration.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return val returnType = propertyDescriptor.returnType ?: return if (TypeUtils.isNullableType(returnType) || KotlinBuiltIns.isPrimitiveType(returnType)) return declaration.addModifier(KtTokens.LATEINIT_KEYWORD) } if (callableInfo.isAbstract) { val containingClass = declaration.containingClassOrObject if (containingClass is KtClass && containingClass.isInterface()) { declaration.removeModifier(KtTokens.ABSTRACT_KEYWORD) } } } private fun setupDeclarationBody(func: KtDeclarationWithBody) { if (func !is KtNamedFunction && func !is KtPropertyAccessor) return if (skipReturnType && callableInfo is FunctionInfo && callableInfo.preferEmptyBody) return val oldBody = func.bodyExpression ?: return val bodyText = getFunctionBodyTextFromTemplate( func.project, TemplateKind.FUNCTION, if (callableInfo.name.isNotEmpty()) callableInfo.name else null, if (skipReturnType) "Unit" else (func as? KtFunction)?.typeReference?.text ?: "", receiverClassDescriptor?.importableFqName ?: receiverClassDescriptor?.name?.let { FqName.topLevel(it) } ) oldBody.replace(KtPsiFactory(func).createBlock(bodyText)) } private fun setupCallTypeArguments(callElement: KtCallElement, typeParameters: List<TypeParameterDescriptor>) { val oldTypeArgumentList = callElement.typeArgumentList ?: return val renderedTypeArgs = typeParameters.map { typeParameter -> val type = substitutions.first { it.byType.constructor.declarationDescriptor == typeParameter }.forType IdeDescriptorRenderers.SOURCE_CODE.renderType(type) } if (renderedTypeArgs.isEmpty()) { oldTypeArgumentList.delete() } else { oldTypeArgumentList.replace(KtPsiFactory(callElement).createTypeArguments(renderedTypeArgs.joinToString(", ", "<", ">"))) elementsToShorten.add(callElement.typeArgumentList!!) } } private fun setupReturnTypeTemplate(builder: TemplateBuilder, declaration: KtNamedDeclaration): TypeExpression? { val candidates = typeCandidates[callableInfo.returnTypeInfo]!! if (candidates.isEmpty()) return null val elementToReplace: KtElement? val expression: TypeExpression = when (declaration) { is KtCallableDeclaration -> { elementToReplace = declaration.typeReference TypeExpression.ForTypeReference(candidates) } is KtClassOrObject -> { elementToReplace = declaration.superTypeListEntries.firstOrNull() TypeExpression.ForDelegationSpecifier(candidates) } else -> throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}") .withPsiAttachment("declaration", declaration) } if (elementToReplace == null) return null if (candidates.size == 1) { builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).text) return null } builder.replaceElement(elementToReplace, expression) return expression } private fun setupValVarTemplate(builder: TemplateBuilder, property: KtProperty) { if (!(callableInfo as PropertyInfo).writable) { builder.replaceElement(property.valOrVarKeyword, ValVarExpression) } } private fun setupTypeParameterListTemplate( builder: TemplateBuilderImpl, declaration: KtNamedDeclaration ): TypeParameterListExpression? { when (declaration) { is KtObjectDeclaration -> return null !is KtTypeParameterListOwner -> { throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}") .withPsiAttachment("declaration", declaration) } } val typeParameterList = (declaration as KtTypeParameterListOwner).typeParameterList ?: return null val typeParameterMap = HashMap<String, List<RenderedTypeParameter>>() val mandatoryTypeParameters = ArrayList<RenderedTypeParameter>() //receiverTypeCandidate?.let { mandatoryTypeParameters.addAll(it.renderedTypeParameters!!) } mandatoryTypeParametersAsCandidates.asSequence().flatMapTo(mandatoryTypeParameters) { it.renderedTypeParameters!!.asSequence() } callableInfo.parameterInfos.asSequence() .flatMap { typeCandidates[it.typeInfo]!!.asSequence() } .forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } if (declaration.getReturnTypeReference() != null) { typeCandidates[callableInfo.returnTypeInfo]!!.forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } } val expression = TypeParameterListExpression( mandatoryTypeParameters, typeParameterMap, callableInfo.kind != CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR ) val leftSpace = typeParameterList.prevSibling as? PsiWhiteSpace val rangeStart = leftSpace?.startOffset ?: typeParameterList.startOffset val offset = typeParameterList.startOffset val range = UnfairTextRange(rangeStart - offset, typeParameterList.endOffset - offset) builder.replaceElement(typeParameterList, range, "TYPE_PARAMETER_LIST", expression, false) return expression } private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List<KtParameter>): List<TypeExpression> { assert(parameterList.size == callableInfo.parameterInfos.size) val typeParameters = ArrayList<TypeExpression>() for ((parameter, ktParameter) in callableInfo.parameterInfos.zip(parameterList)) { val parameterTypeExpression = TypeExpression.ForTypeReference(typeCandidates[parameter.typeInfo]!!) val parameterTypeRef = ktParameter.typeReference!! builder.replaceElement(parameterTypeRef, parameterTypeExpression) // add parameter name to the template val possibleNamesFromExpression = parameter.typeInfo.getPossibleNamesFromExpression(currentFileContext) val possibleNames = arrayOf(*parameter.nameSuggestions.toTypedArray(), *possibleNamesFromExpression) // figure out suggested names for each type option val parameterTypeToNamesMap = HashMap<String, Array<String>>() typeCandidates[parameter.typeInfo]!!.forEach { typeCandidate -> val suggestedNames = Fe10KotlinNameSuggester.suggestNamesByType(typeCandidate.theType, { true }) parameterTypeToNamesMap[typeCandidate.renderedTypes.first()] = suggestedNames.toTypedArray() } // add expression to builder val parameterNameExpression = ParameterNameExpression(possibleNames, parameterTypeToNamesMap) val parameterNameIdentifier = ktParameter.nameIdentifier!! builder.replaceElement(parameterNameIdentifier, parameterNameExpression) typeParameters.add(parameterTypeExpression) } return typeParameters } private fun replaceWithLongerName(typeRefs: List<KtTypeReference>, theType: KotlinType) { val psiFactory = KtPsiFactory(ktFileToEdit.project) val fullyQualifiedReceiverTypeRefs = theType.renderLong(typeParameterNameMap).map { psiFactory.createType(it) } (typeRefs zip fullyQualifiedReceiverTypeRefs).forEach { (shortRef, longRef) -> shortRef.replace(longRef) } } private fun transformToJavaMemberIfApplicable(declaration: KtNamedDeclaration): Boolean { fun convertToJava(targetClass: PsiClass): PsiMember? { val psiFactory = KtPsiFactory(declaration) psiFactory.createPackageDirectiveIfNeeded(config.currentFile.packageFqName)?.let { declaration.containingFile.addBefore(it, null) } val adjustedDeclaration = when (declaration) { is KtNamedFunction, is KtProperty -> { val klass = psiFactory.createClass("class Foo {}") klass.body!!.add(declaration) (declaration.replace(klass) as KtClass).body!!.declarations.first() } else -> declaration } return when (adjustedDeclaration) { is KtNamedFunction, is KtSecondaryConstructor -> { createJavaMethod(adjustedDeclaration as KtFunction, targetClass) } is KtProperty -> { createJavaField(adjustedDeclaration, targetClass) } is KtClass -> { createJavaClass(adjustedDeclaration, targetClass) } else -> null } } if (config.isExtension || receiverClassDescriptor !is JavaClassDescriptor) return false val targetClass = DescriptorToSourceUtils.getSourceFromDescriptor(receiverClassDescriptor) as? PsiClass if (targetClass == null || !targetClass.canRefactor()) return false val project = declaration.project val newJavaMember = convertToJava(targetClass) ?: return false val modifierList = newJavaMember.modifierList!! if (newJavaMember is PsiMethod || newJavaMember is PsiClass) { modifierList.setModifierProperty(PsiModifier.FINAL, false) } val needStatic = when (callableInfo) { is ClassWithPrimaryConstructorInfo -> with(callableInfo.classInfo) { !inner && kind != ClassKind.ENUM_ENTRY && kind != ClassKind.ENUM_CLASS } else -> callableInfo.receiverTypeInfo.staticContextRequired } modifierList.setModifierProperty(PsiModifier.STATIC, needStatic) JavaCodeStyleManager.getInstance(project).shortenClassReferences(newJavaMember) val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile) val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!! targetEditor.selectionModel.removeSelection() when (newJavaMember) { is PsiMethod -> CreateFromUsageUtils.setupEditor(newJavaMember, targetEditor) is PsiField -> targetEditor.caretModel.moveToOffset(newJavaMember.endOffset - 1) is PsiClass -> { val constructor = newJavaMember.constructors.firstOrNull() val superStatement = constructor?.body?.statements?.firstOrNull() as? PsiExpressionStatement val superCall = superStatement?.expression as? PsiMethodCallExpression if (superCall != null) { val lParen = superCall.argumentList.firstChild targetEditor.caretModel.moveToOffset(lParen.endOffset) } else { targetEditor.caretModel.moveToOffset(newJavaMember.nameIdentifier?.startOffset ?: newJavaMember.startOffset) } } } targetEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE) return true } private fun setupEditor(declaration: KtNamedDeclaration) { if (declaration is KtProperty && !declaration.hasInitializer() && containingElement is KtBlockExpression) { val defaultValueType = typeCandidates[callableInfo.returnTypeInfo]!!.firstOrNull()?.theType val defaultValue = defaultValueType?.let { it.getDefaultInitializer() } ?: "null" val initializer = declaration.setInitializer(KtPsiFactory(declaration).createExpression(defaultValue))!! val range = initializer.textRange containingFileEditor.selectionModel.setSelection(range.startOffset, range.endOffset) containingFileEditor.caretModel.moveToOffset(range.endOffset) return } if (declaration is KtSecondaryConstructor && !declaration.hasImplicitDelegationCall()) { containingFileEditor.caretModel.moveToOffset(declaration.getDelegationCall().valueArgumentList!!.startOffset + 1) return } setupEditorSelection(containingFileEditor, declaration) } // build templates fun buildAndRunTemplate(onFinish: () -> Unit) { val declarationSkeleton = createDeclarationSkeleton() val project = declarationSkeleton.project val declarationPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationSkeleton) // build templates val documentManager = PsiDocumentManager.getInstance(project) val document = containingFileEditor.document documentManager.commitDocument(document) documentManager.doPostponedOperationsAndUnblockDocument(document) val caretModel = containingFileEditor.caretModel caretModel.moveToOffset(ktFileToEdit.node.startOffset) val declaration = declarationPointer.element ?: return val declarationMarker = document.createRangeMarker(declaration.textRange) val builder = TemplateBuilderImpl(ktFileToEdit) if (declaration is KtProperty) { setupValVarTemplate(builder, declaration) } if (!skipReturnType) { setupReturnTypeTemplate(builder, declaration) } val parameterTypeExpressions = setupParameterTypeTemplates(builder, declaration.getValueParameters()) // add a segment for the parameter list // Note: because TemplateBuilderImpl does not have a replaceElement overload that takes in both a TextRange and alwaysStopAt, we // need to create the segment first and then hack the Expression into the template later. We use this template to update the type // parameter list as the user makes selections in the parameter types, and we need alwaysStopAt to be false so the user can't tab to // it. val expression = setupTypeParameterListTemplate(builder, declaration) documentManager.doPostponedOperationsAndUnblockDocument(document) // the template built by TemplateBuilderImpl is ordered by element position, but we want types to be first, so hack it val templateImpl = builder.buildInlineTemplate() as TemplateImpl val variables = templateImpl.variables!! if (variables.isNotEmpty()) { val typeParametersVar = if (expression != null) variables.removeAt(0) else null for (i in callableInfo.parameterInfos.indices) { Collections.swap(variables, i * 2, i * 2 + 1) } typeParametersVar?.let { variables.add(it) } } // TODO: Disabled shortening names because it causes some tests fail. Refactor code to use automatic reference shortening templateImpl.isToShortenLongNames = false // run the template TemplateManager.getInstance(project).startTemplate(containingFileEditor, templateImpl, object : TemplateEditingAdapter() { private fun finishTemplate(brokenOff: Boolean) { try { documentManager.commitDocument(document) dialogWithEditor?.close(DialogWrapper.OK_EXIT_CODE) if (brokenOff && !isUnitTestMode()) return // file templates val newDeclaration = PsiTreeUtil.findElementOfClassAtOffset( ktFileToEdit, declarationMarker.startOffset, declaration::class.java, false ) ?: return runWriteAction { postprocessDeclaration(newDeclaration) // file templates if (newDeclaration is KtNamedFunction || newDeclaration is KtSecondaryConstructor) { setupDeclarationBody(newDeclaration as KtFunction) } if (newDeclaration is KtProperty) { newDeclaration.getter?.let { setupDeclarationBody(it) } if (callableInfo is PropertyInfo && callableInfo.initializer != null) { newDeclaration.initializer = callableInfo.initializer } } val callElement = config.originalElement as? KtCallElement if (callElement != null) { setupCallTypeArguments(callElement, expression?.currentTypeParameters ?: Collections.emptyList()) } CodeStyleManager.getInstance(project).reformat(newDeclaration) // change short type names to fully qualified ones (to be shortened below) if (newDeclaration.getValueParameters().size == parameterTypeExpressions.size) { setupTypeReferencesForShortening(newDeclaration, parameterTypeExpressions) } if (!transformToJavaMemberIfApplicable(newDeclaration)) { elementsToShorten.add(newDeclaration) setupEditor(newDeclaration) } } } finally { declarationMarker.dispose() finished = true onFinish() } } override fun templateCancelled(template: Template?) { finishTemplate(true) } override fun templateFinished(template: Template, brokenOff: Boolean) { finishTemplate(brokenOff) } }) } fun showDialogIfNeeded() { if (!isUnitTestMode() && dialogWithEditor != null && !finished) { dialogWithEditor.show() } } } } // TODO: Simplify and use formatter as much as possible @Suppress("UNCHECKED_CAST") internal fun <D : KtNamedDeclaration> placeDeclarationInContainer( declaration: D, container: PsiElement, anchor: PsiElement, fileToEdit: KtFile = container.containingFile as KtFile ): D { val psiFactory = KtPsiFactory(container) val newLine = psiFactory.createNewLine() fun calcNecessaryEmptyLines(decl: KtDeclaration, after: Boolean): Int { var lineBreaksPresent = 0 var neighbor: PsiElement? = null siblingsLoop@ for (sibling in decl.siblings(forward = after, withItself = false)) { when (sibling) { is PsiWhiteSpace -> lineBreaksPresent += (sibling.text ?: "").count { it == '\n' } else -> { neighbor = sibling break@siblingsLoop } } } val neighborType = neighbor?.node?.elementType val lineBreaksNeeded = when { neighborType == KtTokens.LBRACE || neighborType == KtTokens.RBRACE -> 1 neighbor is KtDeclaration && (neighbor !is KtProperty || decl !is KtProperty) -> 2 else -> 1 } return max(lineBreaksNeeded - lineBreaksPresent, 0) } val actualContainer = (container as? KtClassOrObject)?.getOrCreateBody() ?: container fun addDeclarationToClassOrObject( classOrObject: KtClassOrObject, declaration: KtNamedDeclaration ): KtNamedDeclaration { val classBody = classOrObject.getOrCreateBody() return if (declaration is KtNamedFunction) { val neighbor = PsiTreeUtil.skipSiblingsBackward( classBody.rBrace ?: classBody.lastChild!!, PsiWhiteSpace::class.java ) classBody.addAfter(declaration, neighbor) as KtNamedDeclaration } else classBody.addAfter(declaration, classBody.lBrace!!) as KtNamedDeclaration } fun addNextToOriginalElementContainer(addBefore: Boolean): D { val sibling = anchor.parentsWithSelf.first { it.parent == actualContainer } return if (addBefore || PsiTreeUtil.hasErrorElements(sibling)) { actualContainer.addBefore(declaration, sibling) } else { actualContainer.addAfter(declaration, sibling) } as D } val declarationInPlace = when { declaration is KtPrimaryConstructor -> { (container as KtClass).createPrimaryConstructorIfAbsent().replaced(declaration) } declaration is KtProperty && container !is KtBlockExpression -> { val sibling = actualContainer.getChildOfType<KtProperty>() ?: when (actualContainer) { is KtClassBody -> actualContainer.declarations.firstOrNull() ?: actualContainer.rBrace is KtFile -> actualContainer.declarations.first() else -> null } sibling?.let { actualContainer.addBefore(declaration, it) as D } ?: fileToEdit.add(declaration) as D } actualContainer.isAncestor(anchor, true) -> { val insertToBlock = container is KtBlockExpression if (insertToBlock) { val parent = container.parent if (parent is KtFunctionLiteral) { if (!parent.isMultiLine()) { parent.addBefore(newLine, container) parent.addAfter(newLine, container) } } } addNextToOriginalElementContainer(insertToBlock || declaration is KtTypeAlias) } container is KtFile -> container.add(declaration) as D container is PsiClass -> { if (declaration is KtSecondaryConstructor) { val wrappingClass = psiFactory.createClass("class ${container.name} {\n}") addDeclarationToClassOrObject(wrappingClass, declaration) (fileToEdit.add(wrappingClass) as KtClass).declarations.first() as D } else { fileToEdit.add(declaration) as D } } container is KtClassOrObject -> { var sibling: PsiElement? = container.declarations.lastOrNull { it::class == declaration::class } if (sibling == null && declaration is KtProperty) { sibling = container.body?.lBrace } insertMembersAfterAndReformat(null, container, declaration, sibling) } else -> throw KotlinExceptionWithAttachments("Invalid containing element: ${container::class.java}") .withPsiAttachment("container", container) } when (declaration) { is KtEnumEntry -> { val prevEnumEntry = declarationInPlace.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtEnumEntry>() if (prevEnumEntry != null) { if ((prevEnumEntry.prevSibling as? PsiWhiteSpace)?.text?.contains('\n') == true) { declarationInPlace.parent.addBefore(psiFactory.createNewLine(), declarationInPlace) } val comma = psiFactory.createComma() if (prevEnumEntry.allChildren.any { it.node.elementType == KtTokens.COMMA }) { declarationInPlace.add(comma) } else { prevEnumEntry.add(comma) } val semicolon = prevEnumEntry.allChildren.firstOrNull { it.node?.elementType == KtTokens.SEMICOLON } if (semicolon != null) { (semicolon.prevSibling as? PsiWhiteSpace)?.text?.let { declarationInPlace.add(psiFactory.createWhiteSpace(it)) } declarationInPlace.add(psiFactory.createSemicolon()) semicolon.delete() } } } !is KtPrimaryConstructor -> { val parent = declarationInPlace.parent calcNecessaryEmptyLines(declarationInPlace, false).let { if (it > 0) parent.addBefore(psiFactory.createNewLine(it), declarationInPlace) } calcNecessaryEmptyLines(declarationInPlace, true).let { if (it > 0) parent.addAfter(psiFactory.createNewLine(it), declarationInPlace) } } } return declarationInPlace } fun KtNamedDeclaration.getReturnTypeReference() = getReturnTypeReferences().singleOrNull() internal fun KtNamedDeclaration.getReturnTypeReferences(): List<KtTypeReference> { return when (this) { is KtCallableDeclaration -> listOfNotNull(typeReference) is KtClassOrObject -> superTypeListEntries.mapNotNull { it.typeReference } else -> throw AssertionError("Unexpected declaration kind: $text") } } fun CallableBuilderConfiguration.createBuilder(): CallableBuilder = CallableBuilder(this)
apache-2.0
30cfb0f068fa354cc35e37c7bfc136de
49.695935
158
0.618834
6.504224
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2017/Day14.kt
1
1301
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.* import com.nibado.projects.advent.Point object Day14 : Day { private val rows = (0..127).map { "amgozmfv-$it" } private val square : List<String> by lazy { rows.map { hash(it) }.map { toBinary(it) } } override fun part1() = square.sumBy { it.count { it == '1' } }.toString() override fun part2(): String { val points = (0 .. 127).flatMap { x -> (0 .. 127 ).map { y -> Point(x, y) } }.toMutableSet() val visited = points.filter { square[it.y][it.x] == '0'}.toMutableSet() points.removeAll(visited) var count = 0 while(!points.isEmpty()) { count++ fill(visited, points, points.first()) } return count.toString() } private fun fill(visited: MutableSet<Point>, points: MutableSet<Point>, current: Point) { visited += current points -= current current.neighborsHv().filter { points.contains(it) }.forEach { fill(visited, points, it) } } private fun hash(input: String): String { val chars = input.toCharArray().map { it.toInt() } + listOf(17, 31, 73, 47, 23) return (0..15).map { Day10.knot(chars, 64).subList(it * 16, it * 16 + 16) }.map { xor(it) }.toHex() } }
mit
4f4aa48baa6056e5196bec3c2e39f566
32.384615
107
0.588009
3.554645
false
false
false
false
JetBrains/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/upload.kt
1
9431
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package org.jetbrains.intellij.build.impl.compilation import com.github.luben.zstd.Zstd import com.github.luben.zstd.ZstdDirectBufferCompressingStreamNoFinalizer import com.intellij.diagnostic.telemetry.forkJoinTask import com.intellij.diagnostic.telemetry.use import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream import okhttp3.* import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import okio.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import java.nio.ByteBuffer import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong private val MEDIA_TYPE_JSON = "application/json".toMediaType() internal val READ_OPERATION = EnumSet.of(StandardOpenOption.READ) internal const val MAX_BUFFER_SIZE = 4_000_000 internal fun uploadArchives(reportStatisticValue: (key: String, value: String) -> Unit, config: CompilationCacheUploadConfiguration, metadataJson: String, httpClient: OkHttpClient, items: List<PackAndUploadItem>, bufferPool: DirectFixedSizeByteBufferPool) { val uploadedCount = AtomicInteger() val uploadedBytes = AtomicLong() val reusedCount = AtomicInteger() val reusedBytes = AtomicLong() var fallbackToHeads = false val alreadyUploaded: Set<String> = try { if (config.checkFiles) { spanBuilder("fetch info about already uploaded files").use { HashSet(getFoundAndMissingFiles(metadataJson, config.serverUrl, httpClient).found) } } else { emptySet() } } catch (e: Throwable) { Span.current().recordException(e, Attributes.of( AttributeKey.stringKey("message"), "failed to fetch info about already uploaded files, will fallback to HEAD requests" )) fallbackToHeads = true emptySet() } ForkJoinTask.invokeAll(items.mapNotNull { item -> if (alreadyUploaded.contains(item.name)) { reusedCount.getAndIncrement() reusedBytes.getAndAdd(Files.size(item.archive)) return@mapNotNull null } forkJoinTask(spanBuilder("upload archive").setAttribute("name", item.name).setAttribute("hash", item.hash!!)) { val isUploaded = uploadFile(url = "${config.serverUrl}/$uploadPrefix/${item.name}/${item.hash!!}.jar", file = item.archive, useHead = fallbackToHeads, span = Span.current(), httpClient = httpClient, bufferPool = bufferPool) val size = Files.size(item.archive) if (isUploaded) { uploadedCount.getAndIncrement() uploadedBytes.getAndAdd(size) } else { reusedCount.getAndIncrement() reusedBytes.getAndAdd(size) } } }) Span.current().addEvent("upload complete", Attributes.of( AttributeKey.longKey("reusedParts"), reusedCount.get().toLong(), AttributeKey.longKey("uploadedParts"), uploadedCount.get().toLong(), AttributeKey.longKey("reusedBytes"), reusedBytes.get(), AttributeKey.longKey("uploadedBytes"), uploadedBytes.get(), AttributeKey.longKey("totalBytes"), reusedBytes.get() + uploadedBytes.get(), AttributeKey.longKey("totalCount"), (reusedCount.get() + uploadedCount.get()).toLong(), )) reportStatisticValue("compile-parts:reused:bytes", reusedBytes.get().toString()) reportStatisticValue("compile-parts:reused:count", reusedCount.get().toString()) reportStatisticValue("compile-parts:uploaded:bytes", uploadedBytes.get().toString()) reportStatisticValue("compile-parts:uploaded:count", uploadedCount.get().toString()) reportStatisticValue("compile-parts:total:bytes", (reusedBytes.get() + uploadedBytes.get()).toString()) reportStatisticValue("compile-parts:total:count", (reusedCount.get() + uploadedCount.get()).toString()) } private fun getFoundAndMissingFiles(metadataJson: String, serverUrl: String, client: OkHttpClient): CheckFilesResponse { client.newCall(Request.Builder() .url("$serverUrl/check-files") .post(metadataJson.toRequestBody(MEDIA_TYPE_JSON)) .build()).execute().useSuccessful { return Json.decodeFromStream(it.body.byteStream()) } } // Using ZSTD dictionary doesn't make the difference, even slightly worse (default compression level 3). // That's because in our case we compress a relatively large archive of class files. private fun uploadFile(url: String, file: Path, useHead: Boolean, span: Span, httpClient: OkHttpClient, bufferPool: DirectFixedSizeByteBufferPool): Boolean { if (useHead) { val request = Request.Builder().url(url).head().build() val code = httpClient.newCall(request).execute().use { it.code } when { code == 200 -> { span.addEvent("already exist on server, nothing to upload", Attributes.of( AttributeKey.stringKey("url"), url, )) return false } code != 404 -> { span.addEvent("responded with unexpected", Attributes.of( AttributeKey.longKey("code"), code.toLong(), AttributeKey.stringKey("url"), url, )) } } } val fileSize = Files.size(file) if (Zstd.compressBound(fileSize) <= MAX_BUFFER_SIZE) { compressSmallFile(file = file, fileSize = fileSize, bufferPool = bufferPool, url = url) } else { val request = Request.Builder() .url(url) .put(object : RequestBody() { override fun contentType() = MEDIA_TYPE_BINARY override fun writeTo(sink: BufferedSink) { compressFile(file = file, output = sink, bufferPool = bufferPool) } }) .build() httpClient.newCall(request).execute().useSuccessful { } } return true } private fun compressSmallFile(file: Path, fileSize: Long, bufferPool: DirectFixedSizeByteBufferPool, url: String) { val targetBuffer = bufferPool.allocate() try { var readOffset = 0L val sourceBuffer = bufferPool.allocate() var isSourceBufferReleased = false try { FileChannel.open(file, READ_OPERATION).use { input -> do { readOffset += input.read(sourceBuffer, readOffset) } while (readOffset < fileSize) } sourceBuffer.flip() Zstd.compress(targetBuffer, sourceBuffer, 3, false) targetBuffer.flip() bufferPool.release(sourceBuffer) isSourceBufferReleased = true } finally { if (!isSourceBufferReleased) { bufferPool.release(sourceBuffer) } } val compressedSize = targetBuffer.remaining() val request = Request.Builder() .url(url) .put(object : RequestBody() { override fun contentLength() = compressedSize.toLong() override fun contentType() = MEDIA_TYPE_BINARY override fun writeTo(sink: BufferedSink) { targetBuffer.mark() sink.write(targetBuffer) targetBuffer.reset() } }) .build() httpClient.newCall(request).execute().useSuccessful { } } finally { bufferPool.release(targetBuffer) } } private fun compressFile(file: Path, output: BufferedSink, bufferPool: DirectFixedSizeByteBufferPool) { val targetBuffer = bufferPool.allocate() object : ZstdDirectBufferCompressingStreamNoFinalizer(targetBuffer, 3) { override fun flushBuffer(toFlush: ByteBuffer): ByteBuffer { toFlush.flip() while (toFlush.hasRemaining()) { output.write(toFlush) } toFlush.clear() return toFlush } override fun close() { try { super.close() } finally { bufferPool.release(targetBuffer) } } }.use { compressor -> val sourceBuffer = bufferPool.allocate() try { var offset = 0L FileChannel.open(file, READ_OPERATION).use { input -> val fileSize = input.size() while (offset < fileSize) { val actualBlockSize = (fileSize - offset).toInt() if (sourceBuffer.remaining() > actualBlockSize) { sourceBuffer.limit(sourceBuffer.position() + actualBlockSize) } var readOffset = offset do { readOffset += input.read(sourceBuffer, readOffset) } while (sourceBuffer.hasRemaining()) sourceBuffer.flip() compressor.compress(sourceBuffer) sourceBuffer.clear() offset = readOffset } } } finally { bufferPool.release(sourceBuffer) } } } @Serializable private data class CheckFilesResponse( val found: List<String> = emptyList(), val missing: List<String> = emptyList(), )
apache-2.0
b29632009116803f1234fb3e2e8ae3c3
32.685714
124
0.658043
4.794611
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/ide/util/PsiElementBackgroundPresentationComputer.kt
1
5343
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.util import com.intellij.navigation.TargetPresentation import com.intellij.openapi.application.EDT import com.intellij.openapi.application.readAction import com.intellij.openapi.ui.popup.util.PopupUtil import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.ui.AnimatedIcon.ANIMATION_IN_RENDERER_ALLOWED import com.intellij.ui.ScreenUtil import com.intellij.ui.popup.AbstractPopup import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.UIUtil import com.intellij.util.ui.UIUtil.runWhenChanged import com.intellij.util.ui.UIUtil.runWhenHidden import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.SendChannel import java.awt.Dimension import java.awt.Point import java.awt.Rectangle import javax.swing.AbstractListModel import javax.swing.JList import javax.swing.event.ListDataEvent internal fun getComputer(list: JList<*>): PsiElementBackgroundPresentationComputer { val existing = UIUtil.getClientProperty(list, computerKey) if (existing != null) { return existing } val computer = PsiElementBackgroundPresentationComputer(list) UIUtil.putClientProperty(list, computerKey, computer) UIUtil.putClientProperty(list, ANIMATION_IN_RENDERER_ALLOWED, true) fun cleanUp() { UIUtil.putClientProperty(list, computerKey, null) UIUtil.putClientProperty(list, ANIMATION_IN_RENDERER_ALLOWED, null) computer.dispose() } runWhenHidden(list, ::cleanUp) runWhenChanged(list, "cellRenderer", ::cleanUp) return computer } private val computerKey = Key.create<PsiElementBackgroundPresentationComputer>("PsiElementBackgroundPresentationComputer") private typealias RendererAndElement = Pair<PsiElementListCellRenderer<*>, PsiElement> internal class PsiElementBackgroundPresentationComputer(list: JList<*>) { private val myCoroutineScope = CoroutineScope(Job()) private val myRepaintQueue = myCoroutineScope.repaintQueue(list) private val myPresentationMap: MutableMap<RendererAndElement, Deferred<TargetPresentation>> = HashMap() fun dispose() { myCoroutineScope.cancel() myRepaintQueue.close() myPresentationMap.clear() } @RequiresEdt fun computePresentationAsync(renderer: PsiElementListCellRenderer<*>, element: PsiElement): Deferred<TargetPresentation> { return myPresentationMap.computeIfAbsent(RendererAndElement(renderer, element), ::doComputePresentationAsync) } private fun doComputePresentationAsync(rendererAndElement: RendererAndElement): Deferred<TargetPresentation> { val result = myCoroutineScope.async { //delay((Math.random() * 3000 + 2000).toLong()) // uncomment to add artificial delay to check out how it looks in UI readAction { val (renderer, element) = rendererAndElement renderer.computePresentation(element) } } myCoroutineScope.launch { result.join() myRepaintQueue.send(Unit) // repaint _after_ the resulting future is done } return result } } private fun CoroutineScope.repaintQueue(list: JList<*>): SendChannel<Unit> { val repaintQueue = Channel<Unit>(Channel.CONFLATED) launch(Dispatchers.EDT) { // A tick happens when an element has finished computing. // Several elements are also merged into a single tick because the Channel is CONFLATED. for (tick in repaintQueue) { notifyModelChanged(list) redrawListAndContainer(list) delay(100) // update UI no more often that once in 100ms } } return repaintQueue } /** * This method forces [javax.swing.plaf.basic.BasicListUI.updateLayoutStateNeeded] to become non-zero via the path: * [JList.getModel] * -> [AbstractListModel.getListDataListeners] * -> [javax.swing.event.ListDataListener.contentsChanged] * -> [javax.swing.plaf.basic.BasicListUI.Handler.contentsChanged] * * It's needed so next call of [javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState] will recompute list's preferred size. */ private fun notifyModelChanged(list: JList<*>) { val model = list.model if (model !is AbstractListModel) { error("Unsupported list model: " + model.javaClass.name) } val size = model.size if (size == 0) { return } val listeners = model.listDataListeners if (listeners.isEmpty()) { return } val e = ListDataEvent(list, ListDataEvent.CONTENTS_CHANGED, 0, size - 1) for (listener in listeners) { listener.contentsChanged(e) } } private fun redrawListAndContainer(list: JList<*>) { if (!list.isShowing) { return } resizePopup(list) list.repaint() } private fun resizePopup(list: JList<*>) { val popup = PopupUtil.getPopupContainerFor(list) ?: return if (popup is AbstractPopup && popup.dimensionServiceKey != null) { return } val popupLocation = popup.locationOnScreen val rectangle = Rectangle(popupLocation, list.parent.preferredSize) ScreenUtil.fitToScreen(rectangle) if (rectangle.width > popup.size.width) { // don't shrink popup popup.setLocation(Point(rectangle.x, popupLocation.y)) // // don't change popup vertical position on screen popup.size = Dimension(rectangle.width, popup.size.height) // don't change popup height } }
apache-2.0
c8e67475c0ff105f07f9a2f5de485f8a
36.104167
128
0.762867
4.340374
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/collect/Link.kt
1
2071
package com.nibado.projects.advent.collect class Link<T>(val value: T, var next: Link<T>? = null) : Collection<T> { fun next() = next ?: this fun nextOrNull() = next fun firstLink() = linkSequence().first() fun lastLink() = linkSequence().last() fun addNext(value: T) : Link<T> = addNext(Link(value)) fun addNext(link: Link<T>) : Link<T> { val next = this.next link.lastLink().next = next this.next = link return link } fun addAll(iterable: Iterable<T>) { val firstLink = Link(iterable.first()) val last = iterable.drop(1).fold(firstLink) { link, e -> link.next = Link(e) link.next!! } last.next = this.next this.next = firstLink } fun remove(amount: Int = 1) : Link<T> { val toRemove = linkSequence().drop(amount).first() val removeStart = next() next = toRemove.next toRemove.next = null return removeStart } override val size: Int get() = linkSequence().count() override fun contains(element: T): Boolean = linkSequence().any { it.value == element } override fun containsAll(elements: Collection<T>): Boolean { return this.toSet().containsAll(elements) } override fun isEmpty(): Boolean = false override fun iterator(): Iterator<T> = linkSequence().map { it.value }.iterator() fun linkSequence() : Sequence<Link<T>> { val start = this return sequence { var current : Link<T>? = start while(current != null) { yield(current!!) current = current.next if(current == start) { break } } } } override fun toString() : String = joinToString(", ", "[", "]") companion object { fun <T> of(iterable: Iterable<T>) : Link<T> = Link(iterable.first()).also { it.addAll(iterable.drop(1)) } fun <T> of(vararg elements: T) = of(elements.toList()) } }
mit
cda965181e000f7823174d2da4384fb7
26.263158
113
0.547562
4.158635
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/theme/ThemeChooserStage.kt
2
6713
package io.github.chrislo27.rhre3.editor.stage.theme import com.badlogic.gdx.Gdx import com.badlogic.gdx.Preferences import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.editor.stage.EditorStage import io.github.chrislo27.rhre3.screen.EditorScreen import io.github.chrislo27.rhre3.theme.LoadedThemes import io.github.chrislo27.rhre3.theme.Theme import io.github.chrislo27.rhre3.theme.Themes import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.ui.* import io.github.chrislo27.toolboks.util.gdxutils.openFileExplorer class ThemeChooserStage(val editor: Editor, val palette: UIPalette, parent: EditorStage, camera: OrthographicCamera, pixelsWidth: Float, pixelsHeight: Float) : Stage<EditorScreen>(parent, camera, pixelsWidth, pixelsHeight) { private val preferences: Preferences get() = editor.main.preferences val title: TextLabel<EditorScreen> private val chooserButtonBar: Stage<EditorScreen> private val themeList: ThemeListStage<Theme> val themeEditor: ThemeEditorStage init { this.elements += ColourPane(this, this).apply { this.colour.set(Editor.TRANSLUCENT_BLACK) this.colour.a = 0.8f } themeList = object : ThemeListStage<Theme>(editor, palette, this@ThemeChooserStage, [email protected], 362f, 352f) { override val itemList: List<Theme> get() = LoadedThemes.themes override fun getItemName(item: Theme): String = item.name override fun isItemNameLocalizationKey(item: Theme): Boolean = item.nameIsLocalization override fun getItemBgColor(item: Theme): Color = item.background override fun getItemLineColor(item: Theme): Color = item.trackLine override fun isItemSelected(item: Theme): Boolean = item == LoadedThemes.themes[LoadedThemes.index] override fun getBlueBarLimit(): Int = Themes.defaultThemes.size override fun onItemButtonSelected(leftClick: Boolean, realIndex: Int, buttonIndex: Int) { if (leftClick) { LoadedThemes.index = realIndex LoadedThemes.persistIndex(preferences) editor.theme = LoadedThemes.currentTheme } } }.apply { location.set(screenX = 0f, screenY = 0f, screenWidth = 0f, screenHeight = 0f, pixelX = 20f, pixelY = 53f, pixelWidth = 362f, pixelHeight = 352f) } this.elements += themeList title = TextLabel(palette, this, this).apply { this.location.set(screenX = 0f, screenWidth = 1f, screenY = 0.875f, screenHeight = 0.125f) this.textAlign = Align.center this.textWrapping = false this.isLocalizationKey = true this.text = "editor.themeChooser.title" this.location.set(screenWidth = 0.95f, screenX = 0.025f) } this.elements += title themeEditor = ThemeEditorStage(editor, palette, this, this.camera, 362f, 392f).apply { this.location.set(screenX = 0f, screenY = 0f, screenWidth = 0f, screenHeight = 0f, pixelX = 20f, pixelY = 13f, pixelWidth = 362f, pixelHeight = 392f) this.visible = false } this.elements += themeEditor chooserButtonBar = Stage(this, this.camera, 346f, 34f).apply { location.set(screenX = 0f, screenY = 0f, screenWidth = 0f, screenHeight = 0f, pixelX = 20f, pixelY = 13f, pixelWidth = 346f, pixelHeight = 34f) this.elements += Button(palette, this, this.stage).apply { this.location.set(0f, 0f, 0f, 1f, 0f, 0f, 346f - 34f * 2f - 8f * 2f, 0f) this.addLabel(TextLabel(palette, this, this.stage).apply { this.isLocalizationKey = true this.text = "editor.themeEditor" this.textWrapping = true this.fontScaleMultiplier = 0.75f this.location.set(pixelWidth = -4f, pixelX = 2f) }) this.leftClickAction = { _, _ -> themeEditor.state = ThemeEditorStage.State.ChooseTheme themeEditor.update() updateVisibility(true) } } this.elements += object : Button<EditorScreen>(palette, this, this.stage) { override fun onLeftClick(xPercent: Float, yPercent: Float) { super.onLeftClick(xPercent, yPercent) LoadedThemes.reloadThemes(preferences, false) LoadedThemes.persistIndex(preferences) editor.theme = LoadedThemes.currentTheme themeList.apply { buttonScroll = 0 resetButtons() } } }.apply { this.location.set(0f, 0f, 0f, 1f, 346f - 34f * 2f - 8f, 0f, 34f, 0f) this.tooltipTextIsLocalizationKey = true this.tooltipText = "editor.themeChooser.reset" this.addLabel(ImageLabel(palette, this, this.stage).apply { this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_updatesfx")) }) } this.elements += Button(palette, this, this.stage).apply { this.location.set(0f, 0f, 0f, 1f, 346f - 34f, 0f, 34f, 0f) this.addLabel(ImageLabel(palette, this, this.stage).apply { this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_folder")) }) this.leftClickAction = { _, _ -> Gdx.net.openFileExplorer(LoadedThemes.THEMES_FOLDER) } this.tooltipTextIsLocalizationKey = true this.tooltipText = "editor.themeEditor.openContainingFolder" } } this.elements += chooserButtonBar } fun updateVisibility(inThemeEditor: Boolean) { themeEditor.visible = inThemeEditor chooserButtonBar.visible = !inThemeEditor themeList.visible = !inThemeEditor } fun resetEverything() { updateVisibility(false) themeList.resetButtons() title.text = "editor.themeChooser.title" } }
gpl-3.0
3de0e7b8bf601022590100bc357e89e7
44.986301
157
0.613139
4.445695
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/presentation/wishlist/reducer/WishlistReducer.kt
1
3119
package org.stepik.android.presentation.wishlist.reducer import org.stepik.android.presentation.wishlist.WishlistFeature.State import org.stepik.android.presentation.wishlist.WishlistFeature.Message import org.stepik.android.presentation.wishlist.WishlistFeature.Action import org.stepik.android.presentation.wishlist.model.WishlistAction import ru.nobird.app.core.model.mutate import ru.nobird.app.presentation.redux.reducer.StateReducer import javax.inject.Inject class WishlistReducer @Inject constructor() : StateReducer<State, Message, Action> { override fun reduce(state: State, message: Message): Pair<State, Set<Action>> = when (message) { is Message.InitMessage -> { if (state is State.Idle || state is State.Error && message.forceUpdate) { State.Loading to setOf(Action.FetchWishList) } else { null } } is Message.FetchWishlistSuccess -> { if (state is State.Loading) { val newState = if (message.wishlistedCourses.isNullOrEmpty()) { State.Empty } else { State.Content(message.wishlistedCourses) } newState to emptySet() } else { null } } is Message.FetchWishListError -> { if (state is State.Loading) { State.Error to emptySet() } else { null } } is Message.WishlistOperationUpdate -> { val resultingState = when (state) { is State.Content -> { val resultingList = if (message.wishlistOperationData.wishlistAction == WishlistAction.ADD) { state.wishListCourses.mutate { add(0, message.wishlistOperationData.courseId) } } else { state.wishListCourses.mutate { remove(message.wishlistOperationData.courseId) } } if (resultingList.isEmpty()) { State.Empty } else { State.Content(wishListCourses = resultingList) } } is State.Empty -> { if (message.wishlistOperationData.wishlistAction == WishlistAction.ADD) { State.Content(listOf(message.wishlistOperationData.courseId)) } else { state } } else -> state } resultingState to emptySet() } } ?: state to emptySet() }
apache-2.0
ac2ece42bc0cf4f4f031aada943c4360
39.519481
115
0.469061
6.127701
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/compose/theme/Typography.kt
1
2941
package com.nononsenseapps.feeder.ui.compose.theme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Typography import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration // Set of Material typography styles to start with val Typography = Typography( // TODO REMOVE // h1 = TextStyle( // fontWeight = FontWeight.Light, // fontSize = 34.sp, // letterSpacing = (-1.5).sp // ), // h2 = TextStyle( // fontWeight = FontWeight.Light, // fontSize = 30.sp, // letterSpacing = (-0.5).sp // ), // h3 = TextStyle( // fontWeight = FontWeight.Normal, // fontSize = 28.sp, // letterSpacing = 0.sp // ), // h4 = TextStyle( // fontWeight = FontWeight.Normal, // fontSize = 26.sp, // letterSpacing = 0.25.sp // ), // h5 = TextStyle( // fontWeight = FontWeight.Normal, // fontSize = 24.sp, // letterSpacing = 0.sp // ), // h6 = TextStyle( // fontWeight = FontWeight.Medium, // fontSize = 20.sp, // letterSpacing = 0.15.sp // ), ) @Composable fun LinkTextStyle(): TextStyle = TextStyle( color = MaterialTheme.colorScheme.primary, textDecoration = TextDecoration.Underline ) fun titleFontWeight(unread: Boolean) = if (unread) { FontWeight.Bold } else { FontWeight.Normal } @Composable fun FeedListItemTitleStyle(): SpanStyle = FeedListItemTitleTextStyle().toSpanStyle() @Composable fun FeedListItemTitleTextStyle(): TextStyle = MaterialTheme.typography.titleMedium @Composable fun FeedListItemStyle(): TextStyle = MaterialTheme.typography.bodyLarge @Composable fun FeedListItemFeedTitleStyle(): TextStyle = FeedListItemDateStyle() @Composable fun FeedListItemDateStyle(): TextStyle = MaterialTheme.typography.labelMedium @Composable fun TTSPlayerStyle(): TextStyle = MaterialTheme.typography.titleMedium @Composable fun CodeInlineStyle(): SpanStyle = SpanStyle( background = CodeBlockBackground(), fontFamily = FontFamily.Monospace ) /** * Has no background because it is meant to be put over a Surface which has the proper background. */ @Composable fun CodeBlockStyle(): TextStyle = MaterialTheme.typography.bodyMedium.merge( SpanStyle( fontFamily = FontFamily.Monospace ) ) @Composable fun CodeBlockBackground(): Color = MaterialTheme.colorScheme.surfaceVariant @Composable fun BlockQuoteStyle(): SpanStyle = MaterialTheme.typography.bodyLarge.toSpanStyle().merge( SpanStyle( fontWeight = FontWeight.Light ) )
gpl-3.0
9582231e80894a33aa4ea157e106ece6
24.798246
98
0.678341
4.256151
false
false
false
false
allotria/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/actions/MavenBuildMenu.kt
3
2449
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.navigator.actions import com.intellij.execution.Executor import com.intellij.openapi.actionSystem.* import com.intellij.openapi.project.DumbAware import org.jetbrains.idea.maven.project.actions.RunBuildAction import org.jetbrains.idea.maven.statistics.MavenActionsUsagesCollector class MavenBuildMenu : DefaultActionGroup(), DumbAware { private val actionManager = ActionManager.getInstance() override fun update(e: AnActionEvent) { val project = AnAction.getEventProject(e) ?: return childActionsOrStubs .filter { it is MyDelegatingAction || it is RunBuildAction } .forEach { remove(it) } Executor.EXECUTOR_EXTENSION_NAME.extensionList .filter { it.isApplicable(project) } .reversed() .forEach { val contextAction = actionManager.getAction(it.contextActionId) if (contextAction != null) { add(wrap(contextAction, it), Constraints.FIRST) } } ActionManager.getInstance().getAction("Maven.RunBuild")?.let { add(it, Constraints.FIRST) } } private interface MyDelegatingAction private class DelegatingActionGroup internal constructor(action: ActionGroup, private val executor: Executor) : EmptyAction.MyDelegatingActionGroup(action), MyDelegatingAction { override fun getChildren(e: AnActionEvent?): Array<AnAction> { val children = super.getChildren(e) return children.map { wrap(it, executor) }.toTypedArray() } override fun actionPerformed(e: AnActionEvent) { reportUsage(e, executor) super.actionPerformed(e) } } private class DelegatingAction internal constructor(action: AnAction, private val executor: Executor) : EmptyAction.MyDelegatingAction(action), MyDelegatingAction { override fun actionPerformed(e: AnActionEvent) { reportUsage(e, executor) super.actionPerformed(e) } } companion object { private fun wrap(action: AnAction, executor: Executor): AnAction = if (action is ActionGroup) DelegatingActionGroup(action, executor) else DelegatingAction(action, executor) private fun reportUsage(e: AnActionEvent, executor: Executor) { MavenActionsUsagesCollector.trigger(e.project, MavenActionsUsagesCollector.ActionID.RunBuildAction, e, executor) } } }
apache-2.0
d098e00343e8378a0a0f83b3558f8e8b
35.567164
140
0.738261
4.700576
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/codeinsight/htl/annotator/HtlWrongQuotesLiteralFixIntentionAction.kt
1
1104
package com.aemtools.codeinsight.htl.annotator import com.aemtools.common.intention.BaseHtlIntentionAction import com.aemtools.common.util.psiDocumentManager import com.aemtools.lang.htl.psi.mixin.HtlStringLiteralMixin import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.SmartPsiElementPointer /** * Inverts [HtlStringLiteralMixin] quotes. * * @author Dmytro Troynikov */ class HtlWrongQuotesLiteralFixIntentionAction( private val pointer: SmartPsiElementPointer<HtlStringLiteralMixin> ) : BaseHtlIntentionAction( text = { "Invert HTL Literal quotes" } ) { override fun invoke(project: Project, editor: Editor, file: PsiFile) { val element = pointer.element ?: return val document = project.psiDocumentManager().getDocument(file) ?: return val newValue = element.swapQuotes() val (start, end) = element.textRange.startOffset to element.textRange.endOffset document.replaceString(start, end, newValue) project.psiDocumentManager().commitDocument(document) } }
gpl-3.0
22bcbc4709ffeca85d1540c75c8c5a8c
30.542857
83
0.779891
4.506122
false
false
false
false
allotria/intellij-community
plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalUsageCollector.kt
2
4179
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.terminal import com.intellij.internal.statistic.collectors.fus.TerminalFusAwareHandler import com.intellij.internal.statistic.collectors.fus.os.OsVersionUsageCollector import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.terminal.TerminalShellCommandHandler import com.intellij.util.PathUtil import java.util.* class TerminalUsageTriggerCollector { companion object { @JvmStatic fun triggerSshShellStarted(project: Project) { FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, "ssh.exec") } @JvmStatic fun triggerCommandExecuted(project: Project) { FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, "terminal.command.executed") } @JvmStatic fun triggerSmartCommand(project: Project, workingDirectory: String?, localSession: Boolean, command: String, handler: TerminalShellCommandHandler, executed: Boolean) { val data = FeatureUsageData().addData("terminalCommandHandler", handler::class.java.name) if (handler is TerminalFusAwareHandler) { handler.fillData(project, workingDirectory, localSession, command, data) } val eventId = if (executed) { "terminal.smart.command.executed" } else { "terminal.smart.command.not.executed" } FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, eventId, data) } @JvmStatic fun triggerLocalShellStarted(project: Project, shellCommand: Array<String>) { val osVersion = OsVersionUsageCollector.parse(SystemInfo.OS_VERSION) FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, "local.exec", FeatureUsageData() .addData("os-version", if (osVersion == null) "unknown" else osVersion.toCompactString()) .addData("shell", getShellNameForStat(shellCommand.firstOrNull())) ) } @JvmStatic private fun getShellNameForStat(shellName: String?): String { if (shellName == null) return "unspecified" var name = shellName.trimStart() val ind = name.indexOf(" ") name = if (ind < 0) name else name.substring(0, ind) if (SystemInfo.isFileSystemCaseSensitive) { name = name.toLowerCase(Locale.ENGLISH) } name = PathUtil.getFileName(name) name = trimKnownExt(name) return if (KNOWN_SHELLS.contains(name)) name else "other" } private fun trimKnownExt(name: String): String { val ext = PathUtil.getFileExtension(name) return if (ext != null && KNOWN_EXTENSIONS.contains(ext)) name.substring(0, name.length - ext.length - 1) else name } } } private const val GROUP_ID = "terminalShell" private val KNOWN_SHELLS = setOf("activate", "anaconda3", "bash", "cexec", "cmd", "cmder", "cmder_shell", "cygwin", "fish", "git", "git-bash", "git-cmd", "init", "miniconda3", "msys2_shell", "powershell", "pwsh", "sh", "tcsh", "ubuntu", "ubuntu1804", "wsl", "zsh") private val KNOWN_EXTENSIONS = setOf("exe", "bat", "cmd")
apache-2.0
3eec746de22941218b777f813a88cef5
40.386139
140
0.569275
5.028881
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaSliderUI.kt
3
11553
// 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.ide.ui.laf.darcula.ui import com.intellij.ui.JBColor import com.intellij.ui.paint.LinePainter2D import com.intellij.util.ui.JBUI import java.awt.* import java.awt.geom.GeneralPath import javax.swing.JComponent import javax.swing.JSlider import javax.swing.LookAndFeel import javax.swing.SwingConstants import javax.swing.plaf.basic.BasicSliderUI public open class DarculaSliderUI(b: JComponent? = null) : BasicSliderUI(b as JSlider) { companion object { @Suppress("UNUSED_PARAMETER") @JvmStatic fun createUI(c: JComponent): DarculaSliderUI = DarculaSliderUI(c) } private val theme = DarculaSliderUIThemes() override fun paintThumb(g: Graphics) { val g2d = g.create() as Graphics2D g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) try { val path = if (slider.orientation == SwingConstants.HORIZONTAL) { val x1 = thumbRect.x + theme.focusBorderThickness val x2 = x1 + thumbRect.width - (theme.focusBorderThickness * 2) val x3 = theme.thumbHalfWidth + 1 + x1 val y1 = thumbRect.y + theme.focusBorderThickness val y2 = y1 + theme.thumbOverhang val y3 = y1 + thumbRect.height - (theme.focusBorderThickness * 2) getHPath(x1, y1, x2, y2, x3, y3) } else { val x1 = thumbRect.x + theme.focusBorderThickness val x2 = x1 + theme.thumbOverhang val x3 = x1 + thumbRect.width - (theme.focusBorderThickness * 2) val y1 = thumbRect.y + theme.focusBorderThickness val y2 = y1 + theme.thumbHalfWidth + 1 val y3 = y1 + thumbRect.height - (theme.focusBorderThickness * 2) getVPath(x1, y1, x2, x3, y2, y3) } if (slider.hasFocus()) { g2d.stroke = BasicStroke((theme.focusBorderThickness + theme.borderThickness).toFloat()) g2d.paint = theme.focusedOuterColor g2d.draw(path) } g2d.paint = if (slider.isEnabled) theme.buttonColor else theme.disabledButtonColor g2d.fill(path) g2d.paint = if (slider.hasFocus()) { theme.focusedBorderColor } else if (slider.isEnabled) { theme.buttonBorderColor } else { theme.disabledButtonBorderColor } g2d.stroke = BasicStroke(theme.borderThickness.toFloat()) g2d.draw(path) } finally { g2d.dispose() } } private fun getHPath(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int): GeneralPath { val path = GeneralPath() path.moveTo((x1 + theme.arc).toDouble(), y1.toDouble()) path.lineTo((x2 - theme.arc).toDouble(), y1.toDouble()) path.lineTo(x2.toDouble(), (y1 + theme.arc).toDouble()) // path.quadTo(path.currentPoint.x, path.currentPoint.y, x2.toDouble(), (y1 + arc).toDouble()) path.lineTo(x2.toDouble(), y2.toDouble()) path.lineTo(x3.toDouble(), y3.toDouble()) path.lineTo(x1.toDouble(), y2.toDouble()) path.lineTo(x1.toDouble(), (y1 + theme.arc).toDouble()) path.lineTo(x1 + theme.arc.toDouble(), y1.toDouble()) // path.quadTo(path.currentPoint.x, path.currentPoint.y, x1 + arc.toDouble(), y1.toDouble()) path.closePath() return path } private fun getVPath(x1: Int, y1: Int, x2: Int, x3: Int, y2: Int, y3: Int): GeneralPath { val path = GeneralPath() path.moveTo((x1 + theme.arc).toDouble(), y1.toDouble()) path.lineTo(x2.toDouble(), y1.toDouble()) path.lineTo(x3.toDouble(), y2.toDouble()) path.lineTo(x2.toDouble(), y3.toDouble()) path.lineTo((x1 + theme.arc).toDouble(), y3.toDouble()) path.lineTo(x1.toDouble(), (y3 - theme.arc).toDouble()) // path.quadTo(path.currentPoint.x, path.currentPoint.y, x1.toDouble(), (y3 - arc).toDouble()) path.lineTo(x1.toDouble(), (y1 + theme.arc).toDouble()) path.lineTo((x1 + theme.arc).toDouble(), y1.toDouble()) //path.quadTo(path.currentPoint.x, path.currentPoint.y, (x1 + arc).toDouble(), y1.toDouble()) path.closePath() return path } override fun calculateThumbLocation() { super.calculateThumbLocation() if (slider.orientation == JSlider.HORIZONTAL) { val valuePosition = xPositionForValue(slider.value) thumbRect.x = valuePosition - theme.focusedThumbHalfWidth thumbRect.y = trackRect.y } else { val valuePosition = yPositionForValue(slider.value) thumbRect.x = trackRect.x thumbRect.y = valuePosition - theme.focusedThumbHalfWidth } } override fun setThumbLocation(x: Int, y: Int) { super.setThumbLocation(x, y) slider.repaint() } override fun getBaseline(c: JComponent?, width: Int, height: Int): Int { if (slider.orientation == SwingConstants.HORIZONTAL) { return theme.thumbOverhang + (2 * theme.focusBorderThickness) + slider.insets.top + theme.borderThickness } else { return super.getBaseline(c, width, height) } } override fun paintTrack(g: Graphics) { val g2d = g.create() as Graphics2D g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2d.paint = if (slider.isEnabled) theme.trackColor else theme.disabledTrackColor try { if (slider.orientation == SwingConstants.HORIZONTAL) { val y = thumbRect.y + theme.focusBorderThickness + theme.thumbOverhang - theme.trackThickness LinePainter2D.paint(g2d, trackRect.getX(), y.toDouble(), trackRect.maxX, y.toDouble(), LinePainter2D.StrokeType.INSIDE, theme.trackThickness.toDouble()) } else { val x = thumbRect.x + theme.focusBorderThickness + theme.thumbOverhang - theme.trackThickness LinePainter2D.paint(g2d, x.toDouble(), trackRect.y.toDouble(), x.toDouble(), trackRect.maxY, LinePainter2D.StrokeType.INSIDE, theme.trackThickness.toDouble()) } } finally { g2d.dispose() } } override fun paintFocus(g: Graphics) { paintThumb(g) } override fun getThumbSize(): Dimension { val width = (theme.focusedThumbHalfWidth * 2) + 1 return if (slider.orientation == SwingConstants.HORIZONTAL) Dimension(width, theme.thumbHeight) else Dimension(theme.thumbHeight, width) } override fun calculateTrackBuffer() { if (slider.paintLabels && slider.labelTable != null) { val highLabel = highestValueLabel val lowLabel = lowestValueLabel if (slider.orientation == JSlider.HORIZONTAL) { if (highLabel != null && lowLabel != null) { trackBuffer = highLabel.bounds.width.coerceAtLeast(lowLabel.bounds.width) / 2 } trackBuffer = trackBuffer.coerceAtLeast(theme.focusedThumbHalfWidth) } else { if (highLabel != null && lowLabel != null) { trackBuffer = highLabel.bounds.height.coerceAtLeast(lowLabel.bounds.height) / 2 } trackBuffer = trackBuffer.coerceAtLeast(theme.focusedThumbHalfWidth) + 1 } } else { trackBuffer = theme.focusedThumbHalfWidth + 1 } } override fun calculateLabelRect() { super.calculateLabelRect() if (slider.orientation == JSlider.HORIZONTAL) { labelRect.y += theme.tickBottom } else { labelRect.x += theme.tickBottom } } override fun calculateTickRect() { if (slider.orientation == JSlider.HORIZONTAL) { tickRect.x = trackRect.x tickRect.y = trackRect.y + theme.focusBorderThickness + theme.thumbOverhang + theme.tickTop tickRect.width = trackRect.width tickRect.height = if (slider.paintTicks) tickLength else 0 } else { tickRect.width = if (slider.paintTicks) tickLength else 0 if (slider.componentOrientation.isLeftToRight) { tickRect.x = trackRect.x + theme.focusBorderThickness + theme.thumbOverhang + theme.tickTop } else { tickRect.x = trackRect.x - (theme.focusBorderThickness + theme.thumbOverhang + theme.tickTop) } tickRect.y = trackRect.y tickRect.height = trackRect.height } } override fun getTickLength(): Int { return theme.majorTickHeight } override fun installDefaults(slider: JSlider?) { LookAndFeel.installColorsAndFont(slider, "Slider.background", "Slider.foreground", "Slider.font") focusInsets = JBUI.emptyInsets() } override fun paintMinorTickForHorizSlider(g: Graphics, tickBounds: Rectangle, x_: Int) { g as Graphics2D g.color = if (slider.isEnabled) theme.tickColor else theme.disabledTickColor val x = x_ + 1 g.stroke = BasicStroke(theme.borderThickness.toFloat()) g.drawLine(x, 0, x, theme.minorTickHeight) } override fun paintMajorTickForHorizSlider(g: Graphics, tickBounds: Rectangle, x_: Int) { g as Graphics2D g.color = if (slider.isEnabled) theme.tickColor else theme.disabledTickColor val x = x_ + 1 g.stroke = BasicStroke(theme.borderThickness.toFloat()) g.drawLine(x, 0, x, theme.majorTickHeight) } override fun paintMinorTickForVertSlider(g: Graphics, tickBounds: Rectangle, y_: Int) { g as Graphics2D g.color = if (slider.isEnabled) theme.tickColor else theme.disabledTickColor val y = y_ + 1 g.stroke = BasicStroke(theme.borderThickness.toFloat()) g.drawLine(0, y, theme.minorTickHeight, y) } override fun paintMajorTickForVertSlider(g: Graphics, tickBounds: Rectangle, y_: Int) { g as Graphics2D g.color = if (slider.isEnabled) theme.tickColor else theme.disabledTickColor val y = y_ + 1 g.stroke = BasicStroke(theme.borderThickness.toFloat()) g.drawLine(0, y, theme.majorTickHeight, y) } } public class DarculaSliderUIThemes { val thumbHalfWidth = JBUI.scale(7) val thumbHeight = JBUI.scale(24) val focusedThumbHalfWidth = thumbHalfWidth + focusBorderThickness val arc: Int get() = JBUI.scale(1) val trackThickness: Int get() = JBUI.scale(3) val focusBorderThickness: Int get() = JBUI.scale(3) val focusedBorderColor: Color get() = JBUI.CurrentTheme.Focus.focusColor() val borderThickness: Int get() = JBUI.scale(1) val thumbOverhang: Int get() = JBUI.scale(10) val buttonColor: Color get() = JBColor.namedColor("Slider.buttonColor", JBColor(0xFFFFFF, 0x9B9E9E)) val buttonBorderColor: Color get() = JBColor.namedColor("Slider.buttonBorderColor", JBColor(0xA6A6A6, 0x393D3F)) val trackColor: Color get() = JBColor.namedColor("Slider.trackColor", JBColor(0xC7C7C7, 0x666666)) val tickColor: Color get() = JBColor.namedColor("Slider.tickColor", JBColor(0x999999, 0x808080)) val focusedOuterColor: Color get() = JBUI.CurrentTheme.Component.FOCUSED_BORDER_COLOR val disabledButtonColor: Color get() = JBColor.PanelBackground val disabledButtonBorderColor: Color get() = JBColor.namedColor("Component.disabledBorderColor", 0x87AFDA) val disabledTrackColor: Color get() = disabledButtonBorderColor val disabledTickColor: Color get() = disabledButtonBorderColor val tickTop: Int get() = JBUI.scale(6) val tickBottom: Int get() = JBUI.scale(2) val minorTickHeight: Int get() = JBUI.scale(4) val majorTickHeight: Int get() = JBUI.scale(7) }
apache-2.0
7f64fd5c1677e61232eb6ee1da48b483
35.679365
140
0.663637
3.914944
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/model/App.kt
1
2118
/* * (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r) * * 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.faendir.acra.model import com.faendir.acra.util.equalsBy import com.fasterxml.jackson.annotation.JsonIgnore import org.hibernate.annotations.OnDelete import org.hibernate.annotations.OnDeleteAction import javax.persistence.Access import javax.persistence.AccessType import javax.persistence.CascadeType import javax.persistence.CollectionTable import javax.persistence.Column import javax.persistence.ElementCollection import javax.persistence.Embeddable import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.OneToOne /** * @author Lukas * @since 08.12.2017 */ @Entity class App( val name: String, @JsonIgnore @OneToOne(cascade = [CascadeType.ALL], optional = false, orphanRemoval = true, fetch = FetchType.LAZY) @OnDelete(action = OnDeleteAction.CASCADE) var reporter: User ) { var configuration: Configuration = Configuration() @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id = 0 override fun equals(other: Any?) = equalsBy(other, App::id) override fun hashCode() = id @Embeddable class Configuration( var minScore: Int = 95, @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "app_report_columns") @Column(name = "path") var customReportColumns: MutableList<String> = mutableListOf() ) }
apache-2.0
58cf3d4f5be14bb6490d8cb973c940be
30.626866
106
0.750236
4.270161
false
true
false
false
zdary/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettingsWatcher.kt
2
2406
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.project import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesListener.Companion.subscribeOnVirtualFilesChanges import com.intellij.openapi.externalSystem.autoimport.changes.FilesChangesListener import com.intellij.openapi.externalSystem.autoimport.settings.ReadAsyncSupplier import com.intellij.openapi.util.io.FileUtil import org.jetbrains.idea.maven.server.MavenDistributionsCache import java.util.concurrent.ExecutorService class MavenGeneralSettingsWatcher private constructor( private val manager: MavenProjectsManager, private val watcher: MavenProjectsManagerWatcher, backgroundExecutor: ExecutorService, parentDisposable: Disposable ) { private val generalSettings get() = manager.generalSettings private val embeddersManager get() = manager.embeddersManager private val settingsFiles: Set<String> get() = collectSettingsFiles().map { FileUtil.toCanonicalPath(it) }.toSet() private fun collectSettingsFiles() = sequence { generalSettings.effectiveUserSettingsIoFile?.path?.let { yield(it) } generalSettings.effectiveGlobalSettingsIoFile?.path?.let { yield(it) } } private fun fireSettingsChange() { embeddersManager.reset() MavenDistributionsCache.getInstance(manager.project).cleanCaches(); watcher.scheduleUpdateAll(true, true) } private fun fireSettingsXmlChange() { generalSettings.changed() // fireSettingsChange() will be called indirectly by pathsChanged listener on GeneralSettings object } init { generalSettings.addListener(::fireSettingsChange, parentDisposable) val filesProvider = ReadAsyncSupplier.readAction(::settingsFiles, backgroundExecutor, this) subscribeOnVirtualFilesChanges(false, filesProvider, object : FilesChangesListener { override fun apply() = fireSettingsXmlChange() }, parentDisposable) } companion object { @JvmStatic fun registerGeneralSettingsWatcher( manager: MavenProjectsManager, watcher: MavenProjectsManagerWatcher, backgroundExecutor: ExecutorService, parentDisposable: Disposable ) { MavenGeneralSettingsWatcher(manager, watcher, backgroundExecutor, parentDisposable) } } }
apache-2.0
34e32564445160c295f74fbac86787f9
39.1
140
0.793017
5.230435
false
false
false
false
leafclick/intellij-community
platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt
1
3110
// 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.testFramework import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.refreshVfs import com.intellij.util.SmartList import com.intellij.util.io.* import com.intellij.util.lang.CompoundRuntimeException import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement import java.io.IOException import java.nio.file.Path import java.nio.file.Paths import kotlin.properties.Delegates class TemporaryDirectory : ExternalResource() { companion object { @JvmStatic fun generateTemporaryPath(fileName: String): Path { val tempDirectory = Paths.get(FileUtilRt.getTempDirectory()) var path = tempDirectory.resolve(fileName) if (!path.exists()) { return path } var i = 0 var ext = FileUtilRt.getExtension(fileName) if (ext.isNotEmpty()) { ext = ".$ext" } val name = FileUtilRt.getNameWithoutExtension(fileName) do { path = tempDirectory.resolve("${name}_$i$ext") i++ } while (path.exists() && i < 9) if (path.exists()) { throw IOException("Cannot generate unique random path with '$name' prefix under '$path'") } return path } } private val paths = SmartList<Path>() private var sanitizedName: String by Delegates.notNull() override fun apply(base: Statement, description: Description): Statement { sanitizedName = sanitizeFileName(description.methodName) return super.apply(base, description) } override fun after() { val errors = SmartList<Throwable>() for (path in paths) { try { path.delete() } catch (e: Throwable) { errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) paths.clear() } fun newPath(directoryName: String? = null, refreshVfs: Boolean = false): Path { val path = generatePath(directoryName) if (refreshVfs) { path.refreshVfs() } return path } private fun generatePath(suffix: String?): Path { var fileName = sanitizedName if (suffix != null) { fileName += "_$suffix" } val path = generateTemporaryPath(fileName) paths.add(path) return path } fun newVirtualDirectory(directoryName: String? = null): VirtualFile { val path = generatePath(directoryName) path.createDirectories() val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.systemIndependentPath) VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile) return virtualFile!! } } fun VirtualFile.writeChild(relativePath: String, data: String) = VfsTestUtil.createFile(this, relativePath, data) fun VirtualFile.writeChild(relativePath: String, data: ByteArray) = VfsTestUtil.createFile(this, relativePath, data)
apache-2.0
d834801eb4846f90e4f599e97513e377
28.913462
140
0.703537
4.49422
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/navigation/availability/ScannerSwitch.kt
1
1571
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[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.vrem.wifianalyzer.navigation.availability import com.vrem.wifianalyzer.MainContext import com.vrem.wifianalyzer.R internal val navigationOptionScannerSwitchOff: NavigationOption = { it.optionMenu.menu?.let { menu -> menu.findItem(R.id.action_scanner).isVisible = false } } internal val navigationOptionScannerSwitchOn: NavigationOption = { it.optionMenu.menu?.let { menu -> val menuItem = menu.findItem(R.id.action_scanner) menuItem.isVisible = true if (MainContext.INSTANCE.scannerService.running()) { menuItem.setTitle(R.string.scanner_pause) menuItem.setIcon(R.drawable.ic_pause) } else { menuItem.setTitle(R.string.scanner_play) menuItem.setIcon(R.drawable.ic_play_arrow) } } }
gpl-3.0
c3d734e1d1b273e49cd46b6e5542a69c
37.317073
90
0.716741
4.223118
false
false
false
false
zdary/intellij-community
platform/util-ex/src/com/intellij/util/Plow.kt
1
3544
// 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.util import com.intellij.openapi.progress.ProgressManager import com.intellij.util.containers.ContainerUtil import org.jetbrains.annotations.ApiStatus /** * A Processor + Flow, or the Poor man's Flow: a reactive-stream-like wrapper around [Processor]. * * Instead of creating the [Processor] manually - create a [Plow] and work with the Processor inside a lambda. * If your method accepts the processor it is the good idea to return a [Plow] instead to avoid the "return value in parameter" semantic * * Itself [Plow] is stateless and ["Cold"](https://projectreactor.io/docs/core/3.3.9.RELEASE/reference/index.html#reactor.hotCold), * meaning that the same instance of [Plow] could be reused several times (by reevaluating the sources), * but depending on the idempotence of the [producingFunction] this contract could be violated, * so to be careful, and it is better to obtain the new [Plow] instance each time. */ @ApiStatus.Experimental class Plow<T> private constructor(private val producingFunction: (Processor<T>) -> Boolean) { @Suppress("UNCHECKED_CAST") fun processWith(processor: Processor<in T>): Boolean = producingFunction(processor as Processor<T>) fun <P : Processor<T>> processTo(processor: P): P = processor.apply { producingFunction(this) } fun findAny(): T? = processTo(CommonProcessors.FindFirstProcessor()).foundValue fun find(test: (T) -> Boolean): T? = processTo(object : CommonProcessors.FindFirstProcessor<T>() { override fun accept(t: T): Boolean = test(t) }).foundValue fun <C : MutableCollection<T>> collectTo(coll: C): C = coll.apply { processTo(CommonProcessors.CollectProcessor(this)) } fun toList(): List<T> = ContainerUtil.unmodifiableOrEmptyList(collectTo(SmartList())) fun toSet(): Set<T> = ContainerUtil.unmodifiableOrEmptySet(collectTo(HashSet())) fun toArray(array: Array<T>): Array<T> = processTo(CommonProcessors.CollectProcessor()).toArray(array) fun <R> transform(transformation: (Processor<R>) -> (Processor<T>)): Plow<R> = Plow { pr -> producingFunction(transformation(pr)) } fun <R> map(mapping: (T) -> R): Plow<R> = transform { pr -> Processor { v -> pr.process(mapping(v)) } } fun <R> mapNotNull(mapping: (T) -> R?): Plow<R> = transform { pr -> Processor { v -> mapping(v)?.let { pr.process(it) } ?: true } } fun filter(test: (T) -> Boolean): Plow<T> = transform { pr -> Processor { v -> !test(v) || pr.process(v) } } fun <R> mapToProcessor(mapping: (T, Processor<R>) -> Boolean): Plow<R> = Plow { rProcessor -> producingFunction(Processor { t -> mapping(t, rProcessor) }) } fun <R> flatMap(mapping: (T) -> Plow<R>): Plow<R> = mapToProcessor { t, processor -> mapping(t).processWith(processor) } fun cancellable(): Plow<T> = transform { pr -> Processor { v -> ProgressManager.checkCanceled();pr.process(v) } } companion object { @JvmStatic fun <T> empty(): Plow<T> = of { true } @JvmStatic fun <T> of(processorCall: (Processor<T>) -> Boolean): Plow<T> = Plow(processorCall) @JvmStatic @JvmName("ofArray") fun <T> Array<T>.toPlow(): Plow<T> = Plow { pr -> all { pr.process(it) } } @JvmStatic @JvmName("ofIterable") fun <T> Iterable<T>.toPlow(): Plow<T> = Plow { pr -> all { pr.process(it) } } @JvmStatic fun <T> concat(vararg plows: Plow<T>): Plow<T> = of { pr -> plows.all { it.processWith(pr) } } } }
apache-2.0
cb8d5aa61e95f2d304f6f270f9b578c9
45.038961
140
0.689334
3.657379
false
true
false
false
zdary/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrMapConstructorPropertyReference.kt
12
2601
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.references import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentLabel import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrConstructorCall import org.jetbrains.plugins.groovy.lang.resolve.api.* class GrMapConstructorPropertyReference(element: GrArgumentLabel) : GroovyPropertyWriteReferenceBase<GrArgumentLabel>(element) { override val receiverArgument: Argument? get() { val label: GrArgumentLabel = element val namedArgument: GrNamedArgument = label.parent as GrNamedArgument // hard cast because reference must be checked before val constructorReference: GroovyConstructorReference = requireNotNull(getConstructorReference(namedArgument)) val resolveResult: GroovyResolveResult = constructorReference.resolveClass() ?: return null val clazz: PsiClass = resolveResult.element as? PsiClass ?: return null val type: PsiClassType = JavaPsiFacade.getElementFactory(label.project).createType(clazz, resolveResult.substitutor) return JustTypeArgument(type) } override val propertyName: String get() = requireNotNull(element.name) override val argument: Argument? get() = (element.parent as GrNamedArgument).expression?.let(::ExpressionArgument) companion object { @JvmStatic fun getConstructorReference(argument: GrNamedArgument): GroovyConstructorReference? { val parent: PsiElement? = argument.parent if (parent is GrListOrMap) { return parent.constructorReference ?: getReferenceFromDirectInvocation(parent.parent) } return getReferenceFromDirectInvocation(parent) } private fun getReferenceFromDirectInvocation(element: PsiElement?) : GroovyConstructorReference? { if (element is GrArgumentList) { val parent: PsiElement? = element.getParent() if (parent is GrConstructorCall) { return parent.constructorReference } } return null } } }
apache-2.0
657d3f50cfd40e15b2f990236ab3ff8a
47.166667
140
0.780469
4.954286
false
false
false
false
mrbublos/vkm
app/src/main/java/vkm/vkm/utils/Extensions.kt
1
5251
package vkm.vkm.utils import android.content.Context import android.media.MediaPlayer import android.util.Log import android.widget.Toast import com.github.kittinunf.fuel.android.core.Json import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.json.JSONArray import org.json.JSONObject import vkm.vkm.DownloadManager import java.io.File import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.security.MessageDigest import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlin.reflect.KMutableProperty import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.javaType fun ByteArray?.toHexString(): String { if (this == null || isEmpty()) { return "" } val ret = StringBuilder() forEach { ret.append(String.format("%02x", it)) } return ret.toString() } fun ByteArray?.md5(): String { if (this == null) { return ""} return MessageDigest.getInstance("MD5").digest(this).toHexString() } fun String.md5(charset: Charset = StandardCharsets.UTF_8): String { return toByteArray(charset).md5() } fun String?.beginning(length: Int): String { if (this == null) { return "" } return filterIndexed { index, _ -> index < length } } fun String?.log() { this?.takeIf { isNotEmpty() }?.let { Log.v("vkmLog", this) } } fun String?.logE(e: Throwable? = null) { this?.takeIf { isNotEmpty() }?.let { Log.e("vkmLog", this, e) } } fun String.toComposition(): Composition { val composition = Composition() val properties = split("|VKM|") val map = mutableMapOf<String, String>() properties.forEach { serializedProperty -> val pair = serializedProperty.split("=VKM=") if (pair.size > 1) { map[pair[0]] = pair[1] } } composition::class.memberProperties.forEach { val kMutableProperty = it as KMutableProperty<*> map[it.name]?.let { propertyValue -> when (kMutableProperty.returnType.javaType) { Int::class.javaPrimitiveType, Int::class.javaObjectType -> kMutableProperty.setter.call(composition, propertyValue.toInt()) Long::class.javaPrimitiveType, Long::class.javaObjectType -> kMutableProperty.setter.call(composition, propertyValue.toLong()) String::class.java -> kMutableProperty.setter.call(composition, propertyValue) } } } return composition } fun String?.toast(context: Context?, length: Int = Toast.LENGTH_SHORT): String? { if (this == null) { return this } val me = this context?.let { GlobalScope.launch(Dispatchers.Main) { Toast.makeText(context, me, length).show() } } return this } fun String?.normalize() : String? { if (this == null) { return null } return this.trim().toLowerCase().replace(" ", "") } fun Composition.serialize(): String { return Composition::class.memberProperties.joinToString(separator = "|VKM|") { "${it.name}=VKM=${it.get(this)}" } } fun Composition.matches(string: String): Boolean { return name.contains(string) || artist.contains(string) } fun Composition.fileName(): String { val artistNormalized = artist.trim().beginning(32).replace(' ', '_').replace('/', '_') val nameNormalized = name.trim().beginning(32).replace(' ', '_').replace('/', '_') return "$artistNormalized-$nameNormalized.mp3" } fun Composition.localFile(): File? { val file = DownloadManager.getDownloadDir().resolve(fileName()) return if (file.exists()) file else null } fun Composition?.equalsTo(other: Composition?): Boolean { return this?.name.normalize() == other?.name.normalize() && this?.artist.normalize() == other?.artist.normalize() } suspend fun MediaPlayer.loadAsync() { suspendCoroutine<Unit> { continuation -> this.setOnPreparedListener { continuation.resume(Unit) } this.prepareAsync() } } fun JSONObject.gets(name: String): String { return try { this.get(name).toString() } catch (e: Exception) { "" } } fun JSONObject.geta(name: String): JSONArray { return try { this.getJSONArray(name) } catch (e: Exception) { JSONArray("[]") } } fun JSONObject.geto(name: String): JSONObject { return try { this.getJSONObject(name) } catch (e: Exception) { JSONObject("{}") } } fun JSONObject.getl(name: String): Long { return try { this.getLong(name) } catch (e: Exception) { 0L } } fun <R> JSONArray.map(action: (obj: JSONObject) -> R): MutableList<R> { return (0 until this.length()).map { action(this.get(it) as JSONObject) }.toMutableList() } fun <R> JSONArray.mapArr(action: (obj: JSONArray) -> R): MutableList<R> { return (0 until this.length()).map { action(this.get(it) as JSONArray) }.toMutableList() } fun Json?.safeObj(): JSONObject { return try { this?.obj() ?: JSONObject() } catch (e: Exception) { JSONObject() } } fun Json?.safeArr(): JSONArray { return try { this?.array() ?: JSONArray() } catch (e: Exception) { JSONArray() } }
gpl-3.0
ed2d5d593319f31cca843e8edf74a883
27.085561
117
0.648448
3.972012
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/javaInterop/objectMethods/cloneableClassWithoutClone.kt
2
355
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE data class A(val s: String) : Cloneable { fun externalClone(): A = clone() as A } fun box(): String { val a = A("OK") val b = a.externalClone() if (a != b) return "Fail equals" if (a === b) return "Fail identity" return b.s }
apache-2.0
5ec82fa6589e8c77dfafe8dbb2d59114
24.357143
72
0.614085
3.317757
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/InvalidParameter.kt
1
1139
@file:JvmName("InvalidParameterUtils") package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.enums.ErrorCodeType import com.vimeo.networking2.enums.asEnum /** * Similar to [ApiError] object, this holds error codes/error messages relevant to a specific invalid field. * * @param field Name of the invalid field. * @param errorCode Error code for the invalid field. See [ApiError.errorCodeType]. * @param error The user readable error message detailing why the request was invalid. * @param developerMessage Detailed description of why the field is invalid. */ @JsonClass(generateAdapter = true) data class InvalidParameter( @Json(name = "field") val field: String? = null, @Json(name = "error_code") val errorCode: String? = null, @Json(name = "error") val error: String? = null, @Json(name = "developer_message") val developerMessage: String? = null ) /** * @see InvalidParameter.errorCode * @see ErrorCodeType */ val InvalidParameter.errorCodeType: ErrorCodeType get() = errorCode.asEnum(ErrorCodeType.DEFAULT)
mit
61f303ecbe13d193a5e4d0d80aa00fb1
27.475
108
0.738367
3.914089
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/permissions/PermissionsModule.kt
2
6282
// Copyright 2015-present 650 Industries. All rights reserved. package abi42_0_0.expo.modules.permissions import android.Manifest import android.content.Context import android.os.Bundle import abi42_0_0.expo.modules.interfaces.permissions.Permissions import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponse import abi42_0_0.expo.modules.interfaces.permissions.PermissionsResponseListener import abi42_0_0.expo.modules.permissions.requesters.BackgroundLocationRequester import abi42_0_0.expo.modules.permissions.requesters.ForegroundLocationRequester import abi42_0_0.expo.modules.permissions.requesters.LegacyLocationRequester import abi42_0_0.expo.modules.permissions.requesters.NotificationRequester import abi42_0_0.expo.modules.permissions.requesters.PermissionRequester import abi42_0_0.expo.modules.permissions.requesters.RemindersRequester import abi42_0_0.expo.modules.permissions.requesters.SimpleRequester import abi42_0_0.org.unimodules.core.ExportedModule import abi42_0_0.org.unimodules.core.ModuleRegistry import abi42_0_0.org.unimodules.core.Promise import abi42_0_0.org.unimodules.core.interfaces.ExpoMethod internal const val ERROR_TAG = "ERR_PERMISSIONS" class PermissionsModule(context: Context) : ExportedModule(context) { private lateinit var mPermissions: Permissions private lateinit var mRequesters: Map<String, PermissionRequester> @Throws(IllegalStateException::class) override fun onCreate(moduleRegistry: ModuleRegistry) { mPermissions = moduleRegistry.getModule(Permissions::class.java) ?: throw IllegalStateException("Couldn't find implementation for Permissions interface.") val notificationRequester = NotificationRequester(context) val contactsRequester = if (mPermissions.isPermissionPresentInManifest(Manifest.permission.WRITE_CONTACTS)) { SimpleRequester(Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS) } else { SimpleRequester(Manifest.permission.READ_CONTACTS) } mRequesters = mapOf( // Legacy requester PermissionsTypes.LOCATION.type to LegacyLocationRequester( if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.Q) { mPermissions.isPermissionPresentInManifest(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } else { false } ), PermissionsTypes.LOCATION_FOREGROUND.type to ForegroundLocationRequester(), PermissionsTypes.LOCATION_BACKGROUND.type to BackgroundLocationRequester(), PermissionsTypes.CAMERA.type to SimpleRequester(Manifest.permission.CAMERA), PermissionsTypes.CONTACTS.type to contactsRequester, PermissionsTypes.AUDIO_RECORDING.type to SimpleRequester(Manifest.permission.RECORD_AUDIO), PermissionsTypes.MEDIA_LIBRARY_WRITE_ONLY.type to SimpleRequester(Manifest.permission.WRITE_EXTERNAL_STORAGE), PermissionsTypes.MEDIA_LIBRARY.type to SimpleRequester(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), PermissionsTypes.CALENDAR.type to SimpleRequester(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR), PermissionsTypes.SMS.type to SimpleRequester(Manifest.permission.READ_SMS), PermissionsTypes.NOTIFICATIONS.type to notificationRequester, PermissionsTypes.USER_FACING_NOTIFICATIONS.type to notificationRequester, PermissionsTypes.SYSTEM_BRIGHTNESS.type to SimpleRequester(Manifest.permission.WRITE_SETTINGS), PermissionsTypes.REMINDERS.type to RemindersRequester() ) } @Throws(IllegalStateException::class) private fun getRequester(permissionType: String): PermissionRequester { return mRequesters[permissionType] ?: throw IllegalStateException("Unrecognized permission type: $permissionType") } override fun getName(): String = "ExpoPermissions" @ExpoMethod fun getAsync(requestedPermissionsTypes: ArrayList<String>, promise: Promise) { try { delegateToPermissionsServiceIfNeeded(requestedPermissionsTypes, mPermissions::getPermissions, promise) } catch (e: IllegalStateException) { promise.reject(ERROR_TAG + "_UNKNOWN", "Failed to get permissions", e) } } @ExpoMethod fun askAsync(requestedPermissionsTypes: ArrayList<String>, promise: Promise) { try { delegateToPermissionsServiceIfNeeded(requestedPermissionsTypes, mPermissions::askForPermissions, promise) } catch (e: IllegalStateException) { promise.reject(ERROR_TAG + "_UNKNOWN", "Failed to get permissions", e) } } private fun createPermissionsResponseListener(requestedPermissionsTypes: ArrayList<String>, promise: Promise) = PermissionsResponseListener { permissionsNativeStatus -> promise.resolve(parsePermissionsResponse(requestedPermissionsTypes, permissionsNativeStatus)) } private fun delegateToPermissionsServiceIfNeeded(permissionTypes: ArrayList<String>, permissionsServiceDelegate: (PermissionsResponseListener, Array<out String>) -> Unit, promise: Promise) { val androidPermissions = getAndroidPermissionsFromList(permissionTypes) // Some permissions like `NOTIFICATIONS` or `USER_FACING_NOTIFICATIONS` aren't supported by the android. // So, if the user asks/gets those permissions, we can return status immediately. if (androidPermissions.isEmpty()) { // We pass an empty map here cause those permissions don't depend on the system result. promise.resolve(parsePermissionsResponse(permissionTypes, emptyMap())) return } permissionsServiceDelegate(createPermissionsResponseListener(permissionTypes, promise), androidPermissions) } @Throws(IllegalStateException::class) private fun parsePermissionsResponse(requestedPermissionsTypes: List<String>, permissionMap: Map<String, PermissionsResponse>): Bundle { return Bundle().apply { requestedPermissionsTypes.forEach { putBundle(it, getRequester(it).parseAndroidPermissions(permissionMap)) } } } @Throws(IllegalStateException::class) private fun getAndroidPermissionsFromList(requestedPermissionsTypes: List<String>): Array<String> { return requestedPermissionsTypes .map { getRequester(it).getAndroidPermissions() } .reduce { acc, list -> acc + list } .toTypedArray() } }
bsd-3-clause
3666d6b697e4dbc04b0c404fb0356151
49.256
192
0.786215
4.919342
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/patterns/GroovyClosurePattern.kt
6
2388
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.patterns import com.intellij.patterns.ElementPattern import com.intellij.patterns.PatternCondition import com.intellij.psi.PsiMethod import com.intellij.util.ProcessingContext import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall class GroovyClosurePattern : GroovyExpressionPattern<GrClosableBlock, GroovyClosurePattern>(GrClosableBlock::class.java) { fun inMethod(methodPattern: ElementPattern<out PsiMethod>): GroovyClosurePattern { return with(object : PatternCondition<GrClosableBlock>("closureInMethod") { override fun accepts(closure: GrClosableBlock, context: ProcessingContext?): Boolean { val call = getCall(closure) ?: return false context?.put(closureCallKey, call) val method = call.resolveMethod() ?: return false return methodPattern.accepts(method) } }) } fun inMethodResult(condition: PatternCondition<in GroovyMethodResult>): GroovyClosurePattern { return with(object : PatternCondition<GrClosableBlock>("closureInMethodResult") { override fun accepts(closure: GrClosableBlock, context: ProcessingContext?): Boolean { val call = getCall(closure) ?: return false context?.put(closureCallKey, call) val result = call.advancedResolve() as? GroovyMethodResult ?: return false return condition.accepts(result, context) } }) } companion object { private fun getCall(closure: GrClosableBlock): GrCall? { val parent = closure.parent when (parent) { is GrCall -> { return if (closure in parent.closureArguments) parent else null } is GrArgumentList -> { val grandParent = parent.parent as? GrCall ?: return null if (grandParent.closureArguments.isNotEmpty()) return null if (grandParent.expressionArguments.lastOrNull() != closure) return null return grandParent } else -> return null } } } }
apache-2.0
b31b10d827a60b18c4bde948b359677b
41.660714
140
0.729062
4.933884
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/compiler-plugins/scripting-ide-services/src/org/jetbrains/kotlin/scripting/ide_services/compiler/impl/KJvmReplCompleter.kt
2
17463
// 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.scripting.ide_services.compiler.impl import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.lexer.KtKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.renderer.ClassifierNamePolicy import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.MemberScope.Companion.ALL_NAME_FILTER import org.jetbrains.kotlin.scripting.ide_services.compiler.completion import org.jetbrains.kotlin.scripting.ide_services.compiler.filterOutShadowedDescriptors import org.jetbrains.kotlin.scripting.ide_services.compiler.nameFilter import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.asFlexibleType import org.jetbrains.kotlin.types.isFlexible import java.io.File import java.util.* import kotlin.script.experimental.api.ScriptCompilationConfiguration import kotlin.script.experimental.api.SourceCodeCompletionVariant fun getKJvmCompletion( ktScript: KtFile, bindingContext: BindingContext, resolutionFacade: KotlinResolutionFacadeForRepl, moduleDescriptor: ModuleDescriptor, cursor: Int, configuration: ScriptCompilationConfiguration ) = KJvmReplCompleter( ktScript, bindingContext, resolutionFacade, moduleDescriptor, cursor, configuration ).getCompletion() // Insert a constant string right after a cursor position to make this identifiable as a simple reference // For example, code line // import java. // ^ // is converted to // import java.ABCDEF // and it makes token after dot (for which reference variants are looked) discoverable in PSI fun prepareCodeForCompletion(code: String, cursor: Int) = code.substring(0, cursor) + KJvmReplCompleter.INSERTED_STRING + code.substring(cursor) private class KJvmReplCompleter( private val ktScript: KtFile, private val bindingContext: BindingContext, private val resolutionFacade: KotlinResolutionFacadeForRepl, private val moduleDescriptor: ModuleDescriptor, private val cursor: Int, private val configuration: ScriptCompilationConfiguration ) { private fun getElementAt(cursorPos: Int): PsiElement? { var element: PsiElement? = ktScript.findElementAt(cursorPos) while (element !is KtExpression && element != null) { element = element.parent } return element } fun getCompletion() = sequence<SourceCodeCompletionVariant> gen@{ val filterOutShadowedDescriptors = configuration[ScriptCompilationConfiguration.completion.filterOutShadowedDescriptors]!! val nameFilter = configuration[ScriptCompilationConfiguration.completion.nameFilter]!! val element = getElementAt(cursor) var descriptors: Collection<DeclarationDescriptor>? = null var isTipsManagerCompletion = true var isSortNeeded = true if (element == null) return@gen val simpleExpression = when { element is KtSimpleNameExpression -> element element.parent is KtSimpleNameExpression -> element.parent as KtSimpleNameExpression else -> null } if (simpleExpression != null) { val inDescriptor: DeclarationDescriptor = simpleExpression.getResolutionScope(bindingContext, resolutionFacade).ownerDescriptor val prefix = element.text.substring(0, cursor - element.startOffset) val elementParent = element.parent if (prefix.isEmpty() && elementParent is KtBinaryExpression) { val parentChildren = elementParent.children if (parentChildren.size == 3 && parentChildren[1] is KtOperationReferenceExpression && parentChildren[1].text == INSERTED_STRING ) return@gen } isSortNeeded = false descriptors = ReferenceVariantsHelper( bindingContext, resolutionFacade, moduleDescriptor, VisibilityFilter(inDescriptor) ).getReferenceVariants( simpleExpression, DescriptorKindFilter.ALL, { name: Name -> !name.isSpecial && nameFilter(name.identifier, prefix) }, filterOutJavaGettersAndSetters = true, filterOutShadowed = filterOutShadowedDescriptors, // setting to true makes it slower up to 4 times excludeNonInitializedVariable = true, useReceiverType = null ) } else if (element is KtStringTemplateExpression) { if (element.hasInterpolation()) { return@gen } val stringVal = element.entries.joinToString("") { val t = it.text if (it.startOffset <= cursor && cursor <= it.endOffset) { val s = cursor - it.startOffset val e = s + INSERTED_STRING.length t.substring(0, s) + t.substring(e) } else t } val separatorIndex = stringVal.lastIndexOfAny(charArrayOf('/', '\\')) val dir = if (separatorIndex != -1) { stringVal.substring(0, separatorIndex + 1) } else { "." } val namePrefix = stringVal.substring(separatorIndex + 1) val file = File(dir) file.listFiles { p, f -> p == file && f.startsWith(namePrefix, true) }?.forEach { yield(SourceCodeCompletionVariant(it.name, it.name, "file", "file")) } return@gen } else { isTipsManagerCompletion = false val resolutionScope: LexicalScope? val parent = element.parent val qualifiedExpression = when { element is KtQualifiedExpression -> { isTipsManagerCompletion = true element } parent is KtQualifiedExpression -> parent else -> null } if (qualifiedExpression != null) { val receiverExpression = qualifiedExpression.receiverExpression val expressionType = bindingContext.get( BindingContext.EXPRESSION_TYPE_INFO, receiverExpression )?.type if (expressionType != null) { isSortNeeded = false descriptors = ReferenceVariantsHelper( bindingContext, resolutionFacade, moduleDescriptor, { true } ).getReferenceVariants( receiverExpression, CallTypeAndReceiver.DOT(receiverExpression), DescriptorKindFilter.ALL, ALL_NAME_FILTER, filterOutShadowed = filterOutShadowedDescriptors, ) } } else { resolutionScope = bindingContext.get( BindingContext.LEXICAL_SCOPE, element as KtExpression? ) descriptors = (resolutionScope?.getContributedDescriptors( DescriptorKindFilter.ALL, ALL_NAME_FILTER ) ?: return@gen) } } if (descriptors != null) { val targetElement = if (isTipsManagerCompletion) element else element.parent val prefixEnd = cursor - targetElement.startOffset var prefix = targetElement.text.substring(0, prefixEnd) val cursorWithinElement = cursor - element.startOffset val dotIndex = prefix.lastIndexOf('.', cursorWithinElement) prefix = if (dotIndex >= 0) { prefix.substring(dotIndex + 1, cursorWithinElement) } else { prefix.substring(0, cursorWithinElement) } if (descriptors !is ArrayList<*>) { descriptors = ArrayList(descriptors) } (descriptors as ArrayList<DeclarationDescriptor>) .map { val presentation = getPresentation( it ) Triple(it, presentation, (presentation.presentableText + presentation.tailText).toLowerCase()) } .let { if (isSortNeeded) it.sortedBy { descTriple -> descTriple.third } else it } .forEach { val descriptor = it.first val (rawName, presentableText, tailText, completionText) = it.second if (nameFilter(rawName, prefix)) { val fullName: String = formatName( presentableText ) yield( SourceCodeCompletionVariant( completionText, fullName, tailText, getIconFromDescriptor( descriptor ) ) ) } } yieldAll( keywordsCompletionVariants( KtTokens.KEYWORDS, prefix ) ) yieldAll( keywordsCompletionVariants( KtTokens.SOFT_KEYWORDS, prefix ) ) } } private class VisibilityFilter( private val inDescriptor: DeclarationDescriptor ) : (DeclarationDescriptor) -> Boolean { override fun invoke(descriptor: DeclarationDescriptor): Boolean { if (descriptor is TypeParameterDescriptor && !isTypeParameterVisible(descriptor)) return false if (descriptor is DeclarationDescriptorWithVisibility) { return try { descriptor.visibility.isVisible(null, descriptor, inDescriptor) } catch (e: IllegalStateException) { true } } return true } private fun isTypeParameterVisible(typeParameter: TypeParameterDescriptor): Boolean { val owner = typeParameter.containingDeclaration var parent: DeclarationDescriptor? = inDescriptor while (parent != null) { if (parent == owner) return true if (parent is ClassDescriptor && !parent.isInner) return false parent = parent.containingDeclaration } return true } } companion object { const val INSERTED_STRING = "ABCDEF" private const val NUMBER_OF_CHAR_IN_COMPLETION_NAME = 40 private fun keywordsCompletionVariants( keywords: TokenSet, prefix: String ) = sequence { keywords.types.forEach { val token = (it as KtKeywordToken).value if (token.startsWith(prefix)) yield( SourceCodeCompletionVariant( token, token, "keyword", "keyword" ) ) } } private val RENDERER = IdeDescriptorRenderers.SOURCE_CODE.withOptions { this.classifierNamePolicy = ClassifierNamePolicy.SHORT this.typeNormalizer = IdeDescriptorRenderers.APPROXIMATE_FLEXIBLE_TYPES this.parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE this.renderDefaultAnnotationArguments = false this.typeNormalizer = lambda@{ kotlinType: KotlinType -> if (kotlinType.isFlexible()) { return@lambda kotlinType.asFlexibleType().upperBound } kotlinType } } private fun getIconFromDescriptor(descriptor: DeclarationDescriptor): String = when (descriptor) { is FunctionDescriptor -> "method" is PropertyDescriptor -> "property" is LocalVariableDescriptor -> "property" is ClassDescriptor -> "class" is PackageFragmentDescriptor -> "package" is PackageViewDescriptor -> "package" is ValueParameterDescriptor -> "genericValue" is TypeParameterDescriptorImpl -> "class" else -> "" } private fun formatName(builder: String, symbols: Int = NUMBER_OF_CHAR_IN_COMPLETION_NAME): String { return if (builder.length > symbols) { builder.substring(0, symbols) + "..." } else builder } data class DescriptorPresentation( val rawName: String, val presentableText: String, val tailText: String, val completionText: String ) fun getPresentation(descriptor: DeclarationDescriptor): DescriptorPresentation { val rawDescriptorName = descriptor.name.asString() val descriptorName = rawDescriptorName.quoteIfNeeded() var presentableText = descriptorName var typeText = "" var tailText = "" var completionText = "" if (descriptor is FunctionDescriptor) { val returnType = descriptor.returnType typeText = if (returnType != null) RENDERER.renderType(returnType) else "" presentableText += RENDERER.renderFunctionParameters( descriptor ) val parameters = descriptor.valueParameters if (parameters.size == 1 && parameters.first().type.isFunctionType) completionText = "$descriptorName { " val extensionFunction = descriptor.extensionReceiverParameter != null val containingDeclaration = descriptor.containingDeclaration if (extensionFunction) { tailText += " for " + RENDERER.renderType( descriptor.extensionReceiverParameter!!.type ) tailText += " in " + DescriptorUtils.getFqName(containingDeclaration) } } else if (descriptor is VariableDescriptor) { val outType = descriptor.type typeText = RENDERER.renderType(outType) } else if (descriptor is ClassDescriptor) { val declaredIn = descriptor.containingDeclaration tailText = " (" + DescriptorUtils.getFqName(declaredIn) + ")" } else { typeText = RENDERER.render(descriptor) } tailText = if (typeText.isEmpty()) tailText else typeText if (completionText.isEmpty()) { completionText = presentableText var position = completionText.indexOf('(') if (position != -1) { //If this is a string with a package after if (completionText[position - 1] == ' ') { position -= 2 } //if this is a method without args if (completionText[position + 1] == ')') { position++ } completionText = completionText.substring(0, position + 1) } position = completionText.indexOf(":") if (position != -1) { completionText = completionText.substring(0, position - 1) } } return DescriptorPresentation( rawDescriptorName, presentableText, tailText, completionText ) } } }
apache-2.0
3718053a86af0f5770adbacb220ace53
39.517401
158
0.573785
6.179406
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/compile/KtScratchSourceFileProcessor.kt
3
5025
// 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.scratch.compile import org.jetbrains.kotlin.diagnostics.rendering.Renderers import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.scratch.ScratchExpression import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore class KtScratchSourceFileProcessor { companion object { const val GENERATED_OUTPUT_PREFIX = "##scratch##generated##" const val LINES_INFO_MARKER = "end##" const val END_OUTPUT_MARKER = "end##!@#%^&*" const val OBJECT_NAME = "ScratchFileRunnerGenerated" const val INSTANCE_NAME = "instanceScratchFileRunner" const val PACKAGE_NAME = "org.jetbrains.kotlin.idea.scratch.generated" const val GET_RES_FUN_NAME_PREFIX = "generated_get_instance_res" } fun process(expressions: List<ScratchExpression>): Result { val sourceProcessor = KtSourceProcessor() expressions.forEach { sourceProcessor.process(it) } val codeResult = """ package $PACKAGE_NAME ${sourceProcessor.imports.joinToString("\n") { it.text }} object $OBJECT_NAME { class $OBJECT_NAME { ${sourceProcessor.classBuilder} } @JvmStatic fun main(args: Array<String>) { val $INSTANCE_NAME = $OBJECT_NAME() ${sourceProcessor.objectBuilder} println("$END_OUTPUT_MARKER") } } """ return Result.OK("$PACKAGE_NAME.$OBJECT_NAME", codeResult) } class KtSourceProcessor { val classBuilder = StringBuilder() val objectBuilder = StringBuilder() val imports = arrayListOf<KtImportDirective>() private var resCount = 0 fun process(expression: ScratchExpression) { val psiElement = expression.element when (psiElement) { is KtDestructuringDeclaration -> processDestructuringDeclaration(expression, psiElement) is KtVariableDeclaration -> processDeclaration(expression, psiElement) is KtFunction -> processDeclaration(expression, psiElement) is KtClassOrObject -> processDeclaration(expression, psiElement) is KtImportDirective -> imports.add(psiElement) is KtExpression -> processExpression(expression, psiElement) } } private fun processDeclaration(e: ScratchExpression, c: KtDeclaration) { classBuilder.append(c.text).newLine() val descriptor = c.resolveToDescriptorIfAny() ?: return val context = RenderingContext.of(descriptor) objectBuilder.println(Renderers.COMPACT.render(descriptor, context)) objectBuilder.appendLineInfo(e) } private fun processDestructuringDeclaration(e: ScratchExpression, c: KtDestructuringDeclaration) { val entries = c.entries.mapNotNull { if (it.isSingleUnderscore) null else it.resolveToDescriptorIfAny() } entries.forEach { val context = RenderingContext.of(it) val rendered = Renderers.COMPACT.render(it, context) classBuilder.append(rendered).newLine() objectBuilder.println(rendered) } objectBuilder.appendLineInfo(e) classBuilder.append("init {").newLine() classBuilder.append(c.text).newLine() entries.forEach { classBuilder.append("this.${it.name} = ${it.name}").newLine() } classBuilder.append("}").newLine() } private fun processExpression(e: ScratchExpression, expr: KtExpression) { val resName = "$GET_RES_FUN_NAME_PREFIX$resCount" classBuilder.append("fun $resName() = run { ${expr.text} }").newLine() objectBuilder.printlnObj("$INSTANCE_NAME.$resName()") objectBuilder.appendLineInfo(e) resCount += 1 } private fun StringBuilder.appendLineInfo(e: ScratchExpression) { println("$LINES_INFO_MARKER${e.lineStart}|${e.lineEnd}") } private fun StringBuilder.println(str: String) = append("println(\"$GENERATED_OUTPUT_PREFIX$str\")").newLine() private fun StringBuilder.printlnObj(str: String) = append("println(\"$GENERATED_OUTPUT_PREFIX\${$str}\")").newLine() private fun StringBuilder.newLine() = append("\n") } sealed class Result { class Error(val message: String) : Result() class OK(val mainClassName: String, val code: String) : Result() } }
apache-2.0
7c8e5d2522b43d3699878bb6e3f4e954
40.53719
158
0.625672
5.228928
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditEncryptedPassword.kt
1
3158
package info.nightscout.androidaps.setupwizard.elements import android.graphics.Typeface import android.text.Editable import android.text.InputType import android.text.TextWatcher import android.view.View import android.widget.EditText import android.widget.LinearLayout import android.widget.TextView import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.setupwizard.SWTextValidator import info.nightscout.androidaps.utils.CryptoUtil class SWEditEncryptedPassword(injector: HasAndroidInjector, private val cryptoUtil: CryptoUtil) : SWItem(injector, Type.STRING) { private var validator: SWTextValidator = SWTextValidator(String::isNotEmpty) private var updateDelay = 0L override fun generateDialog(layout: LinearLayout) { val context = layout.context val l = TextView(context) l.id = View.generateViewId() label?.let { l.setText(it) } l.setTypeface(l.typeface, Typeface.BOLD) layout.addView(l) val c = TextView(context) c.id = View.generateViewId() comment?.let { c.setText(it) } c.setTypeface(c.typeface, Typeface.ITALIC) layout.addView(c) val editText = EditText(context) editText.id = View.generateViewId() editText.inputType = InputType.TYPE_CLASS_TEXT editText.maxLines = 1 editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD layout.addView(editText) val c2 = TextView(context) c2.id = View.generateViewId() c2.setText(R.string.confirm) layout.addView(c2) val editText2 = EditText(context) editText2.id = View.generateViewId() editText2.inputType = InputType.TYPE_CLASS_TEXT editText2.maxLines = 1 editText2.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD layout.addView(editText2) super.generateDialog(layout) val watcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { sp.remove(preferenceId) scheduleChange(updateDelay) if (validator.isValid(editText.text.toString()) && validator.isValid(editText2.text.toString()) && editText.text.toString() == editText2.text.toString()) save(s.toString(), updateDelay) } override fun afterTextChanged(s: Editable) {} } editText.addTextChangedListener(watcher) editText2.addTextChangedListener(watcher) } fun preferenceId(preferenceId: Int): SWEditEncryptedPassword { this.preferenceId = preferenceId return this } fun validator(validator: SWTextValidator): SWEditEncryptedPassword { this.validator = validator return this } override fun save(value: String, updateDelay: Long) { sp.putString(preferenceId, cryptoUtil.hashPassword(value)) scheduleChange(updateDelay) } }
agpl-3.0
bbe0ce497a31b47cd53d718f7b2c07c0
37.52439
169
0.69031
4.537356
false
false
false
false
fabmax/kool
kool-physics/src/jvmMain/kotlin/de/fabmax/kool/physics/PhysicsWorld.kt
1
10721
package de.fabmax.kool.physics import de.fabmax.kool.math.Mat4f import de.fabmax.kool.math.MutableVec3f import de.fabmax.kool.math.Ray import de.fabmax.kool.math.Vec3f import de.fabmax.kool.physics.articulations.Articulation import de.fabmax.kool.physics.geometry.CollisionGeometry import de.fabmax.kool.scene.Scene import de.fabmax.kool.util.logE import de.fabmax.kool.util.logW import org.lwjgl.system.MemoryStack import physx.PxTopLevelFunctions import physx.common.PxVec3 import physx.extensions.PxDefaultCpuDispatcher import physx.physics.* import physx.support.SupportFunctions import physx.support.TypeHelpers import physx.support.Vector_PxContactPairPoint import kotlin.collections.set actual class PhysicsWorld actual constructor(scene: Scene?, val isContinuousCollisionDetection: Boolean, val numWorkers: Int) : CommonPhysicsWorld(), Releasable { val pxScene: PxScene private val cpuDispatcher: PxDefaultCpuDispatcher private val raycastResult = PxRaycastBuffer10() private val sweepResult = PxSweepBuffer10() private val bufPxGravity = Vec3f(0f, -9.81f, 0f).toPxVec3(PxVec3()) private val bufGravity = MutableVec3f() actual var gravity: Vec3f get() = pxScene.gravity.toVec3f(bufGravity) set(value) { pxScene.gravity = value.toPxVec3(bufPxGravity) } private var mutActiveActors = 0 actual val activeActors: Int get() = mutActiveActors private val pxActors = mutableMapOf<PxActor, RigidActor>() init { Physics.checkIsLoaded() cpuDispatcher = PxTopLevelFunctions.DefaultCpuDispatcherCreate(numWorkers) MemoryStack.stackPush().use { mem -> var flags = PxSceneFlagEnum.eENABLE_ACTIVE_ACTORS if (isContinuousCollisionDetection) { flags = flags or PxSceneFlagEnum.eENABLE_CCD } val sceneDesc = PxSceneDesc.createAt(mem, MemoryStack::nmalloc, Physics.physics.tolerancesScale) sceneDesc.gravity = bufPxGravity sceneDesc.cpuDispatcher = this.cpuDispatcher sceneDesc.filterShader = PxTopLevelFunctions.DefaultFilterShader() sceneDesc.simulationEventCallback = SimEventCallback() sceneDesc.flags.set(flags) pxScene = Physics.physics.createScene(sceneDesc) } scene?.let { registerHandlers(it) } } override fun singleStepAsync(timeStep: Float) { super.singleStepAsync(timeStep) pxScene.simulate(timeStep) } override fun fetchAsyncStepResults() { pxScene.fetchResults(true) for (i in actors.indices) { actors[i].isActive = false } val activeActors = SupportFunctions.PxScene_getActiveActors(pxScene) mutActiveActors = activeActors.size() for (i in 0 until mutActiveActors) { pxActors[activeActors.at(i)]?.isActive = true } super.fetchAsyncStepResults() } fun getActor(pxActor: PxActor): RigidActor? { return pxActors[pxActor] } override fun addActor(actor: RigidActor) { super.addActor(actor) pxScene.addActor(actor.pxRigidActor) pxActors[actor.pxRigidActor] = actor // set necessary ccd flags in case it is enabled for this scene val pxActor = actor.pxRigidActor if (isContinuousCollisionDetection && pxActor is PxRigidBody) { pxActor.setRigidBodyFlag(PxRigidBodyFlagEnum.eENABLE_CCD, true) actor.simulationFilterData = FilterData { set(actor.simulationFilterData) word2 = PxPairFlagEnum.eDETECT_CCD_CONTACT } } } override fun removeActor(actor: RigidActor) { super.removeActor(actor) pxScene.removeActor(actor.pxRigidActor) pxActors -= actor.pxRigidActor } override fun addArticulation(articulation: Articulation) { super.addArticulation(articulation) articulation.links.forEach { pxActors[it.pxLink] = it } pxScene.addArticulation(articulation.pxArticulation) } override fun removeArticulation(articulation: Articulation) { super.removeArticulation(articulation) articulation.links.forEach { pxActors -= it.pxLink } pxScene.removeArticulation(articulation.pxArticulation) } override fun release() { super.release() pxScene.release() bufPxGravity.destroy() raycastResult.destroy() sweepResult.destroy() cpuDispatcher.destroy() } actual fun raycast(ray: Ray, maxDistance: Float, result: HitResult): Boolean { result.clear() MemoryStack.stackPush().use { mem -> synchronized(raycastResult) { val ori = ray.origin.toPxVec3(mem.createPxVec3()) val dir = ray.direction.toPxVec3(mem.createPxVec3()) if (pxScene.raycast(ori, dir, maxDistance, raycastResult)) { var minDist = maxDistance var nearestHit: PxRaycastHit? = null var nearestActor: RigidActor? = null for (i in 0 until raycastResult.nbAnyHits) { val hit = raycastResult.getAnyHit(i) val actor = pxActors[hit.actor] if (actor != null && hit.distance < minDist) { result.hitActors += actor minDist = hit.distance nearestHit = hit nearestActor = actor } } if (nearestHit != null) { result.nearestActor = nearestActor result.hitDistance = minDist nearestHit.position.toVec3f(result.hitPosition) nearestHit.normal.toVec3f(result.hitNormal) } } } } return result.isHit } actual fun sweepTest(testGeometry: CollisionGeometry, geometryPose: Mat4f, testDirection: Vec3f, distance: Float, result: HitResult): Boolean { result.clear() MemoryStack.stackPush().use { mem -> val sweepPose = geometryPose.toPxTransform(mem.createPxTransform()) val sweepDir = testDirection.toPxVec3(mem.createPxVec3()) if (pxScene.sweep(testGeometry.pxGeometry, sweepPose, sweepDir, distance, sweepResult)) { var minDist = distance var nearestHit: PxSweepHit? = null var nearestActor: RigidActor? = null for (i in 0 until sweepResult.nbAnyHits) { val hit = sweepResult.getAnyHit(i) val actor = pxActors[hit.actor] if (actor != null && hit.distance < minDist) { result.hitActors += actor minDist = hit.distance nearestHit = hit nearestActor = actor } } if (nearestHit != null) { result.nearestActor = nearestActor result.hitDistance = minDist nearestHit.position.toVec3f(result.hitPosition) nearestHit.normal.toVec3f(result.hitNormal) } } } return result.isHit } private inner class SimEventCallback : JavaSimulationEventCallback() { val contacts = Vector_PxContactPairPoint(64) override fun onTrigger(pairs: PxTriggerPair, count: Int) { for (i in 0 until count) { val pair = TypeHelpers.getTriggerPairAt(pairs, i) val isEnter = pair.status == PxPairFlagEnum.eNOTIFY_TOUCH_FOUND val trigger = pxActors[pair.triggerActor] val actor = pxActors[pair.otherActor] if (trigger != null && actor != null) { triggerListeners[trigger]?.apply { var cnt = actorEnterCounts.getOrPut(actor) { 0 } val shape = actor.shapes.find { it.pxShape == pair.otherShape } if (shape == null) { logE { "shape reference not found" } } if (isEnter) { cnt++ if (cnt == 1) { listeners.forEach { it.onActorEntered(trigger, actor) } } shape?.let { s -> listeners.forEach { it.onShapeEntered(trigger, actor, s) } } } else { cnt-- shape?.let { s -> listeners.forEach { it.onShapeExited(trigger, actor, s) } } if (cnt == 0) { listeners.forEach { it.onActorExited(trigger, actor) } } } actorEnterCounts[actor] = cnt } } else { logE { "actor reference not found" } } } } override fun onContact(pairHeader: PxContactPairHeader, pairs: PxContactPair, nbPairs: Int) { val actorA = pxActors[pairHeader.getActors(0)] val actorB = pxActors[pairHeader.getActors(1)] if (actorA == null || actorB == null) { logW { "onContact: actor reference not found" } return } for (i in 0 until nbPairs) { val pair = TypeHelpers.getContactPairAt(pairs, i) val evts = pair.events if (evts.isSet(PxPairFlagEnum.eNOTIFY_TOUCH_FOUND)) { val contactPoints: MutableList<ContactPoint>? val pxContactPoints = pair.extractContacts(contacts.data(), 64) if (pxContactPoints > 0) { contactPoints = mutableListOf() for (iPt in 0 until pxContactPoints) { val contact = contacts.at(iPt) contactPoints += ContactPoint(contact.position.toVec3f(), contact.normal.toVec3f(), contact.impulse.toVec3f(), contact.separation) } } else { contactPoints = null } fireOnTouchFound(actorA, actorB, contactPoints) } else if (evts.isSet(PxPairFlagEnum.eNOTIFY_TOUCH_LOST)) { fireOnTouchLost(actorA, actorB) } } } } }
apache-2.0
cd441183ca39651edd5e67ef7dc6030e
39.308271
162
0.568231
4.965725
false
false
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/push/PushService.kt
1
6431
/* * Copyright 2022 Benoit LETONDOR * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.benoitletondor.easybudgetapp.push import com.batch.android.Batch import com.benoitletondor.easybudgetapp.BuildConfig import com.benoitletondor.easybudgetapp.helper.* import com.benoitletondor.easybudgetapp.iab.Iab import com.benoitletondor.easybudgetapp.parameters.* import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import dagger.hilt.android.AndroidEntryPoint import java.util.Calendar import java.util.Date import javax.inject.Inject /** * Service that handles Batch pushes * * @author Benoit LETONDOR */ @AndroidEntryPoint class PushService : FirebaseMessagingService() { @Inject lateinit var iab: Iab @Inject lateinit var parameters: Parameters // -----------------------------------> override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) // Check that the push is valid if (Batch.Push.shouldDisplayPush(this, remoteMessage)) { if (!shouldDisplayPush(remoteMessage)) { Logger.debug("Not displaying push cause conditions are not matching") return } // Display the notification Batch.Push.displayNotification(this, remoteMessage) } } /** * Check if the push should be displayed * * @param remoteMessage * @return true if should display the push, false otherwise */ private fun shouldDisplayPush(remoteMessage: RemoteMessage): Boolean { return isUserOk(remoteMessage) && isVersionCompatible(remoteMessage) && isPremiumCompatible(remoteMessage) } /** * Check if the push should be displayed according to user choice * * @param remoteMessage * @return true if should display the push, false otherwise */ private fun isUserOk(remoteMessage: RemoteMessage): Boolean { try { // Check if it's a daily reminder if (remoteMessage.data.containsKey(DAILY_REMINDER_KEY) && "true" == remoteMessage.data[DAILY_REMINDER_KEY]) { // Only for premium users if ( !iab.isUserPremium() ) { return false } // Check user choice if ( !parameters.isUserAllowingDailyReminderPushes() ) { return false } // Check if the app hasn't been opened today val lastOpenTimestamp = parameters.getLastOpenTimestamp() if (lastOpenTimestamp == 0L) { return false } val lastOpen = Date(lastOpenTimestamp) val cal = Calendar.getInstance() val currentDay = cal.get(Calendar.DAY_OF_YEAR) cal.time = lastOpen val lastOpenDay = cal.get(Calendar.DAY_OF_YEAR) return currentDay != lastOpenDay } else if (remoteMessage.data.containsKey(MONTHLY_REMINDER_KEY) && "true" == remoteMessage.data[MONTHLY_REMINDER_KEY]) { return iab.isUserPremium() && parameters.isUserAllowingMonthlyReminderPushes() } // Else it must be an update push return parameters.isUserAllowingUpdatePushes() } catch (e: Exception) { Logger.error("Error while checking user ok for push", e) return false } } /** * Check if the push should be displayed according to version constrains * * @param remoteMessage * @return true if should display the push, false otherwise */ private fun isVersionCompatible(remoteMessage: RemoteMessage): Boolean { try { var maxVersion = BuildConfig.VERSION_CODE var minVersion = 1 if (remoteMessage.data.containsKey(INTENT_MAX_VERSION_KEY)) { maxVersion = Integer.parseInt(remoteMessage.data[INTENT_MAX_VERSION_KEY]!!) } if (remoteMessage.data.containsKey(INTENT_MIN_VERSION_KEY)) { minVersion = Integer.parseInt(remoteMessage.data[INTENT_MIN_VERSION_KEY]!!) } return BuildConfig.VERSION_CODE in minVersion..maxVersion } catch (e: Exception) { Logger.error("Error while checking app version for push", e) return false } } /** * Check the user status if a push is marked as for premium or not. * * @param remoteMessage push intent * @return true if compatible, false otherwise */ private fun isPremiumCompatible(remoteMessage: RemoteMessage): Boolean { try { if (remoteMessage.data.containsKey(INTENT_PREMIUM_KEY)) { val isForPremium = "true" == remoteMessage.data[INTENT_PREMIUM_KEY] return isForPremium == iab.isUserPremium() } return true } catch (e: Exception) { Logger.error("Error while checking premium compatible for push", e) return false } } companion object { /** * Key to retrieve the max version for a push */ private const val INTENT_MAX_VERSION_KEY = "maxVersion" /** * Key to retrieve the max version for a push */ private const val INTENT_MIN_VERSION_KEY = "minVersion" /** * Key to retrieve if a push is intented for premium user or not */ private const val INTENT_PREMIUM_KEY = "premium" /** * Key to retrieve the daily reminder key for a push */ const val DAILY_REMINDER_KEY = "daily" /** * Key to retrieve the monthly reminder key for a push */ const val MONTHLY_REMINDER_KEY = "monthly" } }
apache-2.0
a6ea82368e37216075db11f546da75af
33.390374
132
0.619033
5.000778
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionHandler.kt
1
7620
// 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.jetbrains.python.refactoring.inline import com.google.common.annotations.VisibleForTesting import com.intellij.codeInsight.TargetElementUtil import com.intellij.lang.Language import com.intellij.lang.refactoring.InlineActionHandler import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.SyntaxTraverser import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.util.CommonRefactoringUtil import com.jetbrains.python.PyBundle import com.jetbrains.python.PyNames import com.jetbrains.python.PythonLanguage import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.impl.references.PyImportReference import com.jetbrains.python.psi.search.PyOverridingMethodsSearch import com.jetbrains.python.psi.search.PySuperMethodsSearch import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.pyi.PyiFile import com.jetbrains.python.pyi.PyiUtil import com.jetbrains.python.sdk.PythonSdkUtil /** * @author Aleksei.Kniazev */ class PyInlineFunctionHandler : InlineActionHandler() { override fun isEnabledForLanguage(l: Language?) = l is PythonLanguage override fun canInlineElement(element: PsiElement?): Boolean { if (element is PyFunction) { val containingFile = if (element.containingFile is PyiFile) PyiUtil.getOriginalElement(element)?.containingFile else element.containingFile return containingFile is PyFile } return false } override fun inlineElement(project: Project?, editor: Editor?, element: PsiElement?) { if (project == null || editor == null || element !is PyFunction) return val functionScope = ControlFlowCache.getScope(element) val error = when { element.isAsync -> "refactoring.inline.function.async" element.isGenerator -> "refactoring.inline.function.generator" PyUtil.isInitOrNewMethod(element) -> "refactoring.inline.function.constructor" PyBuiltinCache.getInstance(element).isBuiltin(element) -> "refactoring.inline.function.builtin" isSpecialMethod(element) -> "refactoring.inline.function.special.method" isUnderSkeletonDir(element) -> "refactoring.inline.function.skeleton.only" hasDecorators(element) -> "refactoring.inline.function.decorator" hasReferencesToSelf(element) -> "refactoring.inline.function.self.referrent" hasStarArgs(element) -> "refactoring.inline.function.star" overridesMethod(element, project) -> "refactoring.inline.function.overrides.method" isOverridden(element) -> "refactoring.inline.function.is.overridden" functionScope.hasGlobals() -> "refactoring.inline.function.global" functionScope.hasNonLocals() -> "refactoring.inline.function.nonlocal" hasNestedFunction(element) -> "refactoring.inline.function.nested" hasNonExhaustiveIfs(element) -> "refactoring.inline.function.interrupts.flow" else -> null } if (error != null) { CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message(error), PyBundle.message("refactoring.inline.function.title"), REFACTORING_ID) return } if (!ApplicationManager.getApplication().isUnitTestMode){ PyInlineFunctionDialog(project, editor, element, findReference(editor)).show() } } private fun isSpecialMethod(function: PyFunction): Boolean { return function.containingClass != null && PyNames.getBuiltinMethods(LanguageLevel.forElement(function)).contains(function.name) } private fun hasNestedFunction(function: PyFunction): Boolean = SyntaxTraverser.psiTraverser(function.statementList).traverse().any { it is PyFunction } private fun hasNonExhaustiveIfs(function: PyFunction): Boolean { val returns = mutableListOf<PyReturnStatement>() function.accept(object : PyRecursiveElementVisitor() { override fun visitPyReturnStatement(node: PyReturnStatement) { returns.add(node) } }) if (returns.isEmpty()) return false val cache = mutableSetOf<PyIfStatement>() return returns.asSequence() .map { PsiTreeUtil.getParentOfType(it, PyIfStatement::class.java) } .distinct() .filterNotNull() .any { checkInterruptsControlFlow(it, cache) } } private fun checkInterruptsControlFlow(ifStatement: PyIfStatement, cache: MutableSet<PyIfStatement>): Boolean { if (ifStatement in cache) return false cache.add(ifStatement) val elsePart = ifStatement.elsePart if (elsePart == null) return true if (checkLastStatement(ifStatement.ifPart.statementList, cache)) return true if (checkLastStatement(elsePart.statementList, cache)) return true ifStatement.elifParts.forEach { if (checkLastStatement(it.statementList, cache)) return true } val parentIfStatement = PsiTreeUtil.getParentOfType(ifStatement, PyIfStatement::class.java) if (parentIfStatement != null && checkInterruptsControlFlow(parentIfStatement, cache)) return true return false } private fun checkLastStatement(statementList: PyStatementList, cache: MutableSet<PyIfStatement>): Boolean { val statements = statementList.statements if (statements.isEmpty()) return true when(val last = statements.last()) { is PyIfStatement -> if (checkInterruptsControlFlow(last, cache)) return true !is PyReturnStatement -> return true } return false } private fun hasDecorators(function: PyFunction): Boolean = function.decoratorList?.decorators?.isNotEmpty() == true private fun overridesMethod(function: PyFunction, project: Project): Boolean { return function.containingClass != null && PySuperMethodsSearch.search(function, TypeEvalContext.codeAnalysis(project, function.containingFile)).any() } private fun isOverridden(function: PyFunction): Boolean { return function.containingClass != null && PyOverridingMethodsSearch.search(function, true).any() } private fun hasStarArgs(function: PyFunction): Boolean { return function.parameterList.parameters.asSequence() .filterIsInstance<PyNamedParameter>() .any { it.isPositionalContainer || it.isKeywordContainer } } private fun hasReferencesToSelf(function: PyFunction): Boolean = SyntaxTraverser.psiTraverser(function.statementList) .any { it is PyReferenceExpression && it.reference.isReferenceTo(function) } private fun isUnderSkeletonDir(function: PyFunction): Boolean { val containingFile = PyiUtil.getOriginalElementOrLeaveAsIs(function, PyElement::class.java).containingFile val sdk = PythonSdkUtil.findPythonSdk(containingFile) ?: return false val skeletonsDir = PythonSdkUtil.findSkeletonsDir(sdk) ?: return false return VfsUtil.isAncestor(skeletonsDir, containingFile.virtualFile, true) } companion object { @JvmStatic fun getInstance(): PyInlineFunctionHandler { return EP_NAME.findExtensionOrFail(PyInlineFunctionHandler::class.java) } @JvmStatic val REFACTORING_ID = "refactoring.inlineMethod" @JvmStatic @VisibleForTesting fun findReference(editor: Editor): PsiReference? { val reference = TargetElementUtil.findReference(editor) return if (reference !is PyImportReference) reference else null } } }
apache-2.0
ae8636f8aec0b9597390694546969c5c
44.628743
154
0.767323
4.674847
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/ide/cds/CDSManager.kt
1
12705
// 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.ide.cds import com.intellij.diagnostic.VMOptions import com.intellij.execution.CommandLineWrapperUtil import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.OSProcessUtil import com.intellij.execution.util.ExecUtil import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.PerformInBackgroundOption import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.text.VersionComparatorUtil import com.sun.management.OperatingSystemMXBean import com.sun.tools.attach.VirtualMachine import java.io.File import java.lang.management.ManagementFactory import java.nio.charset.StandardCharsets import java.util.concurrent.TimeUnit import kotlin.system.measureTimeMillis sealed class CDSTaskResult(val statusName: String) { object Success : CDSTaskResult("success") abstract class Cancelled(statusName: String) : CDSTaskResult(statusName) object InterruptedForRetry : Cancelled("cancelled") object TerminatedByUser : Cancelled("terminated-by-user") object PluginsChanged : Cancelled("plugins-changed") data class Failed(val error: String) : CDSTaskResult("failed") } object CDSManager { private val LOG = Logger.getInstance(javaClass) val isValidEnv: Boolean by lazy { // AppCDS requires classes packed into JAR files, not from the out folder if (PluginManagerCore.isRunningFromSources()) return@lazy false // CDS features are only available on 64 bit JVMs if (!SystemInfo.is64Bit) return@lazy false // The AppCDS (JEP 310) is only added in JDK10, // The closest JRE we ship/support is 11 if (!SystemInfo.isJavaVersionAtLeast(11)) return@lazy false //AppCDS does not support Windows and macOS if (!SystemInfo.isLinux) { //Specific patches are included into JetBrains runtime //to support Windows and macOS if (!SystemInfo.isJetBrainsJvm) return@lazy false if (VersionComparatorUtil.compare(SystemInfo.JAVA_RUNTIME_VERSION, "11.0.4+10-b520.2") < 0) return@lazy false } // we do not like to overload a potentially small computer with our process val osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean::class.java) if (osBean.totalPhysicalMemorySize < 4L * 1024 * 1024 * 1024) return@lazy false if (osBean.availableProcessors < 4) return@lazy false if (!VMOptions.canWriteOptions()) return@lazy false true } val currentCDSArchive: File? by lazy { val arguments = ManagementFactory.getRuntimeMXBean().inputArguments val xShare = arguments.any { it == "-Xshare:auto" || it == "-Xshare:on" } if (!xShare) return@lazy null val key = "-XX:SharedArchiveFile=" return@lazy arguments.firstOrNull { it.startsWith(key) }?.removePrefix(key)?.let(::File) } fun cleanupStaleCDSFiles(isCDSEnabled: Boolean): CDSTaskResult { val paths = CDSPaths.current val currentCDSPath = currentCDSArchive val files = paths.baseDir.listFiles() ?: arrayOf() if (files.isEmpty()) return CDSTaskResult.Success for (path in files) { if (path == currentCDSPath) continue if (isCDSEnabled && paths.isOurFile(path)) continue FileUtil.delete(path) } return CDSTaskResult.Success } fun removeCDS() { if (currentCDSArchive?.isFile != true ) return VMOptions.writeDisableCDSArchiveOption() LOG.warn("Disabled CDS") } private interface CDSProgressIndicator { /// returns non-null value if cancelled val cancelledStatus: CDSTaskResult.Cancelled? var text2: String? } fun installCDS(canStillWork: () -> Boolean, onResult: (CDSTaskResult) -> Unit) { CDSFUSCollector.logCDSBuildingStarted() val startTime = System.currentTimeMillis() ProgressManager.getInstance().run(object : Task.Backgroundable( null, "Optimizing startup performance...", true, PerformInBackgroundOption.ALWAYS_BACKGROUND ) { override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = true val progress = object : CDSProgressIndicator { override val cancelledStatus: CDSTaskResult.Cancelled? get() { if (!canStillWork()) return CDSTaskResult.InterruptedForRetry if (indicator.isCanceled) return CDSTaskResult.TerminatedByUser if (ApplicationManager.getApplication().isDisposed) return CDSTaskResult.InterruptedForRetry return null } override var text2: String? get() = indicator.text2 set(value) { indicator.text2 = value } } val paths = CDSPaths.current val result = try { installCDSImpl(progress, paths) } catch (t: Throwable) { LOG.warn("Settings up CDS Archive crashed unexpectedly. ${t.message}", t) val message = "Unexpected crash $t" paths.markError(message) CDSTaskResult.Failed(message) } val installTime = System.currentTimeMillis() - startTime CDSFUSCollector.logCDSBuildingCompleted(installTime, result) onResult(result) } }) } private fun installCDSImpl(indicator: CDSProgressIndicator, paths: CDSPaths): CDSTaskResult { if (paths.isSame(currentCDSArchive)) { val message = "CDS archive is already generated and being used. Nothing to do" LOG.debug(message) return CDSTaskResult.Success } if (paths.classesErrorMarkerFile.isFile) { return CDSTaskResult.Failed("CDS archive has already failed, skipping") } LOG.info("Starting generation of CDS archive to the ${paths.classesArchiveFile} and ${paths.classesArchiveFile} files") paths.mkdirs() val listResult = generateFileIfNeeded(indicator, paths, paths.classesListFile, ::generateClassList) { t -> "Failed to attach CDS Java Agent to the running IDE instance. ${t.message}" } if (listResult != CDSTaskResult.Success) return listResult val archiveResult = generateFileIfNeeded(indicator, paths, paths.classesArchiveFile, ::generateSharedArchive) { t -> "Failed to generated CDS archive. ${t.message}" } if (archiveResult != CDSTaskResult.Success) return archiveResult VMOptions.writeEnableCDSArchiveOption(paths.classesArchiveFile.absolutePath) LOG.warn("Enabled CDS archive from ${paths.classesArchiveFile}, VMOptions were updated") return CDSTaskResult.Success } private val agentPath: File get() { val libPath = File(PathManager.getLibPath()) / "cds" / "classesLogAgent.jar" if (libPath.isFile) return libPath LOG.warn("Failed to find bundled CDS classes agent in $libPath") //consider local debug IDE case val probe = File(PathManager.getHomePath()) / "out" / "classes" / "artifacts" / "classesLogAgent_jar" / "classesLogAgent.jar" if (probe.isFile) return probe error("Failed to resolve path to the CDS agent") } private fun generateClassList(indicator: CDSProgressIndicator, paths: CDSPaths) { indicator.text2 = "Collecting classes list..." val selfAttachKey = "jdk.attach.allowAttachSelf" if (!System.getProperties().containsKey(selfAttachKey)) { throw RuntimeException("Please make sure you have -D$selfAttachKey=true set in the VM options") } val duration = measureTimeMillis { val vm = VirtualMachine.attach(OSProcessUtil.getApplicationPid()) try { vm.loadAgent(agentPath.path, "${paths.classesListFile}") } finally { vm.detach() } } LOG.info("CDS classes file is generated in ${StringUtil.formatDuration(duration)}") } private fun generateSharedArchive(indicator: CDSProgressIndicator, paths: CDSPaths) { indicator.text2 = "Generating classes archive..." val logLevel = if (LOG.isDebugEnabled) "=debug" else "" val args = listOf( "-Djava.class.path=${ManagementFactory.getRuntimeMXBean().classPath}", "-Xlog:cds$logLevel", "-Xlog:class+path$logLevel", "-Xshare:dump", "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedClassListFile=${paths.classesListFile}", "-XX:SharedArchiveFile=${paths.classesArchiveFile}" ) CommandLineWrapperUtil.writeArgumentsFile(paths.classesPathFile, args, StandardCharsets.UTF_8) val durationLink = measureTimeMillis { val ext = if (SystemInfo.isWindows) ".exe" else "" val javaExe = File(System.getProperty("java.home")!!) / "bin" / "java$ext" val javaArgs = listOf( javaExe.path, "@${paths.classesPathFile}" ) val cwd = File(".").canonicalFile LOG.info("Running CDS generation process: $javaArgs in $cwd with classpath: ${args}") //recreate files for sanity FileUtil.delete(paths.dumpOutputFile) FileUtil.delete(paths.classesArchiveFile) val commandLine = object : GeneralCommandLine() { override fun buildProcess(builder: ProcessBuilder) : ProcessBuilder { return super.buildProcess(builder) .redirectErrorStream(true) .redirectInput(ProcessBuilder.Redirect.PIPE) .redirectOutput(paths.dumpOutputFile) } } commandLine.workDirectory = cwd commandLine.exePath = javaExe.absolutePath commandLine.addParameter("@${paths.classesPathFile}") if (!SystemInfo.isWindows) { // the utility does not recover process exit code from the call on Windows ExecUtil.setupLowPriorityExecution(commandLine) } val timeToWaitFor = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10) fun shouldWaitForProcessToComplete() = timeToWaitFor > System.currentTimeMillis() val process = commandLine.createProcess() try { runCatching { process.outputStream.close() } while (shouldWaitForProcessToComplete()) { if (indicator.cancelledStatus != null) throw InterruptedException() if (process.waitFor(200, TimeUnit.MILLISECONDS)) break } } finally { if (process.isAlive) { process.destroyForcibly() } } if (!shouldWaitForProcessToComplete()) { throw RuntimeException("The process took too long and will be killed. See ${paths.dumpOutputFile} for details") } val exitValue = process.exitValue() if (exitValue != 0) { val outputLines = runCatching { paths.dumpOutputFile.readLines().takeLast(30).joinToString("\n") }.getOrElse { "" } throw RuntimeException("The process existed with code $exitValue. See ${paths.dumpOutputFile} for details:\n$outputLines") } } LOG.info("Generated CDS archive in ${paths.classesArchiveFile}, " + "size = ${StringUtil.formatFileSize(paths.classesArchiveFile.length())}, " + "it took ${StringUtil.formatDuration(durationLink)}") } private operator fun File.div(s: String) = File(this, s) private val File.isValidFile get() = isFile && length() > 42 private inline fun generateFileIfNeeded(indicator: CDSProgressIndicator, paths: CDSPaths, theOutputFile: File, generate: (CDSProgressIndicator, CDSPaths) -> Unit, errorMessage: (Throwable) -> String): CDSTaskResult { try { if (theOutputFile.isValidFile) return CDSTaskResult.Success indicator.cancelledStatus?.let { return it } if (!paths.hasSameEnvironmentToBuildCDSArchive()) return CDSTaskResult.PluginsChanged generate(indicator, paths) LOG.assertTrue(theOutputFile.isValidFile, "Result file must be generated and be valid") return CDSTaskResult.Success } catch (t: Throwable) { FileUtil.delete(theOutputFile) indicator.cancelledStatus?.let { return it } if (t is InterruptedException) { return CDSTaskResult.InterruptedForRetry } val message = errorMessage(t) LOG.warn(message, t) paths.markError(message) return CDSTaskResult.Failed(message) } } }
apache-2.0
8ac8c5945e8b5725006d39305286c091
37.041916
140
0.693743
4.753086
false
false
false
false
JetBrains/xodus
vfs/src/main/kotlin/jetbrains/exodus/vfs/ClusterIterator.kt
1
6782
/** * Copyright 2010 - 2022 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.vfs import jetbrains.exodus.ByteIterable import jetbrains.exodus.env.Cursor import jetbrains.exodus.env.Transaction import jetbrains.exodus.env.TransactionBase import jetbrains.exodus.kotlin.notNull import java.io.Closeable // the ley for transaction's user object containing instance of IOCancellingPolicy private const val CANCELLING_POLICY_KEY = "CP_KEY" internal class ClusterIterator @JvmOverloads constructor(private val vfs: VirtualFileSystem, val txn: Transaction, private val fd: Long, position: Long = 0L) : Closeable { private val cursor: Cursor = vfs.contents.openCursor(txn) private val cancellingPolicy: IOCancellingPolicy? by lazy(LazyThreadSafetyMode.NONE) { vfs.cancellingPolicyProvider?.run { txn.getUserObject(CANCELLING_POLICY_KEY) as IOCancellingPolicy? ?: policy.apply { txn.setUserObject(CANCELLING_POLICY_KEY, this) } } } var current: Cluster? = null private set var isClosed: Boolean = false private set constructor(vfs: VirtualFileSystem, txn: Transaction, file: File) : this(vfs, txn, file.descriptor) init { (txn as TransactionBase).checkIsFinished() if (position >= 0L) { seek(position) } isClosed = false } /** * Seeks to the cluster that contains data by position. Doesn't navigate within cluster itself. * * @param position position in the file */ fun seek(position: Long) { var pos = position val cs = vfs.config.clusteringStrategy val it: ByteIterable? if (cs.isLinear) { // if clustering strategy is linear then all clusters has the same size val firstClusterSize = cs.firstClusterSize it = cursor.getSearchKeyRange(ClusterKey.toByteIterable(fd, pos / firstClusterSize)) if (it == null) { current = null } else { current = readCluster(it) adjustCurrentCluster() val currentCluster = current if (currentCluster != null) { currentCluster.startingPosition = currentCluster.clusterNumber * firstClusterSize } } } else { it = cursor.getSearchKeyRange(ClusterKey.toByteIterable(fd, 0L)) if (it == null) { current = null } else { val maxClusterSize = cs.maxClusterSize var clusterSize = 0L current = readCluster(it) var startingPosition = 0L adjustCurrentCluster() while (current != null) { // if cluster size is equal to max cluster size, then all further cluster will have that size, // so we don't need to load their size val notNullCluster = current.notNull if (clusterSize < maxClusterSize) { clusterSize = notNullCluster.getSize().toLong() } notNullCluster.startingPosition = startingPosition if (pos < clusterSize) { break } pos -= clusterSize startingPosition += clusterSize moveToNext() } } } } fun size(): Long { var result = 0L val cs = vfs.config.clusteringStrategy if (cs.isLinear) { val clusterSize = cs.firstClusterSize.toLong() // if clustering strategy is linear we can try to navigate to the last file cluster if ((cursor.getSearchKeyRange(ClusterKey.toByteIterable(fd + 1, 0L)) != null && cursor.prev) || cursor.prev) { val clusterKey = ClusterKey(cursor.key) if (clusterKey.descriptor == fd) { return clusterKey.clusterNumber * clusterSize + readCluster(cursor.value).getSize() } } seek(0L) // if clustering strategy is linear we can avoid reading cluster size for each cluster var previous: Cluster? = null while (hasCluster()) { if (previous != null) { result += clusterSize } previous = current moveToNext() } if (previous != null) { result += previous.getSize().toLong() } } else { seek(0L) while (hasCluster()) { result += current.notNull.getSize().toLong() moveToNext() } } return result } fun hasCluster() = current != null fun moveToNext() { cancelIfNeeded() if (current != null) { if (!cursor.next) { current = null } else { current = readCluster(cursor.value) adjustCurrentCluster() } } } fun deleteCurrent() { if (current != null) { cursor.deleteCurrent() } } override fun close() { if (!isClosed) { cursor.close() isClosed = true } } fun isObsolete() = txn.isFinished private fun readCluster(it: ByteIterable): Cluster { val clusterConverter = vfs.clusterConverter return Cluster(clusterConverter?.onRead(it) ?: it) } private fun adjustCurrentCluster() { val clusterKey = ClusterKey(cursor.key) if (clusterKey.descriptor != fd) { current = null } else { current.notNull.clusterNumber = clusterKey.clusterNumber } } private fun cancelIfNeeded() { cancellingPolicy?.run { if (needToCancel()) { doCancel() } } } }
apache-2.0
e0451d52e4baf00fe7bf8a74fa1b9f6c
33.784615
114
0.546299
5.17315
false
false
false
false
siosio/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/LookupCancelService.kt
2
3442
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.lookup.LookupEvent import com.intellij.codeInsight.lookup.LookupListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.event.CaretEvent import com.intellij.openapi.editor.event.CaretListener import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jetbrains.kotlin.idea.util.application.getServiceSafe import org.jetbrains.kotlin.psi.KtTypeArgumentList class LookupCancelService { internal class Reminiscence(editor: Editor, offset: Int) { var editor: Editor? = editor private var marker: RangeMarker? = editor.document.createRangeMarker(offset, offset) // forget about auto-popup cancellation when the caret is moved to the start or before it private var editorListener: CaretListener? = object : CaretListener { override fun caretPositionChanged(e: CaretEvent) { if (marker != null && (!marker!!.isValid || editor.logicalPositionToOffset(e.newPosition) <= offset)) { dispose() } } } init { ApplicationManager.getApplication()!!.assertIsDispatchThread() editor.caretModel.addCaretListener(editorListener!!) } fun matches(editor: Editor, offset: Int): Boolean { return editor == this.editor && marker?.startOffset == offset } fun dispose() { ApplicationManager.getApplication()!!.assertIsDispatchThread() if (marker != null) { editor!!.caretModel.removeCaretListener(editorListener!!) marker = null editor = null editorListener = null } } } internal val lookupCancelListener = object : LookupListener { override fun lookupCanceled(event: LookupEvent) { val lookup = event.lookup if (event.isCanceledExplicitly && lookup.isCompletion) { val offset = lookup.currentItem?.getUserData(LookupCancelService.AUTO_POPUP_AT) if (offset != null) { lastReminiscence?.dispose() if (offset <= lookup.editor.document.textLength) { lastReminiscence = Reminiscence(lookup.editor, offset) } } } } } internal fun disposeLastReminiscence(editor: Editor) { if (lastReminiscence?.editor == editor) { lastReminiscence!!.dispose() lastReminiscence = null } } private var lastReminiscence: Reminiscence? = null companion object { fun getInstance(project: Project): LookupCancelService = project.getServiceSafe() fun getServiceIfCreated(project: Project): LookupCancelService? = project.getServiceIfCreated(LookupCancelService::class.java) val AUTO_POPUP_AT = Key<Int>("LookupCancelService.AUTO_POPUP_AT") } fun wasAutoPopupRecentlyCancelled(editor: Editor, offset: Int): Boolean { return lastReminiscence?.matches(editor, offset) ?: false } }
apache-2.0
22dc2e26f53c4f1026638589e961867d
38.563218
158
0.656595
5.17594
false
false
false
false
siosio/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHLoadingPanel.kt
2
5438
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.ui.LoadingDecorator import com.intellij.ui.AnimatedIcon import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.JBLoadingPanel import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.util.ui.AsyncProcessIcon import com.intellij.util.ui.ComponentWithEmptyText import com.intellij.util.ui.StatusText import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.ui.frame.ProgressStripe import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.ui.util.getName import java.awt.BorderLayout import java.awt.GridBagLayout import java.awt.event.KeyEvent import java.util.function.Function import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.KeyStroke class GHLoadingPanel<T> @Deprecated("Replaced with factory because JBLoadingPanel is not really needed for initial loading", ReplaceWith("GHLoadingPanelFactory().create()")) constructor(model: GHLoadingModel, content: T, parentDisposable: Disposable, textBundle: EmptyTextBundle = EmptyTextBundle.Default) : JBLoadingPanel(BorderLayout(), createDecorator(parentDisposable)) where T : JComponent, T : ComponentWithEmptyText { companion object { private fun createDecorator(parentDisposable: Disposable): Function<JPanel, LoadingDecorator> { return Function<JPanel, LoadingDecorator> { object : LoadingDecorator(it, parentDisposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) { override fun customizeLoadingLayer(parent: JPanel, text: JLabel, icon: AsyncProcessIcon): NonOpaquePanel { parent.layout = GridBagLayout() text.text = ApplicationBundle.message("label.loading.page.please.wait") text.icon = AnimatedIcon.Default() text.foreground = UIUtil.getContextHelpForeground() val result = NonOpaquePanel(text) parent.add(result) return result } } } } class Controller(private val model: GHLoadingModel, private val loadingPanel: JBLoadingPanel, private val updateLoadingPanel: ProgressStripe, private val statusText: StatusText, private val textBundle: EmptyTextBundle, private val errorHandlerProvider: () -> GHLoadingErrorHandler?) { init { model.addStateChangeListener(object : GHLoadingModel.StateChangeListener { override fun onLoadingStarted() = update() override fun onLoadingCompleted() = update() override fun onReset() = update() }) update() } private fun update() { if (model.loading) { loadingPanel.isFocusable = true statusText.clear() if (model.resultAvailable) { updateLoadingPanel.startLoading() } else { loadingPanel.startLoading() } } else { loadingPanel.stopLoading() updateLoadingPanel.stopLoading() if (model.resultAvailable) { loadingPanel.isFocusable = false loadingPanel.resetKeyboardActions() statusText.text = textBundle.empty } else { val error = model.error if (error != null) { statusText.clear() .appendText(textBundle.errorPrefix, SimpleTextAttributes.ERROR_ATTRIBUTES) .appendSecondaryText(error.message ?: GithubBundle.message("unknown.loading.error"), SimpleTextAttributes.ERROR_ATTRIBUTES, null) errorHandlerProvider()?.getActionForError(error)?.let { statusText.appendSecondaryText(" ${it.getName()}", SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, it) loadingPanel.registerKeyboardAction(it, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED) } } else statusText.text = textBundle.default } } } } } private val updateLoadingPanel = ProgressStripe(content, parentDisposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply { isOpaque = false } var errorHandler: GHLoadingErrorHandler? = null init { isOpaque = false add(updateLoadingPanel, BorderLayout.CENTER) Controller(model, this, updateLoadingPanel, content.emptyText, textBundle) { errorHandler } } interface EmptyTextBundle { val default: String val empty: String val errorPrefix: String class Simple(override val default: String, override val errorPrefix: String, override val empty: String = "") : EmptyTextBundle object Default : EmptyTextBundle { override val default: String = "" override val empty: String = "" override val errorPrefix: String = GithubBundle.message("cannot.load.data") } } }
apache-2.0
caf299f6c4aa54850a3844849ddf3ddf
37.567376
140
0.673409
5.315738
false
false
false
false
chemickypes/Glitchy
glitchappcore/src/main/java/me/bemind/glitchappcore/DataStructure.kt
1
1510
package me.bemind.glitchappcore import android.graphics.Bitmap import android.util.LruCache import java.util.* /** * Created by angelomoroni on 09/04/17. */ interface Stack<T> : Iterable<T> { fun push(item: T) fun pop(): T? fun peek(): T? fun isEmpty(): Boolean { return size() == 0 } fun size(): Int fun clear() fun clearKeepingFirst() } class LinkedStack<T> :Stack<T>{ val stack = LinkedList<T>() override fun push(item: T) { stack.add(item) } override fun pop(): T? { return if(stack.size>0){ stack.removeLast() }else{ null } } override fun peek(): T? { return if(stack.size>0){ stack.last }else{ null } } override fun size(): Int { return stack.size } override fun clear() { stack.clear() } override fun clearKeepingFirst() { val t = stack.first stack.clear() push(t) } override fun iterator(): Iterator<T> { return stack.iterator() } fun first():T? = if(stack.size>0){ stack.first }else{ null } fun addAll(collection: Collection<T> = ArrayList<T>()) = stack.addAll(collection) fun getAllAsList() :ArrayList<T> = ArrayList(stack) fun removeOld():T?{ val t = getOld() stack.removeAt(1) return t } fun getOld(): T? { return stack[1] } }
apache-2.0
9812d1517038575a7b0a160189004e3a
14.729167
85
0.522517
3.746898
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddFullQualifierIntention.kt
1
7289
// 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.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.util.createSmartPointer import com.intellij.psi.util.descendantsOfType import com.intellij.psi.util.elementType import com.intellij.psi.util.prevLeaf import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.quoteSegmentsIfNeeded import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.core.thisOrParentIsRoot import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.utils.addToStdlib.safeAs class AddFullQualifierIntention : SelfTargetingIntention<KtNameReferenceExpression>( KtNameReferenceExpression::class.java, KotlinBundle.lazyMessage("add.full.qualifier") ), LowPriorityAction { override fun isApplicableTo(element: KtNameReferenceExpression, caretOffset: Int): Boolean = isApplicableTo( referenceExpression = element, contextDescriptor = null, ) override fun applyTo(element: KtNameReferenceExpression, editor: Editor?) { val fqName = element.findSingleDescriptor()?.importableFqName ?: return applyTo(element, fqName) } override fun startInWriteAction(): Boolean = false companion object { fun isApplicableTo(referenceExpression: KtNameReferenceExpression, contextDescriptor: DeclarationDescriptor?): Boolean { if (referenceExpression.parent is KtInstanceExpressionWithLabel) return false val prevElement = referenceExpression.prevElementWithoutSpacesAndComments() if (prevElement.elementType == KtTokens.DOT) return false val resultDescriptor = contextDescriptor ?: referenceExpression.findSingleDescriptor() ?: return false if (resultDescriptor.isExtension || resultDescriptor.isInRoot) return false if (prevElement.elementType == KtTokens.COLONCOLON) { if (resultDescriptor.isTopLevelCallable) return false val prevSibling = prevElement?.getPrevSiblingIgnoringWhitespaceAndComments() if (prevSibling is KtNameReferenceExpression || prevSibling is KtDotQualifiedExpression) return false } val file = referenceExpression.containingKtFile val identifier = referenceExpression.getIdentifier()?.text val fqName = resultDescriptor.importableFqName if (file.importDirectives.any { it.aliasName == identifier && it.importedFqName == fqName }) return false return true } fun applyTo(referenceExpression: KtNameReferenceExpression, fqName: FqName): KtElement { val qualifier = fqName.parent().quoteSegmentsIfNeeded() return referenceExpression.project.executeWriteCommand(KotlinBundle.message("add.full.qualifier"), groupId = null) { val psiFactory = KtPsiFactory(referenceExpression) when (val parent = referenceExpression.parent) { is KtCallableReferenceExpression -> addOrReplaceQualifier(psiFactory, parent, qualifier) is KtCallExpression -> replaceExpressionWithDotQualifier(psiFactory, parent, qualifier) is KtUserType -> addQualifierToType(psiFactory, parent, qualifier) else -> replaceExpressionWithQualifier(psiFactory, referenceExpression, fqName) } } } fun addQualifiersRecursively(root: KtElement): KtElement { if (root is KtNameReferenceExpression) return applyIfApplicable(root) ?: root root.descendantsOfType<KtNameReferenceExpression>() .map { it.createSmartPointer() } .toList() .asReversed() .forEach { it.element?.let(::applyIfApplicable) } return root } private fun applyIfApplicable(referenceExpression: KtNameReferenceExpression): KtElement? { val descriptor = referenceExpression.findSingleDescriptor() ?: return null val fqName = descriptor.importableFqName ?: return null if (!isApplicableTo(referenceExpression, descriptor)) return null return applyTo(referenceExpression, fqName) } } } private fun addOrReplaceQualifier(factory: KtPsiFactory, expression: KtCallableReferenceExpression, qualifier: String): KtElement { val receiver = expression.receiverExpression return if (receiver != null) { replaceExpressionWithDotQualifier(factory, receiver, qualifier) } else { val qualifierExpression = factory.createExpression(qualifier) expression.addBefore(qualifierExpression, expression.firstChild) as KtElement } } private fun replaceExpressionWithDotQualifier(psiFactory: KtPsiFactory, expression: KtExpression, qualifier: String): KtElement { val expressionWithQualifier = psiFactory.createExpressionByPattern("$0.$1", qualifier, expression) return expression.replaced(expressionWithQualifier) } private fun addQualifierToType(psiFactory: KtPsiFactory, userType: KtUserType, qualifier: String): KtElement { val type = userType.parent.safeAs<KtNullableType>() ?: userType val typeWithQualifier = psiFactory.createType("$qualifier.${type.text}") return type.parent.replaced(typeWithQualifier) } private fun replaceExpressionWithQualifier( psiFactory: KtPsiFactory, referenceExpression: KtNameReferenceExpression, fqName: FqName ): KtElement { val expressionWithQualifier = psiFactory.createExpression(fqName.asString()) return referenceExpression.replaced(expressionWithQualifier) } private val DeclarationDescriptor.isInRoot: Boolean get() = importableFqName?.thisOrParentIsRoot() != false private val DeclarationDescriptor.isTopLevelCallable: Boolean get() = safeAs<CallableMemberDescriptor>()?.containingDeclaration is PackageFragmentDescriptor || safeAs<ConstructorDescriptor>()?.containingDeclaration?.containingDeclaration is PackageFragmentDescriptor private fun KtNameReferenceExpression.prevElementWithoutSpacesAndComments(): PsiElement? = prevLeaf { it.elementType !in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET } private fun KtNameReferenceExpression.findSingleDescriptor(): DeclarationDescriptor? = resolveMainReferenceToDescriptors().singleOrNull()
apache-2.0
ff52faa7c4d868e5f3805f0b8f3a30c5
49.618056
158
0.751269
6.004119
false
false
false
false
vovagrechka/fucking-everything
attic/alraune/alraune-back/src/QueryBuilder.kt
1
10168
package alraune.back import vgrechka.* import java.sql.PreparedStatement import java.sql.ResultSet import java.sql.ResultSetMetaData import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KType import kotlin.reflect.full.* //class QueryBuilder() { // val sqlBuf = StringBuilder() // val params = mutableListOf<Any?>() // // // class OptsPile( // val isUpdate: Boolean? = null, // val ctorParamMatching: CtorParamMatching? = null, // val compoundClass: Class<*>? = null, // val componentClasses: List<Class<*>>? = null, // val params_barney: Params_barney? = null // ) // // enum class CtorParamMatching { // Positional, ByName // } // // class ShitHolder(val shit: Any?) // // // fun text(x: String): QueryBuilder { // sqlBuf += " " + x // return this // } // // fun text(s: String, p: Any?): QueryBuilder { // text(s) // param(p) // return this // } // // fun format(format: String, vararg args: Any): QueryBuilder { // text(String.format(format, *args)) // return this // } // // fun param(x: Any?): QueryBuilder { // sqlBuf += " ?" // params += when { // x is Enum<*> -> x.name // else -> x // } // return this // } // // fun execute() { // selectOrUpdate(OptsPile(isUpdate = true)) // } // // fun <Entity : Any> selectSimple(entityClass: Class<Entity>, opts: OptsPile = OptsPile()): List<Entity> { // val list = selectOrUpdate(OptsPile( // isUpdate = false, // compoundClass = ShitHolder::class.java, // componentClasses = listOf(entityClass), // ctorParamMatching = opts.ctorParamMatching ?: CtorParamMatching.ByName))!! // return list.map {entityClass.cast((it as ShitHolder).shit)} // } // // fun dbValueToKtValue(type: KType, row: ReifiedResultSet.Row, colIndex: Int): Any? { // val dbValue = row.getObject(colIndex) // val ktClass = type.classifier as KClass<*> // return when { // dbValue == null -> { // check(type.isMarkedNullable) // null // } // ktClass.isSubclassOf(Enum::class) -> { // ktClass.java.enumConstants.find {(it as Enum<*>).name == dbValue} // ?: bitch("dbValue = $dbValue") // } // else -> ktClass.cast(dbValue) // } // } // // fun instantiateShitFromDBValues(clazz: Class<*>, row: ReifiedResultSet.Row, fromColumn: Int, untilColumn: Int, opts: OptsPile): Any { // check(clazz.kotlin.constructors.size == 1) // val ctor = clazz.kotlin.primaryConstructor!! // val takenColumnsIndices = mutableSetOf<Int>() // val ctorArgs = mutableListOf<Any?>() // // fun loopThroughColumns(block: (colIndex: Int, colName: String) -> Unit) { // for (colIndex in fromColumn until untilColumn) { // if (colIndex !in takenColumnsIndices) { // var colName = row.metaData.getColumnName(colIndex) // colName.indexOfOrNull(".")?.let { // colName = colName.substring(it + 1) // } // block(colIndex, colName) // } // } // } // // for (ctorParam in ctor.valueParameters) { // loopThroughColumns {colIndex, colName -> // val matches = when (opts.ctorParamMatching!!) { // CtorParamMatching.Positional -> ctorArgs.size < ctor.valueParameters.size // CtorParamMatching.ByName -> ctorParam.name!!.toLowerCase() == colName.toLowerCase() // } // if (matches) { // takenColumnsIndices += colIndex // ctorArgs += dbValueToKtValue(ctorParam.type, row, colIndex) // } // } // } // // val inst = // try {ctor.call(*ctorArgs.toTypedArray())} // catch (e: Throwable) { // "break on me" // throw e // } // // loopThroughColumns {colIndex, colName -> // val prop = clazz.kotlin.memberProperties // .find {it.name.toLowerCase() == colName.toLowerCase()} // ?: bitch("colName = $colName") // @Suppress("UNCHECKED_CAST") // (prop as KMutableProperty1<Any, Any?>).set(inst, dbValueToKtValue(prop.returnType, row, colIndex)) // } // // return inst // } // // class ReifiedResultSet(private val rs: ResultSet) { // val metaData = rs.metaData!! // val rows = mutableListOf<Row>() // init { // val maxRows = 1000 // while (rs.next()) { // if (rows.size == maxRows) // bitch("62617923-aea0-4d34-aa6b-9d3d68f4df16") // rows += Row( // metaData, // values = (1..metaData.columnCount).map {rs.getObject(it)}, // nameToValue = mapOf(*(1..metaData.columnCount).map { // metaData.getColumnName(it) to rs.getObject(it)}.toTypedArray())) // } // } // // class Row(val metaData: ResultSetMetaData, val values: List<Any?>, val nameToValue: Map<String, Any?>) { // fun getObject(colIndex: Int): Any? = values[colIndex - 1] // } // } // // private fun selectOrUpdate(opts: OptsPile): List<Any>? { // val t0 = System.currentTimeMillis() // try { // var st: PreparedStatement? = null // var _rs: ResultSet? = null // // var exception: Throwable? = null // try { // st = rctx.connection.prepareStatement(sqlBuf.toString()) // for ((index, ktValue) in params.withIndex()) { // val dbValue = when { // ktValue is Enum<*> -> ktValue.name // else -> ktValue // } // st.setObject(index + 1, dbValue) // } // // if (opts.isUpdate!!) { // st.execute() // return null // } else { // _rs = st.executeQuery() // val rs = ReifiedResultSet(_rs) // val list = mutableListOf<Any>() // val meta = rs.metaData // for (row in rs.rows) { // val compoundCtorArgs = mutableListOf<Any>() // var fromColumn = 1 // var consideringComponent = 0 // // fun considerColumns(untilColumn: Int) { // val componentClass = opts.componentClasses!![consideringComponent] // compoundCtorArgs += instantiateShitFromDBValues(componentClass, row, fromColumn, untilColumn, opts) // fromColumn = untilColumn + 1 // ++consideringComponent // } // // for (i in 1..meta.columnCount) { // if (meta.getColumnName(i).startsWith("separator_")) { // considerColumns(untilColumn = i) // } // } // considerColumns(untilColumn = meta.columnCount + 1) // // val compoundClassInstance = opts.compoundClass!!.kotlin.primaryConstructor!!.call(*compoundCtorArgs.toTypedArray()) // list += compoundClassInstance // } // // opts.params_barney?.let { // if (it.checkLimitExactlyMatchesActualByTryingToSelectOneMore) { // val limit = it.limit!! // if (list.size > limit) // bitch("This query should have returned exactly $limit rows, but got at least one more") // } // } // // return list // } // } // catch (e: Throwable) { // exception = e // throw exception // } // finally { // fun close(x: AutoCloseable?) { // if (x != null) { // try { // x.close() // } catch (e: Throwable) { // exception?.addSuppressed(e) // } // } // } // close(_rs) // close(st) // } // } // finally { // val elapsed = System.currentTimeMillis() - t0 // if (AlGlobalContext.queryLoggingEnabled) // clog("elapsed = $elapsed") // } // } // // fun <Entity : Any> selectOneSimple(entityClass: Class<Entity>, opts: OptsPile = OptsPile()): Entity { // return selectSimple(entityClass, opts).first() // } // // fun selectOneLong(): Long { // val res = selectOneSimple(ShitHolder::class.java, OptsPile(ctorParamMatching = CtorParamMatching.Positional)) // return res.shit as Long // } // // fun <Compound : Any> selectCompound(compoundClass: Class<Compound>, params_barney: Params_barney? = null): List<Compound> { // // TODO:vgrechka Use entityWithParamsClass from params_barney // check(compoundClass.constructors.size == 1) // val componentClasses = compoundClass.kotlin.primaryConstructor!!.valueParameters.map { // it.type.classifier as KClass<*> // } // val list = selectOrUpdate(OptsPile( // isUpdate = false, // compoundClass = compoundClass, // componentClasses = componentClasses.map {it.java}, // ctorParamMatching = CtorParamMatching.ByName, // params_barney = params_barney // ))!! // return list.map {compoundClass.cast(it)} // } //}
apache-2.0
dfbb73c2b1d2b0f01c8e432f4d28217e
36.109489
141
0.493411
4.323129
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/IdeDocumentationTargetProviderImpl.kt
1
2283
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("TestOnlyProblems") // KTIJ-19938 package com.intellij.lang.documentation.ide.impl import com.intellij.codeInsight.documentation.DocumentationManager import com.intellij.codeInsight.lookup.LookupElement import com.intellij.lang.documentation.DocumentationTarget import com.intellij.lang.documentation.ide.IdeDocumentationTargetProvider import com.intellij.lang.documentation.psi.psiDocumentationTarget import com.intellij.lang.documentation.symbol.impl.symbolDocumentationTargets import com.intellij.model.Pointer import com.intellij.model.Symbol import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.psi.PsiFile import com.intellij.util.castSafelyTo open class IdeDocumentationTargetProviderImpl(private val project: Project) : IdeDocumentationTargetProvider { override fun documentationTarget(editor: Editor, file: PsiFile, lookupElement: LookupElement): DocumentationTarget? { val symbolTargets = (lookupElement.`object` as? Pointer<*>) ?.dereference() ?.castSafelyTo<Symbol>() ?.let { symbolDocumentationTargets(file.project, listOf(it)) } if (!symbolTargets.isNullOrEmpty()) { return symbolTargets.first() } val sourceElement = file.findElementAt(editor.caretModel.offset) val targetElement = DocumentationManager.getElementFromLookup(project, editor, file, lookupElement) ?: return null return psiDocumentationTarget(targetElement, sourceElement) } override fun documentationTargets(editor: Editor, file: PsiFile, offset: Int): List<DocumentationTarget> { val symbolTargets = symbolDocumentationTargets(file, offset) if (symbolTargets.isNotEmpty()) { return symbolTargets } val documentationManager = DocumentationManager.getInstance(project) val (targetElement, sourceElement) = documentationManager.findTargetElementAndContext(editor, offset, file) ?: return emptyList() return listOf(psiDocumentationTarget(targetElement, sourceElement)) } }
apache-2.0
eab83fa260c9c22a10af96421b8f5322
47.574468
120
0.779238
4.941558
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/test/kotlin/com/aemtools/index/search/OSGiConfigSearchTest.kt
1
2412
package com.aemtools.index.search import com.aemtools.index.model.sortByMods import com.aemtools.test.base.BaseLightTest import com.aemtools.test.fixture.OSGiConfigFixtureMixin /** * @author Dmytro Troynikov */ class OSGiConfigSearchTest : BaseLightTest(), OSGiConfigFixtureMixin { fun testBasicSearch() = fileCase { addEmptyOSGiConfigs("/config/com.test.Service.xml") verify { OSGiConfigSearch.findConfigsForClass("com.test.Service", project) .firstOrNull() ?: throw AssertionError("Unable to find configuration") } } fun testSearchForOSGiServiceFactory() = fileCase { addEmptyOSGiConfigs( "/config/com.test.Service-first.xml", "/config/com.test.Service-second.xml" ) verify { val configs = OSGiConfigSearch.findConfigsForClass("com.test.Service", project) assertEquals(2, configs.size) } } fun testSearchForOSGiConfigurationFactory() = fileCase { addEmptyOSGiConfigs( "/config/com.test.Service-my-long-name.xml", "/config/com.test.Service-my-very-long-name-2.xml" ) verify { val configs = OSGiConfigSearch.findConfigsForClass("com.test.Service", project) assertEquals(2, configs.size) assertEquals(listOf( "my-long-name", "my-very-long-name-2" ), configs.sortByMods().map { it.suffix() } ) } } fun testBasicSearchForOSGiServiceWithFile() = fileCase { val filesNames = listOf( "/config/com.test.Service.xml", "/config.author/com.test.Service.xml" ) addEmptyOSGiConfigs(*filesNames.toTypedArray()) verify { val configs = OSGiConfigSearch.findConfigsForClass("com.test.Service", project, true) assertEquals( filesNames.map { "/src$it" }, configs.sortByMods().map { it.xmlFile?.virtualFile?.path } ) } } fun testSearchForOSGiServiceFactoryConfigs() = fileCase { val fileNames = listOf( "/config/com.test.Service-first.xml", "/config/com.test.Service-second.xml" ) addEmptyOSGiConfigs(*fileNames.toTypedArray()) verify { val configs = OSGiConfigSearch.findConfigsForClass("com.test.Service", project, true) assertEquals(2, configs.size) assertEquals( fileNames.map { "/src$it" }, configs.sortByMods().map { it.xmlFile?.virtualFile?.path } ) } } }
gpl-3.0
bae8dba1b99ec7c9eb90619a753bf811
26.724138
91
0.657546
4.261484
false
true
false
false
oldcwj/iPing
commons/src/main/kotlin/com/simplemobiletools/commons/extensions/List.kt
1
668
package com.simplemobiletools.commons.extensions import android.net.Uri import java.util.* fun List<Uri>.getMimeType(): String { val mimeGroups = HashSet<String>(size) val subtypes = HashSet<String>(size) forEach { val parts = it.path.getMimeTypeFromPath().split("/") if (parts.size == 2) { mimeGroups.add(parts.getOrElse(0, { "" })) subtypes.add(parts.getOrElse(1, { "" })) } else { return "*/*" } } return when { subtypes.size == 1 -> "${mimeGroups.first()}/${subtypes.first()}" mimeGroups.size == 1 -> "${mimeGroups.first()}/*" else -> "*/*" } }
gpl-3.0
7efcc719df292294ea0b8e3a0d3d2609
26.833333
73
0.550898
4.048485
false
false
false
false
GunoH/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickDoc/KotlinDocumentationTarget.kt
1
12830
// 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.quickDoc import com.google.common.html.HtmlEscapers import com.intellij.codeInsight.documentation.DocumentationManagerUtil import com.intellij.codeInsight.navigation.targetPresentation import com.intellij.lang.documentation.DocumentationResult import com.intellij.lang.documentation.DocumentationSettings import com.intellij.lang.documentation.DocumentationTarget import com.intellij.lang.java.JavaDocumentationProvider import com.intellij.model.Pointer import com.intellij.navigation.TargetPresentation import com.intellij.openapi.util.text.HtmlChunk import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.refactoring.suggested.createSmartPointer import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.components.KtDeclarationRendererOptions import org.jetbrains.kotlin.analysis.api.components.KtTypeRendererOptions import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.kdoc.* import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.appendHighlighted import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.generateJavadoc import org.jetbrains.kotlin.idea.kdoc.KDocRenderer.renderKDoc import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.kdoc.psi.api.KDoc import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* internal class KotlinDocumentationTarget(val element: PsiElement, private val originalElement: PsiElement?) : DocumentationTarget { override fun createPointer(): Pointer<out DocumentationTarget> { val elementPtr = element.createSmartPointer() val originalElementPtr = originalElement?.createSmartPointer() return Pointer { val element = elementPtr.dereference() ?: return@Pointer null KotlinDocumentationTarget(element, originalElementPtr?.dereference()) } } override fun presentation(): TargetPresentation { return targetPresentation(element) } override fun computeDocumentationHint(): String? { return computeLocalDocumentation(element, originalElement, true) } override val navigatable: Navigatable? get() = element as? Navigatable override fun computeDocumentation(): DocumentationResult? { val html = computeLocalDocumentation(element, originalElement, false) ?: return null return DocumentationResult.documentation(html) } companion object { internal val RENDERING_OPTIONS = KtDeclarationRendererOptions( typeRendererOptions = KtTypeRendererOptions.SHORT_NAMES, renderUnitReturnType = true, renderDefaultParameterValue = true, renderDeclarationHeader = true, approximateTypes = true ) } } @Nls private fun computeLocalDocumentation(element: PsiElement, originalElement: PsiElement?, quickNavigation: Boolean): String? { when { element is KtFunctionLiteral -> { val itElement = findElementWithText(originalElement, "it") val itReference = itElement?.getParentOfType<KtNameReferenceExpression>(false) if (itReference != null) { return buildString { renderKotlinDeclaration( element, quickNavigation, symbolFinder = { it -> (it as? KtFunctionLikeSymbol)?.valueParameters?.firstOrNull() }) } } } element is KtTypeReference -> { val declaration = element.parent if (declaration is KtCallableDeclaration && declaration.receiverTypeReference == element && findElementWithText(originalElement, "this") != null ) { return computeLocalDocumentation(declaration, originalElement, quickNavigation) } } element is KtClass && element.isEnum() -> { return buildString { renderEnumSpecialFunction(originalElement, element, quickNavigation) } } element is KtEnumEntry && !quickNavigation -> { val ordinal = element.containingClassOrObject?.body?.run { getChildrenOfType<KtEnumEntry>().indexOf(element) } val project = element.project return buildString { renderKotlinDeclaration(element, false) { definition { it.inherit() ordinal?.let { append("<br>") appendHighlighted("// ", project) { asInfo } appendHighlighted(KotlinBundle.message("quick.doc.text.enum.ordinal", ordinal), project) { asInfo } } } } } } element is KtDeclaration -> { return buildString { renderKotlinDeclaration(element, quickNavigation) } } element is KtLightDeclaration<*, *> -> { val origin = element.kotlinOrigin ?: return null return computeLocalDocumentation(origin, element, quickNavigation) } element is KtValueArgumentList -> { val referenceExpression = element.prevSibling as? KtSimpleNameExpression ?: return null val calledElement = referenceExpression.mainReference.resolve() if (calledElement is KtNamedFunction || calledElement is KtConstructor<*>) { // In case of Kotlin function or constructor return computeLocalDocumentation(calledElement as KtExpression, element, quickNavigation) } else if (calledElement is PsiMethod) { return JavaDocumentationProvider().generateDoc(calledElement, referenceExpression) } } element is KtCallExpression -> { val calledElement = element.referenceExpression()?.mainReference?.resolve() ?: return null return computeLocalDocumentation(calledElement, originalElement, quickNavigation) } element.isModifier() -> { when (element.text) { KtTokens.LATEINIT_KEYWORD.value -> return KotlinBundle.message("quick.doc.text.lateinit") KtTokens.TAILREC_KEYWORD.value -> return KotlinBundle.message("quick.doc.text.tailrec") } } } return null } private fun getContainerInfo(ktDeclaration: KtDeclaration): HtmlChunk { analyze(ktDeclaration) { val containingSymbol = ktDeclaration.getSymbol().getContainingSymbol() val fqName = (containingSymbol as? KtClassLikeSymbol)?.classIdIfNonLocal?.asFqNameString() ?: (ktDeclaration.containingFile as? KtFile)?.packageFqName?.takeIf { !it.isRoot }?.asString() val fqNameSection = fqName ?.let { @Nls val link = StringBuilder() val highlighted = if (DocumentationSettings.isSemanticHighlightingOfLinksEnabled()) KDocRenderer.highlight(it, ktDeclaration.project) { asClassName } else it DocumentationManagerUtil.createHyperlink(link, it, highlighted, false, false) HtmlChunk.fragment( HtmlChunk.icon("class", KotlinIcons.CLASS), HtmlChunk.nbsp(), HtmlChunk.raw(link.toString()), HtmlChunk.br() ) } ?: HtmlChunk.empty() val fileNameSection = ktDeclaration .containingFile ?.name ?.takeIf { containingSymbol == null } ?.let { HtmlChunk.fragment( HtmlChunk.icon("file", KotlinIcons.FILE), HtmlChunk.nbsp(), HtmlChunk.text(it), HtmlChunk.br() ) } ?: HtmlChunk.empty() return HtmlChunk.fragment(fqNameSection, fileNameSection) } } private fun StringBuilder.renderEnumSpecialFunction( originalElement: PsiElement?, element: KtClass, quickNavigation: Boolean ) { val referenceExpression = originalElement?.getNonStrictParentOfType<KtReferenceExpression>() if (referenceExpression != null) { // When caret on special enum function (e.g. SomeEnum.values<caret>()) // element is not an KtReferenceExpression, but KtClass of enum // so reference extracted from originalElement analyze(referenceExpression) { val symbol = referenceExpression.mainReference.resolveToSymbol() as? KtNamedSymbol val name = symbol?.name?.asString() if (name != null) { val containingClass = symbol.getContainingSymbol() as? KtClassOrObjectSymbol val superClasses = containingClass?.superTypes?.mapNotNull { t -> t.expandedClassSymbol } val kdoc = superClasses?.firstNotNullOfOrNull { superClass -> superClass.psi?.navigationElement?.findDescendantOfType<KDoc> { doc -> doc.getChildrenOfType<KDocSection>().any { it.findTagByName(name) != null } } } renderKotlinDeclaration(element, false) { if (!quickNavigation && kdoc != null) { description { renderKDoc(kdoc.getDefaultSection()) } } } return } } } renderKotlinDeclaration(element, quickNavigation) } private fun findElementWithText(element: PsiElement?, text: String): PsiElement? { return when { element == null -> null element.text == text -> element element.prevLeaf()?.text == text -> element.prevLeaf() else -> null } } internal fun PsiElement?.isModifier() = this != null && parent is KtModifierList && KtTokens.MODIFIER_KEYWORDS_ARRAY.firstOrNull { it.value == text } != null private fun StringBuilder.renderKotlinDeclaration( declaration: KtDeclaration, onlyDefinition: Boolean, symbolFinder: KtAnalysisSession.(KtSymbol) -> KtSymbol? = { it }, preBuild: KDocTemplate.() -> Unit = {} ) { analyze(declaration) { val symbol = symbolFinder(declaration.getSymbol()) if (symbol is KtDeclarationSymbol) { insert(KDocTemplate()) { definition { append(HtmlEscapers.htmlEscaper().escape(symbol.render(KotlinDocumentationTarget.RENDERING_OPTIONS))) } if (!onlyDefinition) { description { renderKDoc(symbol, this) } } getContainerInfo(declaration).toString().takeIf { it.isNotBlank() }?.let { info -> containerInfo { append(info) } } preBuild() } } } } private fun KtAnalysisSession.renderKDoc( symbol: KtSymbol, stringBuilder: StringBuilder, ) { val declaration = symbol.psi as? KtElement val kDoc = findKDoc(symbol) if (kDoc != null) { stringBuilder.renderKDoc(kDoc.contentTag, kDoc.sections) return } if (declaration is KtSecondaryConstructor) { declaration.getContainingClassOrObject().findKDoc()?.let { stringBuilder.renderKDoc(it.contentTag, it.sections) } } else if (declaration is KtFunction && symbol is KtCallableSymbol && symbol.getAllOverriddenSymbols().any { it.psi is PsiMethod }) { LightClassUtil.getLightClassMethod(declaration)?.let { stringBuilder.insert(KDocTemplate.DescriptionBodyTemplate.FromJava()) { body = generateJavadoc(it) } } } } private fun KtAnalysisSession.findKDoc(symbol: KtSymbol): KDocContent? { val ktElement = symbol.psi as? KtElement ktElement?.findKDoc()?.let { return it } if (symbol is KtCallableSymbol) { symbol.getAllOverriddenSymbols().forEach { overrider -> findKDoc(overrider)?.let { return it } } } return null }
apache-2.0
a8cc7c4ded8084335e16da6a5843467b
40.390323
151
0.640998
5.575837
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownTableSeparatorRow.kt
1
4335
// 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.lang.psi.impl import com.intellij.openapi.util.TextRange import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.psi.util.parents import org.intellij.plugins.markdown.editor.tables.TableProps import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.util.hasType class MarkdownTableSeparatorRow(text: CharSequence): MarkdownLeafPsiElement(MarkdownTokenTypes.TABLE_SEPARATOR, text) { private val cachedCellsRanges get() = CachedValuesManager.getCachedValue(this) { CachedValueProvider.Result.create(buildCellsRanges(), PsiModificationTracker.MODIFICATION_COUNT) } private fun buildCellsRanges(): List<TextRange> { val elementText = text val cells = elementText.split(TableProps.SEPARATOR_CHAR).toMutableList() val startedWithSeparator = cells.firstOrNull()?.isEmpty() == true if (startedWithSeparator) { cells.removeFirst() } val endedWithSeparator = cells.lastOrNull()?.isEmpty() == true if (endedWithSeparator) { cells.removeLast() } if (cells.isEmpty()) { return emptyList() } val elementRange = textRange var left = elementRange.startOffset if (startedWithSeparator) { left += 1 } var right = left + cells.first().length val ranges = mutableListOf<TextRange>() ranges.add(TextRange(left, right)) val cellsSequence = cells.asSequence().drop(1) for (cell in cellsSequence) { left = right + 1 right = left + cell.length ranges.add(TextRange(left, right)) } return ranges } val parentTable: MarkdownTable? get() = parents(withSelf = true).find { it.hasType(MarkdownElementTypes.TABLE) } as? MarkdownTable val cellsRanges: List<TextRange> get() = cachedCellsRanges private val cellsLocalRanges: List<TextRange> get() = cachedCellsRanges.map { it.shiftLeft(startOffset) } val cellsCount: Int get() = cellsRanges.size fun getCellRange(index: Int, local: Boolean = false): TextRange? { return when { local -> cellsLocalRanges.getOrNull(index) else -> cellsRanges.getOrNull(index) } } fun getCellRangeWithPipes(index: Int, local: Boolean = false): TextRange? { val range = getCellRange(index, local) ?: return null val shifted = range.shiftLeft(startOffset) val elementText = text val left = when { elementText.getOrNull(shifted.startOffset - 1) == TableProps.SEPARATOR_CHAR -> range.startOffset - 1 else -> range.startOffset } val right = when { elementText.getOrNull(shifted.endOffset) == TableProps.SEPARATOR_CHAR -> range.endOffset + 1 else -> range.endOffset } return TextRange(left, right) } fun getCellText(index: Int): String? { return getCellRange(index, local = true)?.let { text.substring(it.startOffset, it.endOffset) } } /** * [offset] - offset in document */ fun getColumnIndexFromOffset(offset: Int): Int? { return cellsRanges.indexOfFirst { it.containsOffset(offset) }.takeUnless { it == -1 } } /** * [offset] - offset in document */ fun getCellRangeFromOffset(offset: Int): TextRange? { return getColumnIndexFromOffset(offset)?.let { cellsRanges[it] } } enum class CellAlignment { NONE, LEFT, RIGHT, CENTER } private fun getCellAlignment(range: TextRange): CellAlignment { val cellText = text.subSequence(range.startOffset, range.endOffset) val firstIndex = cellText.indexOfFirst { it == ':' } if (firstIndex == -1) { return CellAlignment.NONE } val secondIndex = cellText.indexOfLast { it == ':' } return when { firstIndex != secondIndex -> CellAlignment.CENTER cellText.subSequence(0, firstIndex).all { it == ' ' } -> CellAlignment.LEFT else -> CellAlignment.RIGHT } } fun getCellAlignment(index: Int): CellAlignment { val range = getCellRange(index, local = true)!! return getCellAlignment(range) } }
apache-2.0
4106c2459cdc0cc73afa24f3e3b300cb
32.867188
158
0.703345
4.455293
false
false
false
false
MichaelEvans/RxBinding
rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/widget/RxProgressBar.kt
1
1954
package com.jakewharton.rxbinding.widget import android.widget.ProgressBar import rx.functions.Action1 /** * An action which increments the progress value of {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun ProgressBar.incrementProgress(): Action1<in Int> = RxProgressBar.incrementProgressBy(this) /** * An action which increments the secondary progress value of {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun ProgressBar.incrementSecondaryProgress(): Action1<in Int> = RxProgressBar.incrementSecondaryProgressBy(this) /** * An action which sets whether {@code view} is indeterminate. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun ProgressBar.indeterminate(): Action1<in Boolean> = RxProgressBar.indeterminate(this) /** * An action which sets the max value of {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun ProgressBar.max(): Action1<in Int> = RxProgressBar.max(this) /** * An action which sets the progress value of {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun ProgressBar.progress(): Action1<in Int> = RxProgressBar.progress(this) /** * An action which sets the secondary progress value of {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ public inline fun ProgressBar.secondaryProgress(): Action1<in Int> = RxProgressBar.secondaryProgress(this)
apache-2.0
d5e2b657c5386001729bfa454b58488e
36.576923
126
0.737462
4.096436
false
false
false
false
vovagrechka/fucking-everything
1/shared-jvm/src/main/java/source-mapping.kt
1
6148
package vgrechka //import com.google.common.cache.CacheBuilder //import com.google.common.cache.CacheLoader //import com.google.common.cache.LoadingCache //import com.google.debugging.sourcemap.* //import java.io.File //val SourceMapping.penetration by AttachedComputedShit<SourceMapping, SourceMapConsumerPenetration> {sourceMapping-> // val penetration = SourceMapConsumerPenetration() // // val privateLines = run { // val f = sourceMapping.javaClass.getDeclaredField("lines") // f.isAccessible = true // f.get(sourceMapping) as List<List<Any>?> // } // val privateSources = run { // val f = sourceMapping.javaClass.getDeclaredField("sources") // f.isAccessible = true // f.get(sourceMapping) as Array<String> // } // // for ((generatedLine, privateLine) in privateLines.withIndex()) { // if (privateLine != null) { // for (privateEntry in privateLine) { // val sourceLine = run { // val m = privateEntry.javaClass.getMethod("getSourceLine") // m.isAccessible = true // m.invoke(privateEntry) as Int // } // val sourceColumn = run { // val m = privateEntry.javaClass.getMethod("getSourceColumn") // m.isAccessible = true // m.invoke(privateEntry) as Int // } // val sourceFileId = run { // val m = privateEntry.javaClass.getMethod("getSourceFileId") // m.isAccessible = true // m.invoke(privateEntry) as Int // } // // val entry = SourceMapConsumerPenetration.DugEntry( // file = privateSources[sourceFileId], // generatedLine = generatedLine + 1, // sourceLine = sourceLine + 1, // sourceColumn = sourceColumn + 1) // // val entries = penetration.generatedLineToDugEntries.getOrPut(generatedLine + 1) {mutableListOf()} // entries += entry // } // } // } // penetration //} // //class SourceMapConsumerPenetration { // val generatedLineToDugEntries = mutableMapOf<Int, MutableList<DugEntry>>() // // class DugEntry(val file: String, // val generatedLine: Int, // val sourceLine: Int, // val sourceColumn: Int) // // val sourceFileLineToGeneratedLine: MutableMap<FileLine, Int> by lazy { // val res = mutableMapOf<FileLine, Int>() // for ((generatedLine, entries) in generatedLineToDugEntries) { // val firstEntry = entries.first() // for (entry in entries) { // if (entry.sourceLine != firstEntry.sourceLine // || entry.file != firstEntry.file // || entry.generatedLine != generatedLine) // wtf("8ea09bef-be33-4a6f-8eb4-5cd2b8502e02") // } // res[FileLine(firstEntry.file, firstEntry.sourceLine)] = generatedLine // } // res // } // // fun dumpSourceLineToGeneratedLine() { // if (sourceFileLineToGeneratedLine.isEmpty()) return clog("Freaking source map is empty") // val entries = sourceFileLineToGeneratedLine.entries.toMutableList() // entries.sortWith(Comparator<Map.Entry<FileLine, Int>> {a, b -> // val c = a.key.file.compareTo(b.key.file) // if (c != 0) // c // else // a.key.line.compareTo(b.key.line) // }) // for ((sourceFileLine, generatedLine) in entries) { // val fullFilePath = true // val fileDesignator = when { // fullFilePath -> sourceFileLine.file // else -> { // val sourceFile = File(sourceFileLine.file) // sourceFile.name // } // } // val source = fileDesignator + ":" + sourceFileLine.line // clog("source = $source; generatedLine = $generatedLine") // } // } //} // //val theSourceMappings = SourceMappings() // //class SourceMappings(val allowInexactMatches: Boolean = true) { // private val cache = CacheBuilder.newBuilder().build(object:CacheLoader<String, SourceMapping>() { // override fun load(mapFilePath: String): SourceMapping { // val text = File(mapFilePath).readText() // return when { // allowInexactMatches -> SourceMapConsumerFactory.parse(text) // else -> parse(text, null) // } // } // }) // // fun getCached(mapFilePath: String): SourceMapping = cache[mapFilePath.replace("\\", "/")] // // private fun parse(contents: String, supplier: SourceMapSupplier?): SourceMapping { // // Version 1, starts with a magic string // if (contents.startsWith("/** Begin line maps. **/")) { // throw SourceMapParseException( // "This appears to be a V1 SourceMap, which is not supported.") // } else if (contents.startsWith("{")) { // val sourceMapObject = SourceMapObjectParser.parse(contents) // // // Check basic assertions about the format. // when (sourceMapObject.version) { // 3 -> { // val consumer = SourceMapConsumerV3Hack() // consumer.allowInexactMatches = allowInexactMatches // consumer.parse(sourceMapObject, supplier) // return consumer // } // else -> throw SourceMapParseException( // "Unknown source map version:" + sourceMapObject.version) // } // } // // throw SourceMapParseException("unable to detect source map format") // } //} // //object DumpSourceMapTool { // @JvmStatic // fun main(args: Array<String>) { // val mapFilePath = args[0] // val mapping = SourceMappings().getCached(mapFilePath) // mapping.penetration.dumpSourceLineToGeneratedLine() // } //}
apache-2.0
acf317d1cc9c647b00e28a26a15006c6
34.744186
117
0.557254
4.382038
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/util/MarkdownPsiStructureUtil.kt
3
7392
package org.intellij.plugins.markdown.util import com.intellij.lang.ASTNode import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import com.intellij.util.Consumer import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownLanguageUtils.isMarkdownLanguage import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownHeader import org.intellij.plugins.markdown.lang.psi.impl.MarkdownList import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItem import org.intellij.plugins.markdown.lang.psi.util.children import org.intellij.plugins.markdown.lang.psi.util.hasType import org.intellij.plugins.markdown.lang.psi.util.parentOfType internal object MarkdownPsiStructureUtil { @JvmField val PRESENTABLE_TYPES: TokenSet = MarkdownTokenTypeSets.HEADERS @JvmField val TRANSPARENT_CONTAINERS = TokenSet.create( MarkdownElementTypes.MARKDOWN_FILE, MarkdownElementTypes.UNORDERED_LIST, MarkdownElementTypes.ORDERED_LIST, MarkdownElementTypes.LIST_ITEM, MarkdownElementTypes.BLOCK_QUOTE ) private val PRESENTABLE_CONTAINERS = TokenSet.create( MarkdownElementTypes.UNORDERED_LIST, MarkdownElementTypes.ORDERED_LIST ) private val IGNORED_CONTAINERS = TokenSet.create(MarkdownElementTypes.BLOCK_QUOTE) private val HEADER_ORDER = arrayOf( TokenSet.create(MarkdownElementTypes.MARKDOWN_FILE_ELEMENT_TYPE), MarkdownTokenTypeSets.HEADER_LEVEL_1_SET, MarkdownTokenTypeSets.HEADER_LEVEL_2_SET, MarkdownTokenTypeSets.HEADER_LEVEL_3_SET, MarkdownTokenTypeSets.HEADER_LEVEL_4_SET, MarkdownTokenTypeSets.HEADER_LEVEL_5_SET, MarkdownTokenTypeSets.HEADER_LEVEL_6_SET ) /** * @return true if element is on the file top level. */ internal fun ASTNode.isTopLevel(): Boolean { return treeParent?.hasType(MarkdownElementTypes.MARKDOWN_FILE) == true } @JvmStatic fun isSimpleNestedList(itemChildren: Array<PsiElement>): Boolean { if (itemChildren.size != 2) { return false } val (firstItem, secondItem) = itemChildren return firstItem.hasType(MarkdownElementTypes.PARAGRAPH) && secondItem is MarkdownList } /* * nextHeaderConsumer 'null' means reaching EOF */ @JvmOverloads @JvmStatic fun processContainer( element: PsiElement?, consumer: Consumer<PsiElement>, nextHeaderConsumer: Consumer<PsiElement?>? = null ) { if (element == null) { return } val structureContainer = when (element) { is MarkdownFile -> findFirstMarkdownChild(element) else -> element.parentOfType(withSelf = true, TRANSPARENT_CONTAINERS) } if (structureContainer == null) { return } val areListsVisible = Registry.`is`("markdown.structure.view.list.visibility") when { element is MarkdownHeader -> processHeader(structureContainer, element, element, consumer, nextHeaderConsumer) element is MarkdownList && areListsVisible -> processList(element, consumer) element is MarkdownListItem && areListsVisible -> { if (!element.hasTrivialChildren()) { processListItem(element, consumer) } } else -> processHeader(structureContainer, null, null, consumer, nextHeaderConsumer) } } private fun findFirstMarkdownChild(element: PsiElement): PsiElement? { return element.children().firstOrNull { it.language.isMarkdownLanguage() } } private fun processHeader( container: PsiElement, sameLevelRestriction: PsiElement?, from: PsiElement?, resultConsumer: Consumer<PsiElement>, nextHeaderConsumer: Consumer<PsiElement?>? ) { val startElement = when (from) { null -> container.firstChild else -> from.nextSibling } var maxContentLevel: PsiElement? = null for (element in startElement?.siblings(forward = true, withSelf = true).orEmpty()) { when { element.isTransparentInPartial() && maxContentLevel == null -> { processHeader(element, null, null, resultConsumer, nextHeaderConsumer) } element.isTransparentInFull() && maxContentLevel == null -> { if (container.elementType !in IGNORED_CONTAINERS && element.elementType in PRESENTABLE_CONTAINERS) { resultConsumer.consume(element) } processHeader(element, null, null, resultConsumer, nextHeaderConsumer) } element is MarkdownHeader -> { if (sameLevelRestriction != null && isSameLevelOrHigher(element, sameLevelRestriction)) { nextHeaderConsumer?.consume(element) return } if (maxContentLevel == null || isSameLevelOrHigher(element, maxContentLevel)) { maxContentLevel = element if (element.elementType in PRESENTABLE_TYPES) { resultConsumer.consume(element) } } } } } nextHeaderConsumer?.consume(null) } private fun processList(list: MarkdownList, resultConsumer: Consumer<in PsiElement>) { for (child in list.children()) { val children = child.children val containerIsFirst = children.firstOrNull()?.elementType in PRESENTABLE_TYPES || children.singleOrNull()?.elementType in PRESENTABLE_CONTAINERS when { containerIsFirst -> resultConsumer.consume(children.first()) isSimpleNestedList(children) -> resultConsumer.consume(children[1]) child is MarkdownListItem -> resultConsumer.consume(child) } } } private fun processListItem(from: MarkdownListItem, resultConsumer: Consumer<in PsiElement>) { for (child in from.children()) { if (child.elementType in PRESENTABLE_TYPES) { resultConsumer.consume(child) break } if (child.elementType in PRESENTABLE_CONTAINERS) { resultConsumer.consume(child) } } } /** * Returns true if the key of the lists representation in the structure is true * and the processed element is a transparent container, but not a list item. * Returns false otherwise. */ private fun PsiElement.isTransparentInFull(): Boolean { if (!Registry.`is`("markdown.structure.view.list.visibility")) { return false } return elementType in TRANSPARENT_CONTAINERS && this !is MarkdownListItem } /** * Returns true if the key of the lists representation in the structure is false (this means that only headers are shown in the structure view) * and the processed element is a transparent container. * Returns false otherwise. */ private fun PsiElement.isTransparentInPartial(): Boolean { return !Registry.`is`("markdown.structure.view.list.visibility") && elementType in TRANSPARENT_CONTAINERS } private fun isSameLevelOrHigher(left: PsiElement, right: PsiElement): Boolean { return obtainHeaderLevel(left.elementType!!) <= obtainHeaderLevel(right.elementType!!) } private fun obtainHeaderLevel(headerType: IElementType): Int { return when (val index = HEADER_ORDER.indexOfFirst { headerType in it }) { -1 -> Int.MAX_VALUE else -> index } } }
apache-2.0
12548cfbc8f818ff59a9706486334ffa
35.96
151
0.718479
4.781371
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/facet.kt
1
2464
// 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.bridgeEntities import com.intellij.workspaceModel.storage.* import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity interface FacetEntity: WorkspaceEntityWithSymbolicId { val name: String val module: ModuleEntity val facetType: String val configurationXmlTag: String? val moduleId: ModuleId // underlyingFacet is a parent facet!! val underlyingFacet: FacetEntity? override val symbolicId: FacetId get() = FacetId(name, facetType, moduleId) //region generated code @GeneratedCodeApiVersion(1) interface Builder : FacetEntity, WorkspaceEntity.Builder<FacetEntity>, ObjBuilder<FacetEntity> { override var entitySource: EntitySource override var name: String override var module: ModuleEntity override var facetType: String override var configurationXmlTag: String? override var moduleId: ModuleId override var underlyingFacet: FacetEntity? } companion object : Type<FacetEntity, Builder>() { operator fun invoke(name: String, facetType: String, moduleId: ModuleId, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FacetEntity { val builder = builder() builder.name = name builder.facetType = facetType builder.moduleId = moduleId builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: FacetEntity, modification: FacetEntity.Builder.() -> Unit) = modifyEntity( FacetEntity.Builder::class.java, entity, modification) var FacetEntity.Builder.childrenFacets: @Child List<FacetEntity> by WorkspaceEntity.extension() var FacetEntity.Builder.facetExternalSystemIdEntity: @Child FacetExternalSystemIdEntity? by WorkspaceEntity.extension() //endregion val FacetEntity.childrenFacets: List<@Child FacetEntity> by WorkspaceEntity.extension()
apache-2.0
7e92a0178f6ad03fb10977637f7af236
35.776119
120
0.743912
5.231423
false
false
false
false
android/compose-samples
Jetcaster/app/src/main/java/com/example/jetcaster/data/Podcast.kt
1
1319
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetcaster.data import androidx.compose.runtime.Immutable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "podcasts", indices = [ Index("uri", unique = true) ] ) @Immutable data class Podcast( @PrimaryKey @ColumnInfo(name = "uri") val uri: String, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "description") val description: String? = null, @ColumnInfo(name = "author") val author: String? = null, @ColumnInfo(name = "image_url") val imageUrl: String? = null, @ColumnInfo(name = "copyright") val copyright: String? = null )
apache-2.0
9e0df5e3923c7bd1fb43590d97d0116f
32.820513
75
0.718726
4.009119
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/tuples.kt
12
3757
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.typing import com.intellij.psi.PsiClassType import com.intellij.psi.PsiType import com.intellij.psi.util.PsiUtil.extractIterableTypeParameter import org.jetbrains.plugins.groovy.config.GroovyConfigUtils import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic private val tupleRegex = "groovy.lang.Tuple(\\d+)".toRegex() /** * @return number or tuple component count of [groovy.lang.Tuple] inheritor type, * or `null` if the [type] doesn't represent an inheritor of [groovy.lang.Tuple] type */ fun getTupleComponentCountOrNull(type: PsiType): Int? { val classType = type as? PsiClassType ?: return null val fqn = classType.resolve()?.qualifiedName ?: return null return tupleRegex.matchEntire(fqn) ?.groupValues ?.getOrNull(1) ?.toIntOrNull() } sealed class MultiAssignmentTypes { abstract fun getComponentType(position: Int): PsiType? } private class FixedMultiAssignmentTypes(val types: List<PsiType>) : MultiAssignmentTypes() { override fun getComponentType(position: Int): PsiType? = types.getOrNull(position) } private class UnboundedMultiAssignmentTypes(private val type: PsiType) : MultiAssignmentTypes() { override fun getComponentType(position: Int): PsiType = type } fun getMultiAssignmentType(rValue: GrExpression, position: Int): PsiType? { return getMultiAssignmentTypes(rValue)?.getComponentType(position) } fun getMultiAssignmentTypes(rValue: GrExpression): MultiAssignmentTypes? { if (isCompileStatic(rValue)) { return getMultiAssignmentTypesCS(rValue) } else { return getLiteralMultiAssignmentTypes(rValue) ?: getTupleMultiAssignmentTypes(rValue) ?: getIterableMultiAssignmentTypes(rValue) } } fun getMultiAssignmentTypesCountCS(rValue: GrExpression): Int? { return getMultiAssignmentTypesCS(rValue)?.types?.size } private fun getMultiAssignmentTypesCS(rValue: GrExpression): FixedMultiAssignmentTypes? { return getLiteralMultiAssignmentTypesCS(rValue) ?: getTupleMultiAssignmentTypesCS(rValue) } private fun getLiteralMultiAssignmentTypesCS(rValue: GrExpression): FixedMultiAssignmentTypes? { if (rValue !is GrListOrMap || rValue.isMap) { return null } return getLiteralMultiAssignmentTypes(rValue) } private fun getLiteralMultiAssignmentTypes(rValue: GrExpression): FixedMultiAssignmentTypes? { val tupleType = rValue.type as? GrTupleType ?: return null return FixedMultiAssignmentTypes(tupleType.componentTypes) } private fun getTupleMultiAssignmentTypesCS(rValue: GrExpression): FixedMultiAssignmentTypes? { if (GroovyConfigUtils.getInstance().getSDKVersion(rValue) < GroovyConfigUtils.GROOVY3_0) { return null } return getTupleMultiAssignmentTypes(rValue) } private fun getTupleMultiAssignmentTypes(rValue: GrExpression): FixedMultiAssignmentTypes? { val classType = rValue.type as? PsiClassType ?: return null val fqn = classType.resolve()?.qualifiedName ?: return null if (!fqn.matches(tupleRegex)) { return null } return FixedMultiAssignmentTypes(classType.parameters.toList()) } private fun getIterableMultiAssignmentTypes(rValue: GrExpression): MultiAssignmentTypes? { val iterableTypeParameter = extractIterableTypeParameter(rValue.type, false) ?: return null return UnboundedMultiAssignmentTypes(iterableTypeParameter) }
apache-2.0
15bee21b8a94da7cf4d442dc4cba8e49
36.949495
140
0.778813
4.798212
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/testFramework/testSrc/com/intellij/testFramework/propertyBased/PsiIndexConsistencyTester.kt
3
7405
/* * 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.intellij.testFramework.propertyBased import com.intellij.lang.Language import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdater import com.intellij.openapi.util.Conditions import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.impl.source.PostprocessReformattingAspect import com.intellij.psi.impl.source.PsiFileImpl import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.CodeInsightTestFixture import com.intellij.util.FileContentUtilCore import org.jetbrains.jetCheck.Generator /** * @author peter */ object PsiIndexConsistencyTester { val commonRefs: List<RefKind> = listOf(RefKind.PsiFileRef, RefKind.DocumentRef, RefKind.DirRef, RefKind.AstRef(null), RefKind.StubRef(null), RefKind.GreenStubRef(null)) fun commonActions(refs: List<RefKind>): Generator<Action> = Generator.frequency( 1, Generator.constant(Action.Gc), 15, Generator.sampledFrom(Action.Commit, Action.ReparseFile, Action.FilePropertiesChanged, Action.ReloadFromDisk, Action.Reformat, Action.PostponedFormatting, Action.RenamePsiFile, Action.RenameVirtualFile, Action.Save), 20, Generator.sampledFrom(refs).flatMap { Generator.sampledFrom(Action.LoadRef(it), Action.ClearRef(it)) }) fun runActions(model: Model, vararg actions: Action) { WriteCommandAction.runWriteCommandAction(model.project) { try { actions.forEach { it.performAction(model) } } finally { try { Action.Save.performAction(model) model.vFile.delete(this) } catch (e: Throwable) { e.printStackTrace() } } } } open class Model(val vFile: VirtualFile, val fixture: CodeInsightTestFixture) { val refs = hashMapOf<RefKind, Any?>() val project = fixture.project!! fun findPsiFile(language: Language? = null) = findViewProvider().let { vp -> vp.getPsi(language ?: vp.baseLanguage) }!! private fun findViewProvider() = PsiManager.getInstance(project).findViewProvider(vFile)!! fun getDocument() = FileDocumentManager.getInstance().getDocument(vFile)!! fun isCommitted(): Boolean { val document = FileDocumentManager.getInstance().getCachedDocument(vFile) return document == null || PsiDocumentManager.getInstance(project).isCommitted(document) } open fun onCommit() {} open fun onReload() {} open fun onSave() {} } interface Action { fun performAction(model: Model) abstract class SimpleAction: Action { override fun toString(): String = javaClass.simpleName } object Gc: SimpleAction() { override fun performAction(model: Model) = PlatformTestUtil.tryGcSoftlyReachableObjects() } object Commit: SimpleAction() { override fun performAction(model: Model) { PsiDocumentManager.getInstance(model.project).commitAllDocuments() model.onCommit() } } object Save: SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) FileDocumentManager.getInstance().saveAllDocuments() model.onSave() } } object PostponedFormatting: SimpleAction() { override fun performAction(model: Model) = PostprocessReformattingAspect.getInstance(model.project).doPostponedFormatting() } object ReparseFile : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) FileContentUtilCore.reparseFiles(model.vFile) model.onSave() } } object FilePropertiesChanged : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) PushedFilePropertiesUpdater.getInstance(model.project).filePropertiesChanged(model.vFile, Conditions.alwaysTrue()) } } object ReloadFromDisk : SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) PsiManager.getInstance(model.project).reloadFromDisk(model.findPsiFile()) model.onReload() if (model.isCommitted()) { model.onCommit() } } } object RenameVirtualFile: SimpleAction() { override fun performAction(model: Model) { model.vFile.rename(this, model.vFile.nameWithoutExtension + "1." + model.vFile.extension) } } object RenamePsiFile: SimpleAction() { override fun performAction(model: Model) { val newName = model.vFile.nameWithoutExtension + "1." + model.vFile.extension model.findPsiFile().name = newName assert(model.findPsiFile().name == newName) assert(model.vFile.name == newName) } } object Reformat: SimpleAction() { override fun performAction(model: Model) { PostponedFormatting.performAction(model) Commit.performAction(model) CodeStyleManager.getInstance(model.project).reformat(model.findPsiFile()) } } data class LoadRef(val kind: RefKind): Action { override fun performAction(model: Model) { model.refs[kind] = kind.loadRef(model) } } data class ClearRef(val kind: RefKind): Action { override fun performAction(model: Model) { model.refs.remove(kind) } } } abstract class RefKind { abstract fun loadRef(model: Model): Any? object PsiFileRef : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile() } object DocumentRef : RefKind() { override fun loadRef(model: Model): Any? = model.getDocument() } object DirRef : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile().containingDirectory } data class AstRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = model.findPsiFile(language).node } data class StubRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = (model.findPsiFile(language) as PsiFileImpl).stubTree } data class GreenStubRef(val language: Language?) : RefKind() { override fun loadRef(model: Model): Any? = (model.findPsiFile(language) as PsiFileImpl).greenStubTree } } }
apache-2.0
314c5bdf22614b60592b3de55938a289
36.21608
123
0.67549
4.817827
false
false
false
false
myunusov/maxur-mserv
maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/LocatorHolder.kt
1
1008
package org.maxur.mserv.frame /** * Holder for Locator. */ interface LocatorHolder { /** * Returns a Locator. * @return the Locator. */ fun get(): LocatorImpl /** * Put the Locator to holder. * @param value The Locator. */ fun put(value: LocatorImpl) /** * Remove The Locator from Holder by it's name. * @param name The name of the Locator. */ fun remove(name: String) } internal class SingleHolder : LocatorHolder { private var locator: LocatorImpl = NullLocator override fun get() = locator override fun put(value: LocatorImpl) { locator = if (locator is NullLocator) value else throw IllegalStateException("You can have only one service locator per microservice") } override fun remove(name: String) { locator = if (locator.name == name) NullLocator else throw IllegalArgumentException("Locator '$name' is not found") } }
apache-2.0
953b16707ac8d5d8f9c801f0d1a8703a
21.4
97
0.605159
4.561086
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/verification/SASVerificationShortCodeFragment.kt
2
7947
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.fragments.verification import android.os.Bundle import android.view.ViewGroup import android.widget.TextView import androidx.core.view.isInvisible import androidx.core.view.isVisible import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import butterknife.BindView import butterknife.OnClick import im.vector.R import im.vector.fragments.VectorBaseFragment import org.matrix.androidsdk.crypto.rest.model.crypto.KeyVerificationStart import org.matrix.androidsdk.crypto.verification.IncomingSASVerificationTransaction import org.matrix.androidsdk.crypto.verification.OutgoingSASVerificationRequest class SASVerificationShortCodeFragment : VectorBaseFragment() { private lateinit var viewModel: SasVerificationViewModel companion object { fun newInstance() = SASVerificationShortCodeFragment() } @BindView(R.id.sas_decimal_code) lateinit var decimalTextView: TextView @BindView(R.id.sas_emoji_description) lateinit var descriptionTextView: TextView @BindView(R.id.sas_emoji_grid) lateinit var emojiGrid: ViewGroup @BindView(R.id.emoji0) lateinit var emoji0View: ViewGroup @BindView(R.id.emoji1) lateinit var emoji1View: ViewGroup @BindView(R.id.emoji2) lateinit var emoji2View: ViewGroup @BindView(R.id.emoji3) lateinit var emoji3View: ViewGroup @BindView(R.id.emoji4) lateinit var emoji4View: ViewGroup @BindView(R.id.emoji5) lateinit var emoji5View: ViewGroup @BindView(R.id.emoji6) lateinit var emoji6View: ViewGroup override fun getLayoutResId() = R.layout.fragment_sas_verification_display_code override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = activity?.run { ViewModelProviders.of(this).get(SasVerificationViewModel::class.java) } ?: throw Exception("Invalid Activity") viewModel.transaction?.let { if (it.supportsEmoji()) { val emojicodes = it.getEmojiCodeRepresentation(it.shortCodeBytes!!) emojicodes.forEachIndexed { index, emojiRepresentation -> when (index) { 0 -> { emoji0View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji0View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 1 -> { emoji1View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji1View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 2 -> { emoji2View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji2View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 3 -> { emoji3View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji3View.findViewById<TextView>(R.id.item_emoji_name_tv)?.setText(emojiRepresentation.nameResId) } 4 -> { emoji4View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji4View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 5 -> { emoji5View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji5View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } 6 -> { emoji6View.findViewById<TextView>(R.id.item_emoji_tv).text = emojiRepresentation.emoji emoji6View.findViewById<TextView>(R.id.item_emoji_name_tv).setText(emojiRepresentation.nameResId) } } } } //decimal is at least supported decimalTextView.text = it.getShortCodeRepresentation(KeyVerificationStart.SAS_MODE_DECIMAL) if (it.supportsEmoji()) { descriptionTextView.text = getString(R.string.sas_emoji_description) decimalTextView.isVisible = false emojiGrid.isVisible = true } else { descriptionTextView.text = getString(R.string.sas_decimal_description) decimalTextView.isVisible = true emojiGrid.isInvisible = true } } viewModel.transactionState.observe(this, Observer { if (viewModel.transaction is IncomingSASVerificationTransaction) { val uxState = (viewModel.transaction as IncomingSASVerificationTransaction).uxState when (uxState) { IncomingSASVerificationTransaction.State.SHOW_SAS -> { viewModel.loadingLiveEvent.value = null } IncomingSASVerificationTransaction.State.VERIFIED -> { viewModel.loadingLiveEvent.value = null viewModel.deviceIsVerified() } IncomingSASVerificationTransaction.State.CANCELLED_BY_ME, IncomingSASVerificationTransaction.State.CANCELLED_BY_OTHER -> { viewModel.loadingLiveEvent.value = null viewModel.navigateCancel() } else -> { viewModel.loadingLiveEvent.value = R.string.sas_waiting_for_partner } } } else if (viewModel.transaction is OutgoingSASVerificationRequest) { val uxState = (viewModel.transaction as OutgoingSASVerificationRequest).uxState when (uxState) { OutgoingSASVerificationRequest.State.SHOW_SAS -> { viewModel.loadingLiveEvent.value = null } OutgoingSASVerificationRequest.State.VERIFIED -> { viewModel.loadingLiveEvent.value = null viewModel.deviceIsVerified() } OutgoingSASVerificationRequest.State.CANCELLED_BY_ME, OutgoingSASVerificationRequest.State.CANCELLED_BY_OTHER -> { viewModel.loadingLiveEvent.value = null viewModel.navigateCancel() } else -> { viewModel.loadingLiveEvent.value = R.string.sas_waiting_for_partner } } } }) } @OnClick(R.id.sas_request_continue_button) fun didAccept() { viewModel.confirmEmojiSame() } @OnClick(R.id.sas_request_cancel_button) fun didCancel() { viewModel.cancelTransaction() } }
apache-2.0
8873e341b49da1f60d6e074cac327f4a
42.195652
126
0.605889
5.276892
false
false
false
false
sksamuel/ktest
kotest-framework/kotest-framework-engine/src/jvmMain/kotlin/io/kotest/engine/launcher/parseLauncherArgs.kt
1
1179
package io.kotest.engine.launcher import io.kotest.engine.cli.parseArgs data class LauncherArgs( // A path to the test to execute. Nested tests will also be executed val testpath: String?, // restricts tests to the package or subpackages val packageName: String?, // the fully qualified name of the spec class which contains the test to execute val spec: String?, // true to force true colour on the terminal; auto to have autodefault val termcolor: String?, // the fully qualified name of a reporter implementation val reporter: String?, // Tag expression to control which tests are executed val tagExpression: String?, // true to output the configuration values when the Engine is created val dumpconfig: Boolean? ) fun parseLauncherArgs(args: List<String>): LauncherArgs { val a = parseArgs(args) return LauncherArgs( testpath = a["testpath"], packageName = a["package"], spec = a["spec"], termcolor = a["termcolor"], // writer is for backwards compatibility reporter = a["reporter"] ?: a["writer"], tagExpression = a["tags"], dumpconfig = a["dumpconfig"]?.toBoolean(), ) }
mit
4bee9f6b6546d1cfca520c308200bc7f
33.676471
83
0.690416
4.334559
false
true
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/discovery/SettingsItemText.kt
2
2808
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.fragments.discovery import android.view.inputmethod.EditorInfo import android.widget.Button import android.widget.EditText import android.widget.TextView import butterknife.BindView import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.EpoxyModelWithHolder import com.google.android.material.textfield.TextInputLayout import im.vector.R import im.vector.ui.epoxy.BaseEpoxyHolder import im.vector.ui.util.setTextOrHide @EpoxyModelClass(layout = R.layout.item_settings_edit_text) abstract class SettingsItemText : EpoxyModelWithHolder<SettingsItemText.Holder>() { @EpoxyAttribute var descriptionText: String? = null @EpoxyAttribute var errorText: String? = null @EpoxyAttribute var interactionListener: Listener? = null override fun bind(holder: Holder) { super.bind(holder) holder.textView.setTextOrHide(descriptionText) holder.validateButton.setOnClickListener { val code = holder.editText.text.toString() holder.editText.text.clear() interactionListener?.onValidate(code) } if (errorText.isNullOrBlank()) { holder.textInputLayout.error = null } else { holder.textInputLayout.error = errorText } holder.editText.setOnEditorActionListener { tv, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { val code = tv.text.toString() interactionListener?.onValidate(code) holder.editText.text.clear() return@setOnEditorActionListener true } return@setOnEditorActionListener false } } class Holder : BaseEpoxyHolder() { @BindView(R.id.settings_item_description) lateinit var textView: TextView @BindView(R.id.settings_item_edittext) lateinit var editText: EditText @BindView(R.id.settings_item_enter_til) lateinit var textInputLayout: TextInputLayout @BindView(R.id.settings_item_enter_button) lateinit var validateButton: Button } interface Listener { fun onValidate(code: String) } }
apache-2.0
28159bcc22496796b4db2990ba036731
32.047059
83
0.69943
4.656716
false
false
false
false
BastiaanOlij/godot
platform/android/java/lib/src/org/godotengine/godot/io/StorageScope.kt
14
4576
/*************************************************************************/ /* StorageScope.kt */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 org.godotengine.godot.io import android.content.Context import android.os.Build import android.os.Environment import java.io.File /** * Represents the different storage scopes. */ internal enum class StorageScope { /** * Covers internal and external directories accessible to the app without restrictions. */ APP, /** * Covers shared directories (from Android 10 and higher). */ SHARED, /** * Everything else.. */ UNKNOWN; class Identifier(context: Context) { private val internalAppDir: String? = context.filesDir.canonicalPath private val internalCacheDir: String? = context.cacheDir.canonicalPath private val externalAppDir: String? = context.getExternalFilesDir(null)?.canonicalPath private val sharedDir : String? = Environment.getExternalStorageDirectory().canonicalPath private val downloadsSharedDir: String? = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).canonicalPath private val documentsSharedDir: String? = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).canonicalPath /** * Determines which [StorageScope] the given path falls under. */ fun identifyStorageScope(path: String?): StorageScope { if (path == null) { return UNKNOWN } val pathFile = File(path) if (!pathFile.isAbsolute) { return UNKNOWN } val canonicalPathFile = pathFile.canonicalPath if (internalAppDir != null && canonicalPathFile.startsWith(internalAppDir)) { return APP } if (internalCacheDir != null && canonicalPathFile.startsWith(internalCacheDir)) { return APP } if (externalAppDir != null && canonicalPathFile.startsWith(externalAppDir)) { return APP } if (sharedDir != null && canonicalPathFile.startsWith(sharedDir)) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { // Before R, apps had access to shared storage so long as they have the right // permissions (and flag on Q). return APP } // Post R, access is limited based on the target destination // 'Downloads' and 'Documents' are still accessible if ((downloadsSharedDir != null && canonicalPathFile.startsWith(downloadsSharedDir)) || (documentsSharedDir != null && canonicalPathFile.startsWith(documentsSharedDir))) { return APP } return SHARED } return UNKNOWN } } }
mit
259305e192e5b1689c4747c4c35da2fc
39.495575
136
0.590691
5.107143
false
false
false
false
seventhroot/elysium
bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/warn/WarningListCommand.kt
1
3175
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.moderation.bukkit.command.warn import com.rpkit.moderation.bukkit.RPKModerationBukkit import com.rpkit.moderation.bukkit.warning.RPKWarningProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.players.bukkit.profile.RPKProfile import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player import java.time.format.DateTimeFormatter class WarningListCommand(private val plugin: RPKModerationBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.moderation.command.warning.list")) { sender.sendMessage(plugin.messages["no-permission-warning-list"]) return true } var player: Player? = null if (sender is Player) { player = sender } if (args.isNotEmpty()) { val argPlayer = plugin.server.getPlayer(args[0]) if (argPlayer != null) { player = argPlayer } } if (player == null) { sender.sendMessage(plugin.messages["not-from-console"]) return true } val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val warningProvider = plugin.core.serviceManager.getServiceProvider(RPKWarningProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(player) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val profile = minecraftProfile.profile if (profile !is RPKProfile) { sender.sendMessage(plugin.messages["no-profile"]) return true } val warnings = warningProvider.getWarnings(profile) sender.sendMessage(plugin.messages["warning-list-title"]) for ((index, warning) in warnings.withIndex()) { sender.sendMessage(plugin.messages["warning-list-item", mapOf( Pair("issuer", warning.issuer.name), Pair("profile", warning.profile.name), Pair("index", (index + 1).toString()), Pair("reason", warning.reason), Pair("time", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(warning.time)) )]) } return true } }
apache-2.0
761ae609bbaa803f044cc8de7b1fbacb
40.776316
120
0.668346
4.745889
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/graphql/service/GraphQLStructureMutator.kt
1
4014
package org.evomaster.core.problem.graphql.service import com.google.inject.Inject import org.evomaster.core.Lazy import org.evomaster.core.database.SqlInsertBuilder import org.evomaster.core.problem.enterprise.EnterpriseActionGroup import org.evomaster.core.problem.graphql.GraphQLAction import org.evomaster.core.problem.graphql.GraphQLIndividual import org.evomaster.core.problem.api.service.ApiWsStructureMutator import org.evomaster.core.problem.rest.SampleType import org.evomaster.core.search.EvaluatedIndividual import org.evomaster.core.search.Individual import org.evomaster.core.search.service.mutator.MutatedGeneSpecification import org.slf4j.Logger import org.slf4j.LoggerFactory /* TODO: here there is quite bit of code that is similar to REST. Once this is stable, should refactoring to avoid duplication */ class GraphQLStructureMutator : ApiWsStructureMutator() { companion object{ private val log: Logger = LoggerFactory.getLogger(GraphQLStructureMutator::class.java) } @Inject private lateinit var sampler: GraphQLSampler override fun mutateStructure(individual: Individual, evaluatedIndividual: EvaluatedIndividual<*>, mutatedGenes: MutatedGeneSpecification?, targets: Set<Int>) { if (individual !is GraphQLIndividual) { throw IllegalArgumentException("Invalid individual type") } if (!individual.canMutateStructure()) { return // nothing to do } when (individual.sampleType) { SampleType.RANDOM -> mutateForRandomType(individual, mutatedGenes) //TODO other kinds //this would be a bug else -> throw IllegalStateException("Cannot handle sample type ${individual.sampleType}") } if (config.trackingEnabled()) tag(individual, time.evaluatedIndividuals) } override fun addInitializingActions(individual: EvaluatedIndividual<*>, mutatedGenes: MutatedGeneSpecification?) { addInitializingActions(individual, mutatedGenes, sampler) } private fun mutateForRandomType(ind: GraphQLIndividual, mutatedGenes: MutatedGeneSpecification?) { val main = ind.seeMainActionComponents() as List<EnterpriseActionGroup> if (main.size == 1) { val sampledAction = sampler.sampleRandomAction(0.05) as GraphQLAction ind.addGQLAction(action= sampledAction) Lazy.assert { sampledAction.hasLocalId() } //save mutated genes mutatedGenes?.addRemovedOrAddedByAction(sampledAction, ind.seeAllActions().size, localId = sampledAction.getLocalId(), false, ind.seeAllActions().size) return } if (randomness.nextBoolean() || main.size == config.maxTestSize) { //delete one at random log.trace("Deleting action from test") val chosen = randomness.choose(main.indices) //save mutated genes val removedActions = main[chosen].flatten() for(a in removedActions) { /* FIXME: how does position work when adding/removing a subtree? */ mutatedGenes?.addRemovedOrAddedByAction(a, chosen, localId = main[chosen].getLocalId(),true, chosen) } ind.removeGQLActionAt(chosen) } else { //add one at random log.trace("Adding action to test") val sampledAction = sampler.sampleRandomAction(0.05) as GraphQLAction val chosen = randomness.choose(main.indices) ind.addGQLAction(chosen, sampledAction) Lazy.assert { sampledAction.hasLocalId() } //save mutated genes mutatedGenes?.addRemovedOrAddedByAction(sampledAction, chosen, localId = sampledAction.getLocalId(), false, chosen) } } override fun getSqlInsertBuilder(): SqlInsertBuilder? { return sampler.sqlInsertBuilder } }
lgpl-3.0
af2adb4a5bc813a0675076523eb92336
33.913043
163
0.677628
5.093909
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/server/infrastructure/DatabaseMessagesRepository.kt
2
3164
package chat.rocket.android.server.infrastructure import chat.rocket.android.db.DatabaseManager import chat.rocket.android.db.Operation import chat.rocket.android.db.model.MessagesSync import chat.rocket.android.server.domain.MessagesRepository import chat.rocket.android.util.retryDB import chat.rocket.core.model.Message import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class DatabaseMessagesRepository( private val dbManager: DatabaseManager, private val mapper: DatabaseMessageMapper ) : MessagesRepository { override suspend fun getById(id: String): Message? = withContext(Dispatchers.IO) { retryDB("getMessageById($id)") { dbManager.messageDao().getMessageById(id)?.let { message -> mapper.map(message) } } } override suspend fun getByRoomId(roomId: String): List<Message> = withContext(Dispatchers.IO) { // FIXME - investigate how to avoid this distinctBy here, since DAO is returning a lot of // duplicate rows (something related to our JOINS and relations on Room) retryDB("getMessagesByRoomId($roomId)") { dbManager.messageDao().getMessagesByRoomId(roomId) .distinctBy { it.message.message.id } .let { messages -> mapper.map(messages) } } } override suspend fun getRecentMessages(roomId: String, count: Long): List<Message> = withContext(Dispatchers.IO) { retryDB("getRecentMessagesByRoomId($roomId, $count)") { dbManager.messageDao().getRecentMessagesByRoomId(roomId, count) .distinctBy { it.message.message.id } .let { messages -> mapper.map(messages) } } } override suspend fun save(message: Message) { dbManager.processMessagesBatch(listOf(message)).join() } override suspend fun saveAll(newMessages: List<Message>) { dbManager.processMessagesBatch(newMessages).join() } override suspend fun removeById(id: String) { withContext(Dispatchers.IO) { retryDB("delete($id)") { dbManager.messageDao().delete(id) } } } override suspend fun removeByRoomId(roomId: String) { withContext(Dispatchers.IO) { retryDB("deleteByRoomId($roomId)") { dbManager.messageDao().deleteByRoomId(roomId) } } } override suspend fun getAllUnsent(): List<Message> = withContext(Dispatchers.IO) { retryDB("getUnsentMessages") { dbManager.messageDao().getUnsentMessages() .distinctBy { it.message.message.id } .let { mapper.map(it) } } } override suspend fun saveLastSyncDate(roomId: String, timeMillis: Long) { dbManager.sendOperation(Operation.SaveLastSync(MessagesSync(roomId, timeMillis))) } override suspend fun getLastSyncDate(roomId: String): Long? = withContext(Dispatchers.IO) { retryDB("getLastSync($roomId)") { dbManager.messageDao().getLastSync(roomId)?.timestamp } } }
mit
ab14cd100518f8ad7d3a1026122560cd
36.235294
99
0.645702
4.779456
false
false
false
false
hzsweers/palettehelper
palettehelper/src/main/java/io/sweers/palettehelper/util/Analytics.kt
1
978
package io.sweers.palettehelper.util import com.mixpanel.android.mpmetrics.MixpanelAPI import org.json.JSONObject val ANALYTICS_NAV_SOURCE = "Navigation Source" val ANALYTICS_NAV_ENTER = "Navigation Enter Event" val ANALYTICS_NAV_DESTINATION = "Navigation Destination" val ANALYTICS_NAV_MAIN = "Main Activity" val ANALYTICS_NAV_DETAIL = "Detail Activity" val ANALYTICS_NAV_SHARE = "External Share" val ANALYTICS_NAV_INTERNAL = "Internal storage" val ANALYTICS_NAV_CAMERA = "Camera" val ANALYTICS_NAV_URL = "Image URL" val ANALYTICS_KEY_NUMCOLORS = "Number of colors" val ANALYTICS_KEY_PLAY_REFERRER = "Google Play install referrer" public fun MixpanelAPI.trackNav(src: String, dest: String) { val props: JSONObject = JSONObject() .put(ANALYTICS_NAV_SOURCE, src) .put(ANALYTICS_NAV_DESTINATION, dest) track("Navigation", props) } public fun MixpanelAPI.trackMisc(key: String, value: String) { track("Misc", JSONObject().put(key, value)) }
apache-2.0
b32d16ecbb2e733212c1a37c0e11b407
35.222222
64
0.747444
3.704545
false
false
false
false
fython/shadowsocks-android
mobile/src/main/java/com/github/shadowsocks/ScannerActivity.kt
2
7083
/******************************************************************************* * * * Copyright (C) 2017 by Max Lv <[email protected]> * * Copyright (C) 2017 by Mygod Studio <[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.github.shadowsocks import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.ShortcutManager import android.graphics.BitmapFactory import android.hardware.camera2.CameraAccessException import android.hardware.camera2.CameraManager import android.os.Build import android.os.Bundle import android.support.v4.app.TaskStackBuilder import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.util.Log import android.util.SparseArray import android.view.MenuItem import android.widget.Toast import com.github.shadowsocks.App.Companion.app import com.github.shadowsocks.database.Profile import com.github.shadowsocks.database.ProfileManager import com.github.shadowsocks.utils.resolveResourceId import com.google.android.gms.samples.vision.barcodereader.BarcodeCapture import com.google.android.gms.samples.vision.barcodereader.BarcodeGraphic import com.google.android.gms.vision.Frame import com.google.android.gms.vision.barcode.Barcode import com.google.android.gms.vision.barcode.BarcodeDetector import xyz.belvi.mobilevisionbarcodescanner.BarcodeRetriever class ScannerActivity : AppCompatActivity(), Toolbar.OnMenuItemClickListener, BarcodeRetriever { companion object { private const val TAG = "ScannerActivity" private const val REQUEST_IMPORT = 2 private const val REQUEST_IMPORT_OR_FINISH = 3 } private fun navigateUp() { val intent = parentActivityIntent if (shouldUpRecreateTask(intent) || isTaskRoot) TaskStackBuilder.create(this).addNextIntentWithParentStack(intent).startActivities() else finish() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT >= 25) getSystemService(ShortcutManager::class.java).reportShortcutUsed("scan") if (try { (getSystemService(Context.CAMERA_SERVICE) as CameraManager).cameraIdList.isEmpty() } catch (_: CameraAccessException) { true }) { startImport() return } setContentView(R.layout.layout_scanner) val toolbar = findViewById<Toolbar>(R.id.toolbar) toolbar.title = title toolbar.setNavigationIcon(theme.resolveResourceId(R.attr.homeAsUpIndicator)) toolbar.setNavigationOnClickListener { navigateUp() } toolbar.inflateMenu(R.menu.scanner_menu) toolbar.setOnMenuItemClickListener(this) (supportFragmentManager.findFragmentById(R.id.barcode) as BarcodeCapture).setRetrieval(this) } override fun onRetrieved(barcode: Barcode) = runOnUiThread { Profile.findAll(barcode.rawValue).forEach { ProfileManager.createProfile(it) } navigateUp() } override fun onRetrievedMultiple(closetToClick: Barcode?, barcode: MutableList<BarcodeGraphic>?) = check(false) override fun onBitmapScanned(sparseArray: SparseArray<Barcode>?) { } override fun onRetrievedFailed(reason: String?) { Log.w(TAG, reason) } override fun onPermissionRequestDenied() { Toast.makeText(this, R.string.add_profile_scanner_permission_required, Toast.LENGTH_SHORT).show() startImport() } override fun onMenuItemClick(item: MenuItem) = when (item.itemId) { R.id.action_import -> { startImport(true) true } else -> false } private fun startImport(manual: Boolean = false) = startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT) .addCategory(Intent.CATEGORY_OPENABLE) .setType("image/*") .putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true), if (manual) REQUEST_IMPORT else REQUEST_IMPORT_OR_FINISH) override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_IMPORT, REQUEST_IMPORT_OR_FINISH -> if (resultCode == Activity.RESULT_OK) { var success = false val detector = BarcodeDetector.Builder(this) .setBarcodeFormats(Barcode.QR_CODE) .build() if (detector.isOperational) { var list = listOfNotNull(data?.data) val clipData = data?.clipData if (clipData != null) list += (0 until clipData.itemCount).map { clipData.getItemAt(it).uri } val resolver = contentResolver for (uri in list) try { val barcodes = detector.detect(Frame.Builder() .setBitmap(BitmapFactory.decodeStream(resolver.openInputStream(uri))).build()) for (i in 0 until barcodes.size()) Profile.findAll(barcodes.valueAt(i).rawValue).forEach { ProfileManager.createProfile(it) success = true } } catch (e: Exception) { app.track(e) } } else Log.w(TAG, "Google vision isn't operational.") Toast.makeText(this, if (success) R.string.action_import_msg else R.string.action_import_err, Toast.LENGTH_SHORT).show() navigateUp() } else if (requestCode == REQUEST_IMPORT_OR_FINISH) navigateUp() else -> super.onActivityResult(requestCode, resultCode, data) } } }
gpl-3.0
58ba94da273967d8e8d8da742ceff71f
49.234043
115
0.599887
5.066524
false
false
false
false
googlecodelabs/android-compose-codelabs
NavigationCodelab/app/src/main/java/com/example/compose/rally/ui/components/CommonUi.kt
1
5541
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.compose.rally.ui.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.ContentAlpha import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.LocalContentAlpha import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.unit.dp import com.example.compose.rally.R import java.text.DecimalFormat /** * A row representing the basic information of an Account. */ @Composable fun AccountRow( modifier: Modifier = Modifier, name: String, number: Int, amount: Float, color: Color ) { BaseRow( modifier = modifier, color = color, title = name, subtitle = stringResource(R.string.account_redacted) + AccountDecimalFormat.format(number), amount = amount, negative = false ) } /** * A row representing the basic information of a Bill. */ @Composable fun BillRow(name: String, due: String, amount: Float, color: Color) { BaseRow( color = color, title = name, subtitle = "Due $due", amount = amount, negative = true ) } @Composable private fun BaseRow( modifier: Modifier = Modifier, color: Color, title: String, subtitle: String, amount: Float, negative: Boolean ) { val dollarSign = if (negative) "–$ " else "$ " val formattedAmount = formatAmount(amount) Row( modifier = modifier .height(68.dp) .clearAndSetSemantics { contentDescription = "$title account ending in ${subtitle.takeLast(4)}, current balance $dollarSign$formattedAmount" }, verticalAlignment = Alignment.CenterVertically ) { val typography = MaterialTheme.typography AccountIndicator( color = color, modifier = Modifier ) Spacer(Modifier.width(12.dp)) Column(Modifier) { Text(text = title, style = typography.body1) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text(text = subtitle, style = typography.subtitle1) } } Spacer(Modifier.weight(1f)) Row( horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = dollarSign, style = typography.h6, modifier = Modifier.align(Alignment.CenterVertically) ) Text( text = formattedAmount, style = typography.h6, modifier = Modifier.align(Alignment.CenterVertically) ) } Spacer(Modifier.width(16.dp)) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Icon( imageVector = Icons.Filled.ChevronRight, contentDescription = null, modifier = Modifier .padding(end = 12.dp) .size(24.dp) ) } } RallyDivider() } /** * A vertical colored line that is used in a [BaseRow] to differentiate accounts. */ @Composable private fun AccountIndicator(color: Color, modifier: Modifier = Modifier) { Spacer( modifier .size(4.dp, 36.dp) .background(color = color) ) } @Composable fun RallyDivider(modifier: Modifier = Modifier) { Divider(color = MaterialTheme.colors.background, thickness = 1.dp, modifier = modifier) } fun formatAmount(amount: Float): String { return AmountDecimalFormat.format(amount) } private val AccountDecimalFormat = DecimalFormat("####") private val AmountDecimalFormat = DecimalFormat("#,###.##") /** * Used with accounts and bills to create the animated circle. */ fun <E> List<E>.extractProportions(selector: (E) -> Float): List<Float> { val total = this.sumOf { selector(it).toDouble() } return this.map { (selector(it) / total).toFloat() } }
apache-2.0
f92fa420dc093aea0cb4d29cd623c565
30.651429
115
0.673948
4.529027
false
false
false
false
FantAsylum/Floor--13
core/src/com/floor13/game/actors/MapActor.kt
1
1849
package com.floor13.game.actors import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.graphics.g2d.Batch import com.floor13.game.FloorMinus13 import com.floor13.game.core.map.Map import com.floor13.game.core.map.Door import com.floor13.game.util.SidedTextureResolver import com.floor13.game.texture import com.floor13.game.TILE_SIZE class MapActor(val map: Map): BaseActor() { // TODO: pick atlas basing on theme (bunker (1-4 lvl), lab (5-8) etc.) val textureResolver = SidedTextureResolver( FloorMinus13.getAtlas("graphics/terrain/level1/atlas.atlas"), map) val fogOfWarResolver = SidedTextureResolver( FloorMinus13.getAtlas("graphics/fow/atlas.atlas"), map.width, map.height, { x1, y1, x2, y2 -> map.isExplored(x1, y1) == map.isExplored(x2, y2) // TODO: handle also invisibilty fog of war } ) init { setBounds( 0f, 0f, map.width * TILE_SIZE, map.height * TILE_SIZE ) } override fun draw(batch: Batch, parentAlpha: Float) { for (x in 0 until map.width) { for (y in 0 until map.height) { val tile = map[x, y] batch.draw( textureResolver.getTexture(tile.texture, x, y), x * TILE_SIZE, y * TILE_SIZE ) if (!map.isExplored(x, y)) batch.draw( fogOfWarResolver.getTexture(UNEXPLORED_TEXTURE_NAME, x, y), x * TILE_SIZE, y * TILE_SIZE ) // TODO: handle also insibility fog of war // TODO: drawing creature (if present) // TODO: drawing items (if present) } } } companion object { val UNEXPLORED_TEXTURE_NAME = "unexplored" } }
mit
bb1d9069d62d04d5ab513e19eb9349ad
25.414286
74
0.57815
3.436803
false
false
false
false
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/extensions/PopupMenuHelper.kt
1
7228
package tech.summerly.quiet.extensions import android.content.Context import android.support.v7.widget.PopupMenu import android.view.View import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.launch import org.jetbrains.anko.alert import org.jetbrains.anko.noButton import org.jetbrains.anko.toast import org.jetbrains.anko.yesButton import tech.summerly.quiet.R import tech.summerly.quiet.bean.Playlist import tech.summerly.quiet.data.local.LocalMusicApi import tech.summerly.quiet.module.common.bean.Music import tech.summerly.quiet.module.common.bean.MusicType import tech.summerly.quiet.module.common.utils.inputDialog import tech.summerly.quiet.module.playlistdetail.PlaylistDetailActivity import tech.summerly.quiet.ui.widget.PlaylistSelectorBottomSheet /** * author : SUMMERLY * e-mail : [email protected] * time : 2017/8/20 * desc : */ class PopupMenuHelper(private val context: Context) { /** * 获取音乐的弹出按钮 * TODO */ fun getMusicPopupMenu(target: View, music: Music): PopupMenu { val popupMenu = PopupMenu(context, target) popupMenu.inflate(R.menu.popup_menu_music) val defaultMusicHandler = when (music.type) { MusicType.LOCAL -> LocalMusicHandler(context, music) MusicType.NETEASE -> TODO() MusicType.NETEASE_FM -> TODO() } popupMenu.setOnMenuItemClickListener { when (it.itemId) { R.id.menu_music_add_to_next -> { //TODO } R.id.menu_music_add_to_tag -> defaultMusicHandler.addToPlaylist() R.id.menu_music_to_album -> defaultMusicHandler.navToAlbum() R.id.menu_music_delete -> { context .alert(string(R.string.alert_message_delete_music, music.title)) { yesButton { Single .create<String> { val delete = music.deleteAction val isSuccess = delete?.invoke() if (isSuccess == true) { it.onSuccess(string(R.string.toast_delete_music_success, music.title)) } else { it.onError(Exception(string(R.string.toast_delete_music_failed, music.title))) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ message -> context.toast(message) }, { exception -> exception.message?.let { context.toast(it) } }) } noButton { //do nothing } }.show() } } true } return popupMenu } fun getPlaylistItemPopupMenu(target: View, playlist: Playlist): PopupMenu { val popupMenu = PopupMenu(context, target) popupMenu.inflate(R.menu.popup_playlist_item) popupMenu.setOnMenuItemClickListener { when (it.itemId) { R.id.popup_playlist_remove -> { context.alert { title = ("删除歌单 ${playlist.name}") yesButton { launch { LocalMusicApi.removePlaylist(playlist) launch(UI) { it.dismiss() } } log { "删除 ---> ${playlist.id}" } } }.show() } R.id.popup_playlist_rename -> { context .inputDialog("重命名", "名字", "命名", "取消") { dialog, textInputLayout -> val text = textInputLayout.editText?.text?.toString()?.trim() if (text.isNullOrBlank()) { textInputLayout.error = "不能为空" } else { launch { LocalMusicApi.updatePlaylist(playlist.copy(name = text!!)) launch(UI) { dialog.dismiss() } } } log { "text = $text" } } .show() } } true } return popupMenu } interface MusicHandler { val context: Context val music: Music fun addToPlaylist() fun navToAlbum() @Deprecated("") fun delete() } class LocalMusicHandler(override val context: Context, override val music: Music) : MusicHandler { override fun addToPlaylist() { PlaylistSelectorBottomSheet(context) { selector, playlist -> launch { LocalMusicApi.addToPlaylist(music, playlist = playlist) launch(UI) { [email protected](string(R.string.toast_add_to_tag_success)) selector.dismiss() } } }.show() } override fun navToAlbum() { PlaylistDetailActivity.startForLocalAlbum(context, music.album.name) } override fun delete() { context.alert(string(R.string.alert_message_delete_music, music.title)) { yesButton { log("正在删除本地音乐 : $music ") if (music.delete()) { context.toast(string(R.string.toast_delete_music_success, music.title)) } else { context.toast(string(R.string.toast_delete_music_failed, music.title)) log("删除失败") } } noButton { //do nothing } }.show() } } }
gpl-2.0
11fd06671b83d6ba42aaff5fc2706a8a
38.065574
130
0.436766
5.844644
false
false
false
false
nickthecoder/tickle
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/loop/FullSpeedGameLoop.kt
1
3525
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.loop import uk.co.nickthecoder.tickle.Game import uk.co.nickthecoder.tickle.graphics.Window import uk.co.nickthecoder.tickle.physics.TickleWorld /** * This is the default implementation of [GameLoop]. * * Note. This implementation call tick on Producer, Director, all StageViews, and all Stage (and therefore all Roles) * every frame. There is no attempt to keep a constant frame rate. * Therefore under heavy load, the time between two ticks can vary, and there is no mechanism to even out these * steps to prevent objects moving at different speeds depending on the load. * * If your games uses physics (JBox2d), then TickleWorld ensures that the time step is consistent. * i.e. objects WILL move at a constant speed, regardless of load. (at the expense of potential stuttering). * * Runs as quickly as possible. It will be capped to the screen's refresh rate if using v-sync. * See [Window.enableVSync]. */ class FullSpeedGameLoop(game: Game) : AbstractGameLoop(game) { override fun sceneStarted() { resetStats() game.scene.stages.values.forEach { stage -> stage.world?.resetAccumulator() } } override fun tick() { tickCount++ with(game) { producer.preTick() director.preTick() producer.tick() director.tick() if (!game.paused) { game.scene.views.values.forEach { it.tick() } game.scene.stages.values.forEach { it.tick() } // Call tick on all TickleWorlds // Each stage can have its own TickleWorld. However, in the most common case, there is only // one tickle world shared by all stages. Given the way that TickleWorld keeps a constant // time step, we COULD just call tick on every stage's TickleWorld without affecting the game. // However, debugging information may be misleading, as the first stage will cause a step, and // the subsequent stages will skip (because the accumulator is near zero). // So, this code ticks all Stages' worlds, but doesn't bother doing it twice for the same world. var world: TickleWorld? = null game.scene.stages.values.forEach { stage -> val stageWorld = stage.world if (stageWorld != null) { if (stageWorld != world) { world = stageWorld stageWorld.tick() } } } } director.postTick() producer.postTick() mouseMoveTick() processRunLater() } game.scene.draw(game.renderer) game.window.swap() } }
gpl-3.0
12536c8b0a44bc40e98425d63c4c2419
36.105263
117
0.636596
4.577922
false
false
false
false
SoulBeaver/SpriteSheetProcessor
src/main/java/com/sbg/rpg/javafx/SpriteSheetProcessorController.kt
1
2964
/* * Copyright 2016 Christian Broomfield * * 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.sbg.rpg.javafx import com.sbg.rpg.javafx.model.AnnotatedSpriteSheet import com.sbg.rpg.packing.common.SpriteCutter import com.sbg.rpg.packing.common.SpriteDrawer import com.sbg.rpg.packing.common.extensions.filenameWithoutExtension import com.sbg.rpg.packing.common.extensions.pmap import com.sbg.rpg.packing.common.extensions.readImage import com.sbg.rpg.packing.unpacker.SpriteSheetUnpacker import org.apache.logging.log4j.LogManager import tornadofx.Controller import java.io.File import java.nio.file.Path import java.nio.file.Paths import javax.imageio.ImageIO class SpriteSheetProcessorController : Controller() { private val logger = LogManager.getLogger(SpriteSheetProcessorController::class.simpleName) private val view: SpriteSheetProcessorView by inject() private val spriteSheetUnpacker: SpriteSheetUnpacker = SpriteSheetUnpacker(SpriteCutter(SpriteDrawer())) private var spriteSheetPaths: List<Path> = emptyList() fun unpackSpriteSheets(spriteSheetFiles: List<File>): List<AnnotatedSpriteSheet> { logger.debug("Loading files $spriteSheetFiles") this.spriteSheetPaths = spriteSheetFiles.map { Paths.get(it.absolutePath) } return spriteSheetPaths.pmap { spriteSheetPath -> logger.debug("Unpacking ${spriteSheetPath.fileName}") val spriteSheet = spriteSheetPath.readImage() val spriteBoundsList = spriteSheetUnpacker.discoverSprites(spriteSheet) AnnotatedSpriteSheet( spriteSheet, spriteBoundsList ) } } fun saveSprites(directory: File) { val spritesPerFile = spriteSheetPaths.pmap { spriteSheetPath -> spriteSheetPath.fileName to spriteSheetUnpacker.unpack(spriteSheetPath.readImage()) } logger.debug("Writing individual sprites to file.") for ((fileName, sprites) in spritesPerFile) { val fileNameWithoutExtension = fileName.filenameWithoutExtension() sprites.forEachIndexed { idx, sprite -> ImageIO.write( sprite, "png", Paths.get(directory.absolutePath, "${fileNameWithoutExtension}_$idx.png").toFile()) } } logger.debug("Finished writing sprites to file.") } }
apache-2.0
0054bf8d093400962635d895c7d5e99b
37
108
0.705466
4.712242
false
false
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/SettingsActivity.kt
1
4050
package fr.geobert.efficio import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.preference.PreferenceFragment import android.support.design.widget.Snackbar import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.view.View import fr.geobert.efficio.db.DbHelper import fr.geobert.efficio.dialog.FileChooserDialog import fr.geobert.efficio.dialog.FileChooserDialogListener import fr.geobert.efficio.dialog.MessageDialog import fr.geobert.efficio.misc.MY_PERM_REQUEST_WRITE_EXT_STORAGE import fr.geobert.efficio.misc.OnRefreshReceiver import kotlinx.android.synthetic.main.item_editor.* import kotlinx.android.synthetic.main.settings_activity.* class SettingsActivity : BaseActivity(), FileChooserDialogListener { companion object { fun callMe(ctx: Context) { val i = Intent(ctx, SettingsActivity::class.java) ctx.startActivity(i) } } class SettingsFragment : PreferenceFragment(), FileChooserDialogListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.settings) } override fun onFileChosen(name: String) { (activity as FileChooserDialogListener).onFileChosen(name) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.settings_activity) setSpinnerVisibility(View.GONE) setTitle(R.string.settings) setIcon(R.mipmap.ic_action_arrow_left) setIconOnClick(View.OnClickListener { onBackPressed() }) if (savedInstanceState == null) { fragmentManager.beginTransaction().replace(R.id.flContent, SettingsFragment(), "settings").commit() } backup_db_btn.setOnClickListener { askPermAndBackupDatabase() } restore_db_btn.setOnClickListener { chooseFileToRestore() } } private fun chooseFileToRestore() { val f = FileChooserDialog.newInstance("/Efficio") f.setTargetFragment(fragmentManager.findFragmentByTag("settings"), 0) f.show(fragmentManager, "FileChooser") } override fun onFileChosen(name: String) { val msg = if (DbHelper.restoreDatabase(this, name)) { val i = Intent(OnRefreshReceiver.REFRESH_ACTION) sendBroadcast(i) R.string.restore_database_done } else R.string.restore_database_fail Snackbar.make(my_toolbar, msg, Snackbar.LENGTH_LONG).show() } private fun askPermAndBackupDatabase() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), MY_PERM_REQUEST_WRITE_EXT_STORAGE) } else { doBackup() } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { MY_PERM_REQUEST_WRITE_EXT_STORAGE -> { if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) { doBackup() } else { MessageDialog.newInstance(R.string.permission_write_required, R.string.permission_required_title) .show(fragmentManager, "PermAsk") } } } } private fun doBackup() { val name = DbHelper.backupDb() val msg = if (name != null) getString(R.string.backup_database_done).format(name) else getString(R.string.backup_database_fail) Snackbar.make(my_toolbar, msg, Snackbar.LENGTH_LONG).show() } }
gpl-2.0
5a393079e2bcc59eaf394347b0354c92
34.526316
119
0.66642
4.764706
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/platform/discord/legacy/entities/jda/JDAUser.kt
1
1660
package net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.jda import com.fasterxml.jackson.annotation.JsonIgnore import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.DiscordUser import net.perfectdreams.loritta.morenitta.utils.ImageFormat import net.perfectdreams.loritta.morenitta.utils.extensions.getEffectiveAvatarUrl open class JDAUser(@JsonIgnore val handle: net.dv8tion.jda.api.entities.User) : DiscordUser { override val id: Long get() = handle.idLong override val name: String get() = handle.name override val avatar: String? get() = handle.avatarId override val avatarUrl: String? get() = handle.effectiveAvatarUrl override val asMention: String get() = handle.asMention override val isBot: Boolean get() = handle.isBot /** * Gets the effective avatar URL in the specified [format] * * @see getEffectiveAvatarUrl */ fun getEffectiveAvatarUrl(format: ImageFormat) = getEffectiveAvatarUrl(format, 128) /** * Gets the effective avatar URL in the specified [format] and [ímageSize] * * @see getEffectiveAvatarUrlInFormat */ fun getEffectiveAvatarUrl(format: ImageFormat, imageSize: Int): String { val extension = format.extension return if (avatar != null) { "https://cdn.discordapp.com/avatars/$id/$avatar.${extension}?size=$imageSize" } else { val avatarId = id % 5 // This only exists in png AND doesn't have any other sizes "https://cdn.discordapp.com/embed/avatars/$avatarId.png" } } }
agpl-3.0
0721ff1a75988bb4fcf7d16dff445fc4
32.2
93
0.683544
4.595568
false
false
false
false
signed/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/compile/KotlinCompileUtil.kt
1
4388
/* * 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.intellij.testGuiFramework.recorder.compile import com.intellij.ide.plugins.PluginManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.Logger import com.intellij.testGuiFramework.recorder.ScriptGenerator import com.intellij.testGuiFramework.recorder.actions.PerformScriptAction import java.io.File import java.net.URL import java.nio.file.Paths object KotlinCompileUtil { private val LOG by lazy { Logger.getInstance("#${KotlinCompileUtil::class.qualifiedName}") } fun compile(codeString: String) { LocalCompiler().compileOnPooledThread(ScriptGenerator.ScriptWrapper.wrapScript(codeString), getAllUrls().map { Paths.get(it.toURI()).toFile().path }) } fun compileAndRun(codeString: String) { LocalCompiler().compileAndRunOnPooledThread(ScriptGenerator.ScriptWrapper.wrapScript(codeString), getAllUrls().map { Paths.get(it.toURI()).toFile().path }) } fun getAllUrls(): List<URL> { if (ServiceManager::class.java.classLoader.javaClass.name.contains("Launcher\$AppClassLoader")) { //lets substitute jars with a common lib dir to avoid Windows long path error val urls = ServiceManager::class.java.classLoader.forcedUrls() val libUrl = urls.filter { url -> (url.file.endsWith("idea.jar") && File(url.path).parentFile.name == "lib") }.firstOrNull()!!.getParentURL() urls.filter { url -> !url.file.startsWith(libUrl.file) }.plus(libUrl).toSet() //add git4idea urls to allow git configuration from local runner // if (System.getenv("TEAMCITY_VERSION") != null) urls.plus(getGit4IdeaUrls()) if (!ApplicationManager.getApplication().isUnitTestMode) urls.plus(ServiceManager::class.java.classLoader.forcedBaseUrls()) return urls.toList() } var list: List<URL> = (ServiceManager::class.java.classLoader.forcedUrls() + PerformScriptAction::class.java.classLoader.forcedUrls()) if (!ApplicationManager.getApplication().isUnitTestMode) list += ServiceManager::class.java.classLoader.forcedBaseUrls() return list } fun getGit4IdeaUrls(): List<URL> { val git4IdeaPluginClassLoader = PluginManager.getPlugins().filter { pluginDescriptor -> pluginDescriptor.name.toLowerCase() == "git integration" }.firstOrNull()!!.pluginClassLoader val urls = git4IdeaPluginClassLoader.forcedUrls() val libUrl = urls.filter { url -> (url.file.endsWith("git4idea.jar") && File(url.path).parentFile.name == "lib") }.firstOrNull()!!.getParentURL() urls.filter { url -> !url.file.startsWith(libUrl.file) }.plus(libUrl).toSet() return urls } fun URL.getParentURL() = File(this.file).parentFile.toURI().toURL() fun ClassLoader.forcedUrls(): List<URL> { val METHOD_DEFAULT_NAME: String = "getUrls" val METHOD_ALTERNATIVE_NAME: String = "getURLs" var methodName: String = METHOD_DEFAULT_NAME if (this.javaClass.methods.any { mtd -> mtd.name == METHOD_ALTERNATIVE_NAME }) methodName = METHOD_ALTERNATIVE_NAME val method = this.javaClass.getMethod(methodName) method.isAccessible val methodResult = method.invoke(this) val myList: List<*> = (methodResult as? Array<*>)?.asList() ?: methodResult as List<*> return myList.filterIsInstance(URL::class.java) } fun ClassLoader.forcedBaseUrls(): List<URL> { try { return ((this.javaClass.getMethod("getBaseUrls").invoke( this) as? List<*>)!!.filter { it is URL && it.protocol == "file" && !it.file.endsWith("jar!") }) as List<URL> } catch (e: NoSuchMethodException) { return emptyList() } } }
apache-2.0
ede0d1e265324a2fe8c743a795dfde00
40.018692
184
0.702598
4.272639
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryAdapter.kt
3
2969
package eu.kanade.tachiyomi.ui.library import android.view.View import android.view.ViewGroup import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.util.inflate import eu.kanade.tachiyomi.widget.RecyclerViewPagerAdapter /** * This adapter stores the categories from the library, used with a ViewPager. * * @constructor creates an instance of the adapter. */ class LibraryAdapter(private val controller: LibraryController) : RecyclerViewPagerAdapter() { /** * The categories to bind in the adapter. */ var categories: List<Category> = emptyList() // This setter helps to not refresh the adapter if the reference to the list doesn't change. set(value) { if (field !== value) { field = value notifyDataSetChanged() } } private var boundViews = arrayListOf<View>() /** * Creates a new view for this adapter. * * @return a new view. */ override fun createView(container: ViewGroup): View { val view = container.inflate(R.layout.library_category) as LibraryCategoryView view.onCreate(controller) return view } /** * Binds a view with a position. * * @param view the view to bind. * @param position the position in the adapter. */ override fun bindView(view: View, position: Int) { (view as LibraryCategoryView).onBind(categories[position]) boundViews.add(view) } /** * Recycles a view. * * @param view the view to recycle. * @param position the position in the adapter. */ override fun recycleView(view: View, position: Int) { (view as LibraryCategoryView).onRecycle() boundViews.remove(view) } /** * Returns the number of categories. * * @return the number of categories or 0 if the list is null. */ override fun getCount(): Int { return categories.size } /** * Returns the title to display for a category. * * @param position the position of the element. * @return the title to display. */ override fun getPageTitle(position: Int): CharSequence { return categories[position].name } /** * Returns the position of the view. */ override fun getItemPosition(obj: Any): Int { val view = obj as? LibraryCategoryView ?: return POSITION_NONE val index = categories.indexOfFirst { it.id == view.category.id } return if (index == -1) POSITION_NONE else index } /** * Called when the view of this adapter is being destroyed. */ fun onDestroy() { for (view in boundViews) { if (view is LibraryCategoryView) { view.unsubscribe() } } } }
apache-2.0
15e79823a1dba7b7b93885424543585d
26.84466
100
0.599192
4.653605
false
false
false
false
Bombe/Sone
src/test/kotlin/net/pterodactylus/sone/database/memory/ConfigurationLoaderTest.kt
1
4832
package net.pterodactylus.sone.database.memory import net.pterodactylus.sone.test.TestValue.from import net.pterodactylus.sone.test.mock import net.pterodactylus.sone.test.whenever import net.pterodactylus.util.config.Configuration import net.pterodactylus.util.config.Value import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.containsInAnyOrder import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.nullValue import org.junit.Test /** * Unit test for [ConfigurationLoader]. */ class ConfigurationLoaderTest { private val configuration = mock<Configuration>() private val configurationLoader = ConfigurationLoader(configuration) private fun setupStringValue(attribute: String, value: String? = null): Value<String?> = from(value).apply { whenever(configuration.getStringValue(attribute)).thenReturn(this) } private fun setupLongValue(attribute: String, value: Long? = null): Value<Long?> = from(value).apply { whenever(configuration.getLongValue(attribute)).thenReturn(this) } @Test fun `loader can load known posts`() { setupStringValue("KnownPosts/0/ID", "Post2") setupStringValue("KnownPosts/1/ID", "Post1") setupStringValue("KnownPosts/2/ID") val knownPosts = configurationLoader.loadKnownPosts() assertThat(knownPosts, containsInAnyOrder("Post1", "Post2")) } @Test fun `loader can load known post replies`() { setupStringValue("KnownReplies/0/ID", "PostReply2") setupStringValue("KnownReplies/1/ID", "PostReply1") setupStringValue("KnownReplies/2/ID") val knownPosts = configurationLoader.loadKnownPostReplies() assertThat(knownPosts, containsInAnyOrder("PostReply1", "PostReply2")) } @Test fun `loader can load bookmarked posts`() { setupStringValue("Bookmarks/Post/0/ID", "Post2") setupStringValue("Bookmarks/Post/1/ID", "Post1") setupStringValue("Bookmarks/Post/2/ID") val knownPosts = configurationLoader.loadBookmarkedPosts() assertThat(knownPosts, containsInAnyOrder("Post1", "Post2")) } @Test fun `loader can save bookmarked posts`() { val post1 = setupStringValue("Bookmarks/Post/0/ID") val post2 = setupStringValue("Bookmarks/Post/1/ID") val post3 = setupStringValue("Bookmarks/Post/2/ID") val originalPosts = setOf("Post1", "Post2") configurationLoader.saveBookmarkedPosts(originalPosts) val extractedPosts = setOf(post1.value, post2.value) assertThat(extractedPosts, containsInAnyOrder("Post1", "Post2")) assertThat(post3.value, nullValue()) } @Test fun `loader can load Sone following times`() { setupStringValue("SoneFollowingTimes/0/Sone", "Sone1") setupLongValue("SoneFollowingTimes/0/Time", 1000L) setupStringValue("SoneFollowingTimes/1/Sone", "Sone2") setupLongValue("SoneFollowingTimes/1/Time", 2000L) setupStringValue("SoneFollowingTimes/2/Sone") assertThat(configurationLoader.getSoneFollowingTime("Sone1"), equalTo(1000L)) assertThat(configurationLoader.getSoneFollowingTime("Sone2"), equalTo(2000L)) assertThat(configurationLoader.getSoneFollowingTime("Sone3"), nullValue()) } @Test fun `loader can overwrite existing Sone following time`() { val sone1Id = setupStringValue("SoneFollowingTimes/0/Sone", "Sone1") val sone1Time = setupLongValue("SoneFollowingTimes/0/Time", 1000L) val sone2Id = setupStringValue("SoneFollowingTimes/1/Sone", "Sone2") val sone2Time = setupLongValue("SoneFollowingTimes/1/Time", 2000L) setupStringValue("SoneFollowingTimes/2/Sone") configurationLoader.setSoneFollowingTime("Sone1", 3000L) assertThat(listOf(sone1Id.value to sone1Time.value, sone2Id.value to sone2Time.value), containsInAnyOrder<Pair<String?, Long?>>( "Sone1" to 3000L, "Sone2" to 2000L )) } @Test fun `loader can remove Sone following time`() { val sone1Id = setupStringValue("SoneFollowingTimes/0/Sone", "Sone1") val sone1Time = setupLongValue("SoneFollowingTimes/0/Time", 1000L) val sone2Id = setupStringValue("SoneFollowingTimes/1/Sone", "Sone2") val sone2Time = setupLongValue("SoneFollowingTimes/1/Time", 2000L) setupStringValue("SoneFollowingTimes/2/Sone") configurationLoader.removeSoneFollowingTime("Sone1") assertThat(sone1Id.value, equalTo("Sone2")) assertThat(sone1Time.value, equalTo(2000L)) assertThat(sone2Id.value, nullValue()) } @Test fun `sone with missing following time is not loaded`() { setupStringValue("SoneFollowingTimes/0/Sone", "Sone1") setupLongValue("SoneFollowingTimes/0/Time", 1000L) setupStringValue("SoneFollowingTimes/1/Sone", "Sone2") setupLongValue("SoneFollowingTimes/1/Time") setupStringValue("SoneFollowingTimes/2/Sone") assertThat(configurationLoader.getSoneFollowingTime("Sone1"), equalTo(1000L)) assertThat(configurationLoader.getSoneFollowingTime("Sone2"), nullValue()) assertThat(configurationLoader.getSoneFollowingTime("Sone3"), nullValue()) } }
gpl-3.0
f1784f9bd5b474eb05a3b496698fd29c
38.606557
130
0.771109
3.893634
false
true
false
false
wangjiegulu/AndroidKotlinBucket
library/src/main/kotlin/com/wangjie/androidkotlinbucket/library/AKBViewExt.kt
1
2323
package com.wangjie.androidkotlinbucket.library import android.app.Activity import android.content.Context import android.content.Intent import android.support.v4.app.Fragment import android.view.View import android.widget.Toast /** * Author: wangjie * Email: [email protected] * Date: 11/9/15. */ /** Activity **/ // 从Activity中注入View public fun <T : View> Activity._pick(resId: Int) = lazy(LazyThreadSafetyMode.NONE) { findViewById(resId) as T } //// 绑定点击事件 //public fun Activity._click(onClick: ((View) -> Unit)?, vararg resId: Int): Activity { // __click({ findViewById(it) }, onClick, resId) // return this //} /** Fragment **/ // 从Fragment中注入View public fun <T : View> Fragment._pick(resId: Int) = lazy(LazyThreadSafetyMode.NONE) { view!!.findViewById(resId) as T } //// 绑定点击事件 //public fun Fragment._click(onClick: ((View) -> Unit)?, vararg resId: Int): Fragment { // __click({ view.findViewById(it) }, onClick, resId) // return this //} /** View **/ // 从View中注入View public fun <T : View> View._pick(resId: Int) = lazy(LazyThreadSafetyMode.NONE) { findViewById(resId) as T } //// 绑定点击事件 //public fun View._click(onClick: ((View) -> Unit)?, vararg resId: Int): View { // __click({ findViewById(it) }, onClick, resId) // return this //} /** Common **/ //public fun _abkClick(onClick: ((View) -> Unit)?, vararg view: View) { // onClick?.let { // view.forEach { it.setOnClickListener(onClick) } // } //} // // //private inline fun __click(findView: (Int) -> View, noinline onClick: ((View) -> Unit)?, resId: IntArray) { // onClick?.let { // resId.forEach { findView(it).setOnClickListener(onClick) } // } //} inline fun <reified T : Activity> Context.toActivity(f: (Intent) -> Unit) { with(Intent(this, T::class.java)) { f(this) startActivity(this) } } // toast fun Activity.toast(message: String, duration: Int = Toast.LENGTH_SHORT) = Toast.makeText(this, message, duration).show() fun Fragment.toast(message: String, duration: Int = Toast.LENGTH_SHORT) = context?.lets { Toast.makeText(this, message, duration).show() } fun View.toast(message: String, duration: Int = Toast.LENGTH_SHORT) = context?.lets { Toast.makeText(this, message, duration).show() }
apache-2.0
06d2e9e5f8ac8b0c9d6c4ed274a5e581
26.597561
138
0.661953
3.433991
false
false
false
false
FrancYescO/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/util/ApiAuthProvider.kt
1
2339
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.util import ink.abb.pogo.scraper.services.BotService import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import org.springframework.web.servlet.handler.HandlerInterceptorAdapter import java.math.BigInteger import java.security.SecureRandom import java.util.regex.Pattern import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @Component open class ApiAuthProvider : HandlerInterceptorAdapter() { @Autowired lateinit var service: BotService val random: SecureRandom = SecureRandom() @Throws(Exception::class) override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean { if (request.method.equals("OPTIONS")) return true // Allow preflight calls val pattern = Pattern.compile("\\/api/bot/([A-Za-z0-9\\-_]*)") val matcher = pattern.matcher(request.requestURI) if (matcher.find()) { val token = service.getBotContext(matcher.group(1)).restApiToken // If the token is invalid or isn't in the request, nothing will be done return request.getHeader("X-PGB-ACCESS-TOKEN")!!.equals(token) } return false } fun generateRandomString(): String { return BigInteger(130, random).toString(32) } fun generateAuthToken(botName: String) { val token: String = this.generateRandomString() service.getBotContext(botName).restApiToken = token Log.cyan("REST API token for bot $botName : $token has been generated") } fun generateRestPassword(botName: String) { val password: String = this.generateRandomString() service.getBotContext(botName).restApiPassword = password service.doWithBot(botName) { it.settings.restApiPassword = password } Log.red("Generated restApiPassword: $password") } }
gpl-3.0
b7934bbd1fb08a57f4fdca653f5977f1
33.397059
97
0.70714
4.62253
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/settings/privacy/ConnectionDetailsPanel.kt
1
2740
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.settings.privacy import android.content.Context import android.view.View import android.widget.FrameLayout import androidx.appcompat.content.res.AppCompatResources import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import mozilla.components.browser.icons.IconRequest import mozilla.components.support.ktx.android.view.putCompoundDrawablesRelativeWithIntrinsicBounds import org.mozilla.focus.R import org.mozilla.focus.databinding.ConnectionDetailsBinding import org.mozilla.focus.ext.components @SuppressWarnings("LongParameterList") class ConnectionDetailsPanel( context: Context, private val tabTitle: String, private val tabUrl: String, private val isConnectionSecure: Boolean, private val goBack: () -> Unit, ) : BottomSheetDialog(context) { private var binding: ConnectionDetailsBinding = ConnectionDetailsBinding.inflate(layoutInflater, null, false) init { setContentView(binding.root) expandBottomSheet() updateSiteInfo() updateConnectionState() setListeners() } private fun expandBottomSheet() { val bottomSheet = findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout BottomSheetBehavior.from(bottomSheet).state = BottomSheetBehavior.STATE_EXPANDED } private fun updateSiteInfo() { binding.siteTitle.text = tabTitle binding.siteFullUrl.text = tabUrl context.components.icons.loadIntoView( binding.siteFavicon, IconRequest(tabUrl, isPrivate = true), ) } private fun updateConnectionState() { binding.securityInfo.text = if (isConnectionSecure) { context.getString(R.string.secure_connection) } else { context.getString(R.string.insecure_connection) } val securityIcon = if (isConnectionSecure) { AppCompatResources.getDrawable(context, R.drawable.mozac_ic_lock) } else { AppCompatResources.getDrawable(context, R.drawable.mozac_ic_warning) } binding.securityInfo.putCompoundDrawablesRelativeWithIntrinsicBounds( start = securityIcon, end = null, top = null, bottom = null, ) } private fun setListeners() { binding.detailsBack.setOnClickListener { goBack.invoke() dismiss() } } }
mpl-2.0
1dc64130568283cdb9d0e8c7d9a224dc
32.414634
99
0.69635
4.807018
false
false
false
false
fnouama/intellij-community
platform/diff-impl/tests/com/intellij/diff/comparison/SplitComparisonUtilTest.kt
8
3346
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.comparison public class SplitComparisonUtilTest : ComparisonUtilTestBase() { public fun testSplitter() { splitter { ("x" - "z") default(mod(0, 0, 1, 1)) testAll() } splitter { ("x_y" - "a_b") default(mod(0, 0, 2, 2)) testAll() } splitter { ("x_y" - "a_b y") default(mod(0, 0, 1, 1), mod(1, 1, 1, 1)) testAll() } splitter { ("x y" - "x a_b y") default(mod(0, 0, 1, 2)) testAll() } splitter { ("x_y" - "x a_y b") default(mod(0, 0, 1, 1), mod(1, 1, 1, 1)) testAll() } splitter { ("x_" - "x a_...") default(mod(0, 0, 2, 2)) testAll() } splitter { ("x_y_" - "a_b_") default(mod(0, 0, 2, 2)) testAll() } splitter { ("x_y" - " x _ y ") default(mod(0, 0, 2, 2)) testDefault() } splitter { ("x_y" - " x _ y.") default(mod(0, 0, 1, 1), mod(1, 1, 1, 1)) testDefault() } splitter { ("a_x_b_" - " x_") default(del(0, 0, 1), mod(1, 0, 1, 1), del(2, 1, 1)) testDefault() } splitter { ("a_x_b_" - "!x_") default(del(0, 0, 1), mod(1, 0, 1, 1), del(2, 1, 1)) testAll() } } public fun testSquash() { splitter(squash = true) { ("x" - "z") default(mod(0, 0, 1, 1)) testAll() } splitter(squash = true) { ("x_y" - "a_b") default(mod(0, 0, 2, 2)) testAll() } splitter(squash = true) { ("x_y" - "a_b y") default(mod(0, 0, 2, 2)) testAll() } splitter(squash = true) { ("a_x_b_" - " x_") default(mod(0, 0, 3, 1)) testDefault() } splitter(squash = true) { ("a_x_b_" - "!x_") default(mod(0, 0, 3, 1)) testAll() } } public fun testTrim() { splitter(trim = true) { ("_" - " _ ") default(mod(0, 0, 2, 2)) trim() testAll() } splitter(trim = true) { ("" - " _ ") default(mod(0, 0, 1, 2)) trim(ins(1, 1, 1)) ignore() testAll() } splitter(trim = true) { (" _ " - "") default(mod(0, 0, 2, 1)) trim(del(1, 1, 1)) ignore() testAll() } splitter(trim = true) { ("x_y" - "z_ ") default(mod(0, 0, 2, 2)) testAll() } splitter(trim = true) { ("z" - "z_ ") default(ins(1, 1, 1)) ignore() testAll() } splitter(trim = true) { ("z_ x" - "z_ w") default(mod(1, 1, 1, 1)) testAll() } splitter(trim = true) { ("__z__" - "z") default(del(0, 0, 2), del(3, 1, 2)) ignore() testAll() } } }
apache-2.0
dbb6707cbc0e992f5b91e3ec477f37f3
20.177215
75
0.463837
3.05292
false
true
false
false
square/leakcanary
leakcanary-android-release/src/main/java/leakcanary/internal/BackgroundListener.kt
2
2034
package leakcanary.internal import android.app.Activity import android.app.Application import android.app.Application.ActivityLifecycleCallbacks import leakcanary.ProcessInfo import leakcanary.internal.friendly.mainHandler import leakcanary.internal.friendly.noOpDelegate /** * Tracks whether the app is in background, based on the app's importance. */ internal class BackgroundListener( private val processInfo: ProcessInfo, private val callback: (Boolean) -> Unit ) : ActivityLifecycleCallbacks by noOpDelegate() { private val checkAppInBackground: Runnable = object : Runnable { override fun run() { val appInBackgroundNow = processInfo.isImportanceBackground updateBackgroundState(appInBackgroundNow) if (!appInBackgroundNow) { mainHandler.removeCallbacks(this) mainHandler.postDelayed(this, BACKGROUND_REPEAT_DELAY_MS) } } } private fun updateBackgroundState(appInBackgroundNow: Boolean) { if (appInBackground != appInBackgroundNow) { appInBackground = appInBackgroundNow callback.invoke(appInBackgroundNow) } } private var appInBackground = false fun install(application: Application) { application.registerActivityLifecycleCallbacks(this) updateBackgroundState(appInBackgroundNow = false) checkAppInBackground.run() } fun uninstall(application: Application) { application.unregisterActivityLifecycleCallbacks(this) updateBackgroundState(appInBackgroundNow = false) mainHandler.removeCallbacks(checkAppInBackground) } override fun onActivityPaused(activity: Activity) { mainHandler.removeCallbacks(checkAppInBackground) mainHandler.postDelayed(checkAppInBackground, BACKGROUND_DELAY_MS) } override fun onActivityResumed(activity: Activity) { updateBackgroundState(appInBackgroundNow = false) mainHandler.removeCallbacks(checkAppInBackground) } companion object { private const val BACKGROUND_DELAY_MS = 1000L private const val BACKGROUND_REPEAT_DELAY_MS = 5000L } }
apache-2.0
4ec7ad3b7fcbe6a5ee9bef1b9827dace
30.78125
74
0.774828
5.296875
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/search/url/UrlCardView.kt
1
3850
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.search.url import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import androidx.cardview.widget.CardView import androidx.core.view.isVisible import androidx.databinding.DataBindingUtil import jp.toastkid.lib.color.IconColorFinder import jp.toastkid.lib.intent.UrlShareIntentFactory import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.ViewSearchCardUrlBinding import jp.toastkid.yobidashi.libs.Toaster import jp.toastkid.yobidashi.libs.clip.Clipboard /** * @author toastkidjp */ class UrlCardView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : CardView(context, attrs, defStyleAttr) { private val preferenceApplier = PreferenceApplier(context) private var binding: ViewSearchCardUrlBinding? = null private var insertAction: ((String) -> Unit)? = null init { val inflater = LayoutInflater.from(context) binding = DataBindingUtil.inflate(inflater, R.layout.view_search_card_url, this, true) binding?.module = this } /** * This function is called from data-binding. * * @param view [View] */ fun clipUrl(view: View) { val text = getCurrentText() val context = view.context Clipboard.clip(context, text) Toaster.snackShort( view, context.getString(R.string.message_clip_to, text), preferenceApplier.colorPair() ) } fun setInsertAction(action: (String) -> Unit) { insertAction = action } fun edit() { insertAction?.invoke(binding?.text?.text.toString()) } /** * This function is called from data-binding. * * @param view [View] */ fun shareUrl(view: View) { view.context.startActivity(UrlShareIntentFactory()(getCurrentText())) } /** * Switch visibility and content. * * @param title site's title * @param url URL */ fun switch(title: String?, url: String?) = if (url.isNullOrBlank() || !isEnabled) { clearContent() hide() } else { setTitle(title) setLink(url) show() } /** * Show this module. */ private fun show() { if (this.visibility == View.GONE && isEnabled) { runOnMainThread { this.visibility = View.VISIBLE } } } /** * Hide this module. */ fun hide() { if (isVisible) { runOnMainThread { this.visibility = View.GONE } } } fun onResume() { val color = IconColorFinder.from(this).invoke() binding?.clip?.setColorFilter(color) binding?.share?.setColorFilter(color) binding?.edit?.setColorFilter(color) } fun dispose() { binding = null } private fun getCurrentText() = binding?.text?.text.toString() private fun setTitle(title: String?) { binding?.title?.text = title } /** * Set open link and icon. * * @param link Link URL(string) */ private fun setLink(link: String) { binding?.text?.text = link } private fun clearContent() { binding?.title?.text = "" binding?.text?.text = "" } private fun runOnMainThread(action: () -> Unit) = post { action() } }
epl-1.0
65349c7e5e43334e336a557de726debd
25.02027
94
0.621039
4.375
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/ui/ManageCategoriesActivity.kt
1
6522
package info.papdt.express.helper.ui import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.LinearLayout import androidx.recyclerview.widget.RecyclerView import info.papdt.express.helper.R import info.papdt.express.helper.dao.PackageDatabase import info.papdt.express.helper.dao.SRDatabase import info.papdt.express.helper.event.EventCallbacks import info.papdt.express.helper.event.EventIntents import info.papdt.express.helper.ui.adapter.CategoriesListAdapter import info.papdt.express.helper.ui.common.AbsActivity import info.papdt.express.helper.ui.dialog.EditCategoryDialog import info.papdt.express.helper.ui.items.CategoryItemViewBinder import moe.feng.kotlinyan.common.* class ManageCategoriesActivity : AbsActivity() { companion object { fun launch(activity: Activity, requestCode: Int) { val intent = Intent(activity, ManageCategoriesActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK) activity.startActivityForResult(intent, requestCode) } } private val listView: RecyclerView by lazyFindNonNullView(android.R.id.list) private val emptyView: LinearLayout by lazyFindNonNullView(R.id.empty_view) private val adapter: CategoriesListAdapter = CategoriesListAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_manage_categories) } override fun setUpViews() { listView.adapter = adapter adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { override fun onChanged() { emptyView.visibility = if (adapter.itemCount > 0) View.GONE else View.VISIBLE } override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { onChanged() } override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { onChanged() } }) ui { adapter.setCategories(asyncIO { SRDatabase.categoryDao.getAll() }.await()) } } override fun onStart() { super.onStart() registerLocalBroadcastReceiver(EventCallbacks.onItemClick(CategoryItemViewBinder::class) { if (it != null) { EditCategoryDialog.newEditDialog(it).show(supportFragmentManager, "edit_dialog") } }, action = EventIntents.getItemOnClickActionName(CategoryItemViewBinder::class)) registerLocalBroadcastReceiver(EventCallbacks.onSaveNewCategory { ui { val newList = asyncIO { SRDatabase.categoryDao.add(it) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } }, action = EventIntents.ACTION_SAVE_NEW_CATEGORY) registerLocalBroadcastReceiver(EventCallbacks.onSaveEditCategory { oldData, data -> ui { if (oldData.title == data.title) { // Its title hasn't been changed. Just update val newList = asyncIO { SRDatabase.categoryDao.update(data) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } else { // Title has been changed. Need update package list val newList = asyncIO { val packDatabase = PackageDatabase.getInstance(this) for (pack in packDatabase.data) { if (pack.categoryTitle == oldData.title) { pack.categoryTitle = data.title } } packDatabase.save() SRDatabase.categoryDao.delete(oldData) SRDatabase.categoryDao.add(data) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } } }, action = EventIntents.ACTION_SAVE_EDIT_CATEGORY) registerLocalBroadcastReceiver(EventCallbacks.onDeleteCategory { buildAlertDialog { titleRes = R.string.delete_category_dialog_title messageRes = R.string.delete_category_dialog_message okButton { _, _ -> ui { val newList = asyncIO { SRDatabase.categoryDao.deleteWithUpdatingPackages(this, it) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } } cancelButton() }.show() }, action = EventIntents.ACTION_REQUEST_DELETE_CATEGORY) } override fun onStop() { super.onStop() unregisterAllLocalBroadcastReceiver() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_manage_categories, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_new_category -> { EditCategoryDialog.newCreateDialog().show(supportFragmentManager, "create_dialog") true } R.id.action_reset_category -> { buildAlertDialog { titleRes = R.string.reset_default_category_dialog_title messageRes = R.string.reset_default_category_dialog_message okButton { _, _ -> ui { val newList = asyncIO { SRDatabase.categoryDao.clearWithUpdatingPackages(this) SRDatabase.categoryDao.addDefaultCategories(this) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } } cancelButton() }.show() true } else -> super.onOptionsItemSelected(item) } }
gpl-3.0
b84377bbd481608fc3979ac6fea44a18
39.018405
98
0.592303
5.439533
false
false
false
false
xfournet/intellij-community
platform/platform-impl/src/com/intellij/openapi/progress/progress.kt
23
1665
/* * 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.openapi.progress import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls inline fun runModalTask(@Nls(capitalization = Nls.Capitalization.Title) title: String, project: Project? = null, cancellable: Boolean = true, crossinline task: (indicator: ProgressIndicator) -> Unit) { ProgressManager.getInstance().run(object : Task.Modal(project, title, cancellable) { override fun run(indicator: ProgressIndicator) { task(indicator) } }) } inline fun runBackgroundableTask(@Nls(capitalization = Nls.Capitalization.Title) title: String, project: Project? = null, cancellable: Boolean = true, crossinline task: (indicator: ProgressIndicator) -> Unit) { ProgressManager.getInstance().run(object : Task.Backgroundable(project, title, cancellable) { override fun run(indicator: ProgressIndicator) { task(indicator) } }) }
apache-2.0
fc63008c4fa823e5cd67a3167c6e4fe9
39.634146
95
0.671471
4.70339
false
false
false
false
Kotlin/dokka
plugins/base/src/main/kotlin/transformers/pages/sourcelinks/SourceLinksTransformer.kt
1
6546
package org.jetbrains.dokka.base.transformers.pages.sourcelinks import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiIdentifier import org.jetbrains.dokka.DokkaConfiguration import org.jetbrains.dokka.DokkaConfiguration.DokkaSourceSet import org.jetbrains.dokka.analysis.DescriptorDocumentableSource import org.jetbrains.dokka.analysis.PsiDocumentableSource import org.jetbrains.dokka.base.DokkaBase import org.jetbrains.dokka.base.translators.documentables.PageContentBuilder import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.* import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.plugability.plugin import org.jetbrains.dokka.plugability.querySingle import org.jetbrains.dokka.transformers.pages.PageTransformer import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.utils.addToStdlib.cast import java.io.File class SourceLinksTransformer(val context: DokkaContext) : PageTransformer { private val builder : PageContentBuilder = PageContentBuilder( context.plugin<DokkaBase>().querySingle { commentsToContentConverter }, context.plugin<DokkaBase>().querySingle { signatureProvider }, context.logger ) override fun invoke(input: RootPageNode): RootPageNode { val sourceLinks = getSourceLinksFromConfiguration() if (sourceLinks.isEmpty()) { return input } return input.transformContentPagesTree { node -> when (node) { is WithDocumentables -> { val sources = node.documentables .filterIsInstance<WithSources>() .fold(mutableMapOf<DRI, List<Pair<DokkaSourceSet, String>>>()) { acc, documentable -> val dri = (documentable as Documentable).dri acc.compute(dri) { _, v -> val sources = resolveSources(sourceLinks, documentable) v?.plus(sources) ?: sources } acc } if (sources.isNotEmpty()) node.modified(content = transformContent(node.content, sources)) else node } else -> node } } } private fun getSourceLinksFromConfiguration(): List<SourceLink> { return context.configuration.sourceSets .flatMap { it.sourceLinks.map { sl -> SourceLink(sl, it) } } } private fun resolveSources( sourceLinks: List<SourceLink>, documentable: WithSources ): List<Pair<DokkaSourceSet, String>> { return documentable.sources.mapNotNull { (sourceSet, documentableSource) -> val sourceLink = sourceLinks.find { sourceLink -> File(documentableSource.path).startsWith(sourceLink.path) && sourceLink.sourceSetData == sourceSet } ?: return@mapNotNull null sourceSet to documentableSource.toLink(sourceLink) } } private fun DocumentableSource.toLink(sourceLink: SourceLink): String { val sourcePath = File(this.path).invariantSeparatorsPath val sourceLinkPath = File(sourceLink.path).invariantSeparatorsPath val lineNumber = when (this) { is DescriptorDocumentableSource -> this.descriptor .cast<DeclarationDescriptorWithSource>() .source.getPsi() ?.lineNumber() is PsiDocumentableSource -> this.psi.lineNumber() else -> null } return sourceLink.url + sourcePath.split(sourceLinkPath)[1] + sourceLink.lineSuffix + "${lineNumber ?: 1}" } private fun PsiElement.lineNumber(): Int? { val ktIdentifierTextRange = this.node?.findChildByType(KtTokens.IDENTIFIER)?.textRange val javaIdentifierTextRange = this.getChildOfType<PsiIdentifier>()?.textRange // synthetic and some light methods might return null val textRange = ktIdentifierTextRange ?: javaIdentifierTextRange ?: textRange ?: return null val doc = PsiDocumentManager.getInstance(project).getDocument(containingFile) // IJ uses 0-based line-numbers; external source browsers use 1-based return doc?.getLineNumber(textRange.startOffset)?.plus(1) } private fun ContentNode.signatureGroupOrNull() = (this as? ContentGroup)?.takeIf { it.dci.kind == ContentKind.Symbol } private fun transformContent( contentNode: ContentNode, sources: Map<DRI, List<Pair<DokkaSourceSet, String>>> ): ContentNode = contentNode.signatureGroupOrNull()?.let { sg -> sources[sg.dci.dri.singleOrNull()]?.let { sourceLinks -> sourceLinks .filter { it.first.sourceSetID in sg.sourceSets.sourceSetIDs } .takeIf { it.isNotEmpty() } ?.let { filteredSourcesLinks -> sg.copy(children = sg.children + filteredSourcesLinks.map { buildContentLink( sg.dci.dri.first(), it.first, it.second ) }) } } } ?: when (contentNode) { is ContentComposite -> contentNode.transformChildren { transformContent(it, sources) } else -> contentNode } private fun buildContentLink(dri: DRI, sourceSet: DokkaSourceSet, link: String) = builder.contentFor( dri, setOf(sourceSet), ContentKind.Source, setOf(TextStyle.FloatingRight) ) { text("(") link("source", link) text(")") } } data class SourceLink(val path: String, val url: String, val lineSuffix: String?, val sourceSetData: DokkaSourceSet) { constructor(sourceLinkDefinition: DokkaConfiguration.SourceLinkDefinition, sourceSetData: DokkaSourceSet) : this( sourceLinkDefinition.localDirectory, sourceLinkDefinition.remoteUrl.toExternalForm(), sourceLinkDefinition.remoteLineSuffix, sourceSetData ) }
apache-2.0
b14765e26983f5d6b49c5e6993a566e1
41.79085
118
0.633058
5.392092
false
false
false
false
Riccorl/kotlin-koans
src/i_introduction/_3_Default_Arguments/n03DefaultArguments.kt
1
927
package i_introduction._3_Default_Arguments import util.TODO import util.doc2 fun todoTask3(): Nothing = TODO( """ Task 3. Several overloaded 'foo' functions in the class 'JavaCode3' can be replaced with one function in Kotlin. Change the declaration of the function 'foo' in a way that makes the code using 'foo' compile. You have to add 'foo' parameters and implement its body. Uncomment the commented code and make it compile. """, documentation = doc2(), references = { name: String -> JavaCode3().foo(name); foo(name) }) fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String = (if (toUpperCase) name.toUpperCase() else name) + number fun task3(): String { // todoTask3() return (foo("a") + foo("b", number = 1) + foo("c", toUpperCase = true) + foo(name = "d", number = 2, toUpperCase = true)) }
mit
2d57890350641c9fedceacea8ab6667d
36.12
136
0.632147
3.99569
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UITableView_CellProcesser.kt
1
5182
package com.yy.codex.uikit import com.yy.codex.foundation.NSLog import com.yy.codex.foundation.lets import java.util.* /** * Created by cuiminghui on 2017/2/27. */ internal fun UITableView._updateCellsFrame() { subviews.forEach { (it as? UITableViewCell)?.let { it.frame = it.frame.setWidth(frame.width) } } } internal fun UITableView._reloadData() { _lastVisibleHash = "" _reloadSectionHeaderFooterView() _reloadCellCaches() _reloadContentSize() _markCellReusable(listOf()) _updateCells() _updateTableHeaderFooterViewFrame() _updateSectionHeaderFooterFrame() } internal fun UITableView._requestCell(indexPath: NSIndexPath): UITableViewCell? { _cellInstances.toList().forEach { it.second.toList().forEach { if (it.cell._indexPath == indexPath) { return it.cell } } } return null } internal fun UITableView._allCells(): List<UITableViewCell> { var cells: MutableList<UITableViewCell> = mutableListOf() _cellInstances.toList().forEach { it.second.toList().forEach { cells.add(it.cell) } } return cells.toList() } internal fun UITableView._updateCells() { val dataSource = dataSource ?: return val visiblePositions = _requestVisiblePositions() val currentVisibleHash = _computeVisibleHash(visiblePositions) if (_lastVisibleHash == currentVisibleHash) { return } _lastVisibleHash = currentVisibleHash _markCellReusable(visiblePositions).forEach { val visiblePosition = it val cell = dataSource.cellForRowAtIndexPath(this, it.indexPath) cell._indexPath = it.indexPath cell.frame = CGRect(0.0, it.value, frame.width, it.height) cell.setSelected(_isCellSelected(cell), false) _enqueueCell(cell, it) if (cell.superview !== this) { cell.removeFromSuperview() insertSubview(cell, 0) } cell._updateAppearance() delegate()?.let { it.willDisplayCell(this, cell, visiblePosition.indexPath) } } } internal fun UITableView._isCellSelected(cell: UITableViewCell): Boolean { indexPathsForSelectedRows.forEach { if (it == cell._indexPath) { return true } } return false } internal fun UITableView._dequeueCell(reuseIdentifier: String): UITableViewCell? { var cell: UITableViewCell? = null _cellInstances[reuseIdentifier]?.let { it.toList().forEach { if (cell != null) { return@forEach } if (!it.isBusy) { cell = it.cell } } } cell?.prepareForReuse() return cell } internal fun UITableView._requestPreviousPointCell(cell: UITableViewCell): UITableViewCell? { (this._requestCell(this._requestCellPositionWithPoint(cell.frame.y - 1.0).indexPath))?.let { if (it != cell && it.frame.y + it.frame.height >= cell.frame.y - 1.0) { return it } } return null } internal fun UITableView._requestNextPointCell(cell: UITableViewCell): UITableViewCell? { (this._requestCell(this._requestCellPositionWithPoint(cell.frame.y + cell.frame.height + 1.0).indexPath))?.let { if (it != cell && it.frame.y <= cell.frame.y + cell.frame.height + 1.0) { return it } } return null } private fun UITableView._enqueueCell(cell: UITableViewCell, cellPosition: UITableViewCellPosition) { val reuseIdentifier = cell.reuseIdentifier ?: return if (_cellInstances[reuseIdentifier] == null) { _cellInstances[reuseIdentifier] = mutableListOf() } _cellInstances[reuseIdentifier]?.let { var found = false it.toList().forEach { if (it.cell === cell) { it.cellPosition = cellPosition it.isBusy = true found = true } } if (!found) { it.add(UITableViewReusableCell(cell, cellPosition, true)) } } } private fun UITableView._markCellReusable(visiblePositions: List<UITableViewCellPosition>): List<UITableViewCellPosition> { val trimmedPositions: MutableList<UITableViewCellPosition> = visiblePositions.toMutableList() val visibleMapping: HashMap<UITableViewCellPosition, Boolean> = hashMapOf() visiblePositions.forEach { visibleMapping[it] = true } _cellInstances.toList().forEach { it.second.toList().forEach { it.isBusy = it.cellPosition != null && visibleMapping[it.cellPosition!!] == true if (it.isBusy) { trimmedPositions.remove(it.cellPosition) } else { it.cellPosition = null lets(it.cell, it.cell._indexPath) { cell, indexPath -> delegate()?.let { it.didEndDisplayingCell(this, cell, indexPath) } } } } } return trimmedPositions.toList() } internal class UITableViewReusableCell(val cell: UITableViewCell, var cellPosition: UITableViewCellPosition?, var isBusy: Boolean)
gpl-3.0
185d5b7997558547027f4159670507c4
30.797546
130
0.623311
4.490468
false
false
false
false
googlecodelabs/slices-basic-codelab
complete/src/main/java/com/example/android/slicesbasiccodelab/TemperatureSliceProvider.kt
1
7123
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.slicesbasiccodelab import android.app.PendingIntent import android.content.ContentResolver import android.content.Context import android.content.Intent import android.net.Uri import android.util.Log import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.IconCompat import androidx.slice.Slice import androidx.slice.SliceProvider import androidx.slice.builders.ListBuilder import androidx.slice.builders.SliceAction import androidx.slice.builders.header import androidx.slice.builders.list import com.example.android.slicesbasiccodelab.MainActivity.Companion.getTemperature import com.example.android.slicesbasiccodelab.MainActivity.Companion.getTemperatureString import com.example.android.slicesbasiccodelab.TemperatureBroadcastReceiver.Companion.ACTION_CHANGE_TEMPERATURE import com.example.android.slicesbasiccodelab.TemperatureBroadcastReceiver.Companion.EXTRA_TEMPERATURE_VALUE /** * Creates a temperature control Slice that mirrors the main activity. The slice displays the * current temperature and allows the user to adjust the temperature up and down from the Slice * without launching the activity. * * NOTE: The main action still allows the user to launch the main activity if they choose. */ class TemperatureSliceProvider : SliceProvider() { private lateinit var contextNonNull: Context override fun onCreateSliceProvider(): Boolean { // TODO: Step 2.3, Review non-nullable Context variable. contextNonNull = context ?: return false return true } /* * Each Slice has an associated URI. The standard format is package name + path for each Slice. * In our case, we only have one slice mapped to the 'temperature' path * ('com.example.android.slicesbasiccodelab/temperature'). * * When a surface wants to display a Slice, it sends a binding request to your app with this * URI via this method and you build out the slice to return. The surface can then display the * Slice when appropriate. * * Note: You can make your slices interactive by adding actions. (We do this for our * temperature up/down buttons.) */ override fun onBindSlice(sliceUri: Uri): Slice? { Log.d(TAG, "onBindSlice(): $sliceUri") // TODO: Step 2.4, Define a slice path. when (sliceUri.path) { "/temperature" -> return createTemperatureSlice(sliceUri) } return null } // Creates the actual Slice used in onBindSlice(). private fun createTemperatureSlice(sliceUri: Uri): Slice { Log.d(TAG, "createTemperatureSlice(): $sliceUri") /* Slices are constructed by using a ListBuilder (it is the main building block of Slices). * ListBuilder allows you to add different types of rows that are displayed in a list. * Because we are using the Slice KTX library, we can use the DSL version of ListBuilder, * so we just need to use list() and include some general arguments before defining the * structure of the Slice. */ // TODO: Step 3.1, Review Slice's ListBuilder. return list(contextNonNull, sliceUri, ListBuilder.INFINITY) { setAccentColor(ContextCompat.getColor(contextNonNull, R.color.slice_accent_color)) /* The first row of your slice should be a header. The header supports a title, * subtitle, and a tappable action (usually used to launch an Activity). A header * can also have a summary of the contents of the slice which can be shown when * the Slice may be too large to be displayed. In our case, we are also attaching * multiple actions to the header row (temp up/down). * * If we wanted to add additional rows, you can use the RowBuilder or the GridBuilder. * */ // TODO: Step 3.2, Create a Slice Header (title and primary action). header { title = getTemperatureString(contextNonNull) // Launches the main Activity associated with the Slice. primaryAction = SliceAction.create( PendingIntent.getActivity( contextNonNull, sliceUri.hashCode(), Intent(contextNonNull, MainActivity::class.java), 0 ), IconCompat.createWithResource(contextNonNull, R.drawable.ic_home), ListBuilder.ICON_IMAGE, contextNonNull.getString(R.string.slice_action_primary_title) ) } // TODO: Step 3.3, Add Temperature Up Slice Action. addAction( SliceAction.create( createTemperatureChangePendingIntent(getTemperature() + 1), IconCompat.createWithResource(contextNonNull, R.drawable.ic_temp_up), ListBuilder.ICON_IMAGE, contextNonNull.getString(R.string.increase_temperature) ) ) // TODO: Step 3.4, Add Temperature Down Slice Action. addAction( SliceAction.create( createTemperatureChangePendingIntent(getTemperature() - 1), IconCompat.createWithResource(contextNonNull, R.drawable.ic_temp_down), ListBuilder.ICON_IMAGE, contextNonNull.getString(R.string.decrease_temperature) ) ) } } // TODO: Step 3.4, Review Pending Intent Creation. // PendingIntent that triggers an increase/decrease in temperature. private fun createTemperatureChangePendingIntent(value: Int): PendingIntent { val intent = Intent(ACTION_CHANGE_TEMPERATURE) .setClass(contextNonNull, TemperatureBroadcastReceiver::class.java) .putExtra(EXTRA_TEMPERATURE_VALUE, value) return PendingIntent.getBroadcast( contextNonNull, requestCode++, intent, PendingIntent.FLAG_UPDATE_CURRENT ) } companion object { private const val TAG = "TempSliceProvider" private var requestCode = 0 fun getUri(context: Context, path: String): Uri { return Uri.Builder() .scheme(ContentResolver.SCHEME_CONTENT) .authority(context.packageName) .appendPath(path) .build() } } }
apache-2.0
ffa57836e55284efbb4e5fb78aaca7ab
42.969136
110
0.660817
5.084226
false
false
false
false
macleod2486/AndroidSwissKnife
app/src/main/java/com/macleod2486/androidswissknife/MainActivity.kt
1
4897
/* AndroidSwissKnife Copyright (C) 2016 macleod2486 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.macleod2486.androidswissknife import android.content.pm.PackageManager import android.os.Bundle import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.view.MenuItem import android.view.View import android.widget.AdapterView.OnItemClickListener import android.widget.ArrayAdapter import android.widget.ListView import android.widget.Toast import androidx.appcompat.app.ActionBarDrawerToggle import com.macleod2486.androidswissknife.views.NFC import com.macleod2486.androidswissknife.views.Toggles class MainActivity : AppCompatActivity() { var index = 0 //Request codes val CAMERA_CODE = 0 lateinit private var drawer: DrawerLayout lateinit private var drawerToggle: ActionBarDrawerToggle //Different fragments var toggleFrag = Toggles() var nfcFrag = NFC() //Manages what the back button does override fun onBackPressed() { if (drawer.isDrawerOpen(GravityCompat.START)) { Log.i("Main", "Drawer closed") drawer.closeDrawers() } if (index == 0 && !toggleFrag.isAdded) { supportFragmentManager.beginTransaction().replace(R.id.container, toggleFrag, "main").commit() } else { super.onBackPressed() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Configures the drawer drawer = findViewById<View>(R.id.drawer) as DrawerLayout drawerToggle = object : ActionBarDrawerToggle(this, drawer, R.string.drawer_open, R.string.drawer_close) { override fun onDrawerClosed(view: View) { supportActionBar!!.setTitle(R.string.drawer_close) super.onDrawerClosed(view) } override fun onDrawerOpened(drawerView: View) { supportActionBar!!.setTitle(R.string.drawer_open) super.onDrawerOpened(drawerView) } } drawer.setDrawerListener(drawerToggle) drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) //Sets up the listview within the drawer val menuList = resources.getStringArray(R.array.menu) val list = findViewById<View>(R.id.optionList) as ListView list.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, menuList) list.onItemClickListener = OnItemClickListener { parent, view, position, id -> Log.i("MainActivity", "Position $position") if (position == 0) { index = 0 supportFragmentManager.beginTransaction().replace(R.id.container, toggleFrag, "toggles").commit() } else if (position == 1) { index = 1 supportFragmentManager.beginTransaction().replace(R.id.container, nfcFrag, "nfc").commit() } drawer.closeDrawers() } //Make the actionbar clickable to bring out the drawer supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setHomeButtonEnabled(true) //Displays the first fragment supportFragmentManager.beginTransaction().replace(R.id.container, toggleFrag, "toggles").commit() } //Toggles open the drawer override fun onOptionsItemSelected(item: MenuItem): Boolean { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawers() } else { drawer.openDrawer(GravityCompat.START) } return true } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { CAMERA_CODE -> { if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { toggleFrag.toggleLight() } else { Toast.makeText(this, "Need to enable all wifi permissions", Toast.LENGTH_SHORT).show() } return } } } }
gpl-3.0
b095f2ebb34b6c2ee9c674eec7c4443b
37.566929
115
0.666939
5.043254
false
false
false
false
http4k/http4k
http4k-cloudnative/src/test/kotlin/org/http4k/cloudnative/health/HealthTest.kt
1
3132
package org.http4k.cloudnative.health import com.natpryce.hamkrest.and import com.natpryce.hamkrest.assertion.assertThat import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.I_M_A_TEAPOT import org.http4k.core.Status.Companion.OK import org.http4k.core.Status.Companion.SERVICE_UNAVAILABLE import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasStatus import org.http4k.routing.bind import org.junit.jupiter.api.Test class HealthTest { private val health = Health(extraRoutes = arrayOf("/other" bind GET to { Response(I_M_A_TEAPOT) })) @Test fun liveness() { assertThat(health(Request(GET, "/liveness")), hasStatus(OK)) } @Test fun readiness() { assertThat(health(Request(GET, "/readiness")), hasStatus(OK).and(hasBody("success=true"))) } @Test fun `extra routes are callable`() { assertThat(health(Request(GET, "/other")), hasStatus(I_M_A_TEAPOT)) } @Test fun `readiness with extra checks`() { assertThat(Health(checks = listOf(check(true, "first"), check(false, "second")))(Request(GET, "/readiness")), hasStatus(SERVICE_UNAVAILABLE).and(hasBody("overall=false\nfirst=true\nsecond=false [foobar]"))) } @Test fun `readiness continues to run when check fails`() { assertThat(Health(checks = listOf(throws("boom"), check(true, "second")))(Request(GET, "/readiness")), hasStatus(SERVICE_UNAVAILABLE).and(hasBody("overall=false\nboom=false [foobar]\nsecond=true"))) } @Test fun `readiness with three checks`() { val checks = listOf(check(true, "first"), check(true, "second"), check(false, "third")) assertThat(Health(checks = checks)(Request(GET, "/readiness")), hasStatus(SERVICE_UNAVAILABLE).and(hasBody("overall=false\nfirst=true\nsecond=true\nthird=false [foobar]"))) } @Test fun `readiness with four checks`() { val checks = listOf(check(true, "first"), check(true, "second"), check(true, "third"), check(false, "fourth")) assertThat(Health(checks = checks)(Request(GET, "/readiness")), hasStatus(SERVICE_UNAVAILABLE).and(hasBody("overall=false\nfirst=true\nsecond=true\nthird=true\nfourth=false [foobar]"))) } @Test fun `readiness with three passing checks`() { val checks = listOf(check(true, "first"), check(true, "second"), check(true, "third")) assertThat(Health(checks = checks)(Request(GET, "/readiness")), hasStatus(OK).and(hasBody("overall=true\nfirst=true\nsecond=true\nthird=true"))) } private fun check(result: Boolean, name: String): ReadinessCheck = object : ReadinessCheck { override fun invoke(): ReadinessCheckResult = if (result) Completed(name) else Failed(name, "foobar") override val name: String = name } private fun throws(name: String): ReadinessCheck = object : ReadinessCheck { override fun invoke(): ReadinessCheckResult = throw Exception("foobar") override val name: String = name } }
apache-2.0
c25d2c53a63efef0d2763ca55795e2e8
38.64557
133
0.674649
3.838235
false
true
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/scenes/Scenes.kt
1
5676
package com.binarymonks.jj.core.scenes import com.badlogic.gdx.utils.Array import com.badlogic.gdx.utils.ObjectMap import com.binarymonks.jj.core.JJ import com.binarymonks.jj.core.api.ScenesAPI import com.binarymonks.jj.core.assets.AssetReference import com.binarymonks.jj.core.async.Bond import com.binarymonks.jj.core.async.OneTimeTask import com.binarymonks.jj.core.extensions.emptyGDXArray import com.binarymonks.jj.core.pools.Poolable import com.binarymonks.jj.core.pools.new import com.binarymonks.jj.core.pools.newArray import com.binarymonks.jj.core.pools.recycle import com.binarymonks.jj.core.specs.InstanceParams import com.binarymonks.jj.core.specs.SceneSpec import com.binarymonks.jj.core.specs.SceneSpecRef import com.binarymonks.jj.core.workshop.MasterFactory class Scenes : ScenesAPI { val masterFactory = MasterFactory() private val unresolvedSpecRefs: ObjectMap<String, SceneSpecRef> = ObjectMap() val sceneSpecs: ObjectMap<String, SceneSpec> = ObjectMap() private var dirty = false internal var rootScene: Scene? = null internal var scenesByGroupName = ObjectMap<String, Array<Scene>>() internal var inUpdate = false override fun instantiate(instanceParams: InstanceParams, scene: SceneSpec): Bond<Scene> { return instantiate(instanceParams, scene, rootScene) } internal fun instantiate(instanceParams: InstanceParams, scene: SceneSpec, parentScene: Scene?): Bond<Scene> { loadAssetsNow() val delayedCreate = new(CreateSceneFunction::class) @Suppress("UNCHECKED_CAST") val bond = new(Bond::class) as Bond<Scene> delayedCreate.set(scene, instanceParams, bond, parentScene) if (!JJ.B.physicsWorld.isUpdating) { JJ.tasks.addPrePhysicsTask(delayedCreate) } else { JJ.tasks.addPostPhysicsTask(delayedCreate) } return bond } override fun instantiate(instanceParams: InstanceParams, path: String): Bond<Scene> { loadAssetsNow() // To resolve any new SceneSpecRefs. return instantiate(instanceParams, sceneSpecs.get(path)) } internal fun instantiate(instanceParams: InstanceParams, path: String, parentScene: Scene?): Bond<Scene> { loadAssetsNow() // To resolve any new SceneSpecRefs. return instantiate(instanceParams, sceneSpecs.get(path), parentScene) } override fun instantiate(scene: SceneSpec): Bond<Scene> { return instantiate(InstanceParams.new(), scene) } override fun instantiate(path: String): Bond<Scene> { return instantiate(InstanceParams.new(), path) } override fun addSceneSpec(path: String, scene: SceneSpecRef) { unresolvedSpecRefs.put(path, scene) dirty = true } fun getScene(path: String): SceneSpec { return sceneSpecs.get(path) } override fun loadAssetsNow() { if (dirty) { var assets: Array<AssetReference> = getAllAssets() JJ.B.assets.loadNow(assets) unresolvedSpecRefs.forEach { sceneSpecs.put(it.key, it.value.resolve()) } unresolvedSpecRefs.clear() } dirty = false } private fun getAllAssets(): Array<AssetReference> { val assets: Array<AssetReference> = Array() for (entry in unresolvedSpecRefs) { assets.addAll(entry.value.getAssets()) } return assets } override fun destroyAll() { JJ.tasks.doOnceAfterPhysics { destroyAllScenes() } } override fun getScenesByGroupName(groupName: String, outResult: Array<Scene>){ if (scenesByGroupName.containsKey(groupName)) { outResult.addAll(scenesByGroupName[groupName]) } } /** * Adds scene to world. */ internal fun add(scene: Scene) { if (scene.groupName != null) { if (!scenesByGroupName.containsKey(scene.groupName)) { scenesByGroupName.put(scene.groupName, newArray()) } scenesByGroupName[scene.groupName].add(scene) } } /** *Removes a scene from the world. */ internal fun remove(scene: Scene) { if (scene.groupName != null) { scenesByGroupName[scene.groupName].removeValue(scene, true) } } fun update() { inUpdate = true rootScene?.update() inUpdate = false } internal fun destroyAllScenes() { for (entry in rootScene!!.sceneLayers.entries()) { val layerCopy: Array<Scene> = newArray() for (scene in entry.value) { layerCopy.add(scene) } for (scene in layerCopy) { scene.destroy() } recycle(layerCopy) } } } class CreateSceneFunction : OneTimeTask(), Poolable { internal var sceneSpec: SceneSpec? = null internal var instanceParams: InstanceParams? = null internal var bond: Bond<Scene>? = null internal var parentScene: Scene? = null operator fun set(sceneSpec: SceneSpec, instanceParams: InstanceParams, bond: Bond<Scene>, parentScene: Scene?) { this.sceneSpec = sceneSpec this.instanceParams = instanceParams.clone() this.bond = bond this.parentScene = parentScene } override fun doOnce() { val scene = JJ.B.scenes.masterFactory.createScene(sceneSpec!!, instanceParams!!, parentScene) bond!!.succeed(scene) recycle(instanceParams!!) recycle(this) } override fun reset() { sceneSpec = null instanceParams = null bond = null parentScene = null } }
apache-2.0
0ed1cb3556a8f18e24dc8ed2c93bb3be
31.44
116
0.654863
4.522709
false
false
false
false
squark-io/yggdrasil
yggdrasil-bootstrap/src/main/kotlin/io/squark/yggdrasil/bootstrap/NestedJarURLConnection.kt
1
2444
package io.squark.yggdrasil.bootstrap import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.Closeable import java.io.File import java.io.FileNotFoundException import java.io.InputStream import java.net.URL import java.net.URLConnection import java.util.jar.JarEntry import java.util.jar.JarFile import java.util.jar.JarInputStream internal class NestedJarURLConnection(url: URL) : URLConnection(url), Closeable { private var _inputStream: InputStream? = null override fun close() { _inputStream ?: _inputStream!!.close() } override fun connect() { if (url.protocol != "jar") { throw NotImplementedError("Protocol ${url.protocol} not supported") } val parts = url.path.split("!/") if (parts.size < 2 || parts.size > 3) { throw IllegalArgumentException( "URL should have jar part followed by entry and optional subentry (jar://path/to/jar.jar!/entry/in/jar!/sub/entry). Was \"${url.path}\"") } val jar = parts[0] val entry = parts[1] val jarFile = JarFile(File(URL(jar).file)) val jarEntry = jarFile.getJarEntry(entry) if (parts.size == 3) { val subEntryName = parts[2] if (!jarEntry.name.endsWith(".jar")) { throw IllegalArgumentException("Only JAR entries can hold subEntries. Was ${jarEntry.name}") } val jarInputStream = JarInputStream(jarFile.getInputStream(jarEntry)) var subEntry: JarEntry? = jarInputStream.nextJarEntry var bytes: ByteArray? = null while (subEntry != null) { if (subEntryName == subEntry.name) { val buffer = ByteArray(2048) val outputStream = ByteArrayOutputStream() var len = jarInputStream.read(buffer) while (len > 0) { outputStream.write(buffer, 0, len) len = jarInputStream.read(buffer) } bytes = outputStream.toByteArray() outputStream.close() break } subEntry = jarInputStream.nextJarEntry continue } if (bytes == null) { throw FileNotFoundException("${url}") } _inputStream = ByteArrayInputStream(bytes) jarInputStream.close() jarFile.close() } else { _inputStream = jarFile.getInputStream(jarEntry) } } override fun getInputStream(): InputStream? { return _inputStream } }
apache-2.0
b5c54807728ea04671e90e0c20296195
31.054054
145
0.636252
4.372093
false
false
false
false
prfarlow1/nytc-meet
app/src/main/kotlin/org/needhamtrack/nytc/settings/SharedPreferencesManager.kt
1
1011
package org.needhamtrack.nytc.settings import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager class SharedPreferencesManager private constructor(context: Context) : UserSettings { private val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) companion object { private val LAST_IP = "last_ip" private val ACCOUNT_NAME = "account_name" private var instance: UserSettings? = null fun getInstance(context: Context): UserSettings { return instance ?: SharedPreferencesManager(context).apply { instance = this } } } override var lastIp: String get() = preferences.getString(LAST_IP, "") set(value) = preferences.edit().putString(LAST_IP, value).apply() override var accountName: String get() = preferences.getString(ACCOUNT_NAME, "") set(value) = preferences.edit().putString(ACCOUNT_NAME, value).apply() }
mit
b5b5ecb6262612f851b339e3b6038ca2
36.444444
103
0.712166
4.884058
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/AvatarsDownloader.kt
1
2054
package de.westnordost.streetcomplete.data.osmnotes import android.util.Log import de.westnordost.osmapi.user.UserApi import de.westnordost.streetcomplete.ktx.format import de.westnordost.streetcomplete.ktx.saveToFile import java.io.File import java.io.IOException import java.net.URL import javax.inject.Inject import javax.inject.Named /** Downloads and stores the OSM avatars of users */ class AvatarsDownloader @Inject constructor( private val userApi: UserApi, @Named("AvatarsCacheDirectory") private val cacheDir: File ) { fun download(userIds: Collection<Long>) { if (!ensureCacheDirExists()) { Log.w(TAG, "Unable to create directories for avatars") return } val time = System.currentTimeMillis() for (userId in userIds) { val avatarUrl = getProfileImageUrl(userId) if (avatarUrl != null) { download(userId, avatarUrl) } } val seconds = (System.currentTimeMillis() - time) / 1000.0 Log.i(TAG, "Downloaded ${userIds.size} avatar images in ${seconds.format(1)}s") } private fun getProfileImageUrl(userId: Long): String? { return try { userApi.get(userId)?.profileImageUrl } catch (e : Exception) { Log.w(TAG, "Unable to query info for user id $userId") null } } /** download avatar for the given user and a known avatar url */ fun download(userId: Long, avatarUrl: String) { if (!ensureCacheDirExists()) return try { val avatarFile = File(cacheDir, "$userId") URL(avatarUrl).saveToFile(avatarFile) Log.d(TAG, "Downloaded file: ${avatarFile.path}") } catch (e: IOException) { Log.w(TAG, "Unable to download avatar for user id $userId") } } private fun ensureCacheDirExists(): Boolean { return cacheDir.exists() || cacheDir.mkdirs() } companion object { private const val TAG = "OsmAvatarsDownload" } }
gpl-3.0
a99d108c08f7dc9d3a0852286424eda3
31.09375
87
0.632425
4.398287
false
false
false
false
JetBrains/anko
anko/library/generated/sdk28/src/main/java/Services.kt
2
11493
@file:JvmName("Sdk28ServicesKt") package org.jetbrains.anko import android.content.Context import android.view.accessibility.AccessibilityManager import android.accounts.AccountManager import android.app.ActivityManager import android.app.AlarmManager import android.app.AppOpsManager import android.media.AudioManager import android.os.BatteryManager import android.bluetooth.BluetoothManager import android.hardware.camera2.CameraManager import android.view.accessibility.CaptioningManager import android.telephony.CarrierConfigManager import android.content.ClipboardManager import android.companion.CompanionDeviceManager import android.net.ConnectivityManager import android.hardware.ConsumerIrManager import android.app.admin.DevicePolicyManager import android.hardware.display.DisplayManager import android.app.DownloadManager import android.telephony.euicc.EuiccManager import android.hardware.fingerprint.FingerprintManager import android.os.HardwarePropertiesManager import android.hardware.input.InputManager import android.view.inputmethod.InputMethodManager import android.app.KeyguardManager import android.location.LocationManager import android.media.projection.MediaProjectionManager import android.media.session.MediaSessionManager import android.media.midi.MidiManager import android.app.usage.NetworkStatsManager import android.nfc.NfcManager import android.app.NotificationManager import android.net.nsd.NsdManager import android.os.PowerManager import android.print.PrintManager import android.content.RestrictionsManager import android.app.SearchManager import android.hardware.SensorManager import android.content.pm.ShortcutManager import android.os.storage.StorageManager import android.app.usage.StorageStatsManager import android.os.health.SystemHealthManager import android.telecom.TelecomManager import android.telephony.TelephonyManager import android.view.textclassifier.TextClassificationManager import android.media.tv.TvInputManager import android.app.UiModeManager import android.app.usage.UsageStatsManager import android.hardware.usb.UsbManager import android.os.UserManager import android.app.WallpaperManager import android.net.wifi.aware.WifiAwareManager import android.net.wifi.WifiManager import android.net.wifi.p2p.WifiP2pManager import android.view.WindowManager /** Returns the AccessibilityManager instance. **/ val Context.accessibilityManager: AccessibilityManager get() = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager /** Returns the AccountManager instance. **/ val Context.accountManager: AccountManager get() = getSystemService(Context.ACCOUNT_SERVICE) as AccountManager /** Returns the ActivityManager instance. **/ val Context.activityManager: ActivityManager get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager /** Returns the AlarmManager instance. **/ val Context.alarmManager: AlarmManager get() = getSystemService(Context.ALARM_SERVICE) as AlarmManager /** Returns the AppOpsManager instance. **/ val Context.appOpsManager: AppOpsManager get() = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager /** Returns the AudioManager instance. **/ val Context.audioManager: AudioManager get() = getSystemService(Context.AUDIO_SERVICE) as AudioManager /** Returns the BatteryManager instance. **/ val Context.batteryManager: BatteryManager get() = getSystemService(Context.BATTERY_SERVICE) as BatteryManager /** Returns the BluetoothManager instance. **/ val Context.bluetoothManager: BluetoothManager get() = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager /** Returns the CameraManager instance. **/ val Context.cameraManager: CameraManager get() = getSystemService(Context.CAMERA_SERVICE) as CameraManager /** Returns the CaptioningManager instance. **/ val Context.captioningManager: CaptioningManager get() = getSystemService(Context.CAPTIONING_SERVICE) as CaptioningManager /** Returns the CarrierConfigManager instance. **/ val Context.carrierConfigManager: CarrierConfigManager get() = getSystemService(Context.CARRIER_CONFIG_SERVICE) as CarrierConfigManager /** Returns the ClipboardManager instance. **/ val Context.clipboardManager: ClipboardManager get() = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager /** Returns the CompanionDeviceManager instance. **/ val Context.companionDeviceManager: CompanionDeviceManager get() = getSystemService(Context.COMPANION_DEVICE_SERVICE) as CompanionDeviceManager /** Returns the ConnectivityManager instance. **/ val Context.connectivityManager: ConnectivityManager get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager /** Returns the ConsumerIrManager instance. **/ val Context.consumerIrManager: ConsumerIrManager get() = getSystemService(Context.CONSUMER_IR_SERVICE) as ConsumerIrManager /** Returns the DevicePolicyManager instance. **/ val Context.devicePolicyManager: DevicePolicyManager get() = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager /** Returns the DisplayManager instance. **/ val Context.displayManager: DisplayManager get() = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager /** Returns the DownloadManager instance. **/ val Context.downloadManager: DownloadManager get() = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager /** Returns the EuiccManager instance. **/ val Context.euiccManager: EuiccManager get() = getSystemService(Context.EUICC_SERVICE) as EuiccManager /** Returns the FingerprintManager instance. **/ val Context.fingerprintManager: FingerprintManager get() = getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager /** Returns the HardwarePropertiesManager instance. **/ val Context.hardwarePropertiesManager: HardwarePropertiesManager get() = getSystemService(Context.HARDWARE_PROPERTIES_SERVICE) as HardwarePropertiesManager /** Returns the InputManager instance. **/ val Context.inputManager: InputManager get() = getSystemService(Context.INPUT_SERVICE) as InputManager /** Returns the InputMethodManager instance. **/ val Context.inputMethodManager: InputMethodManager get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager /** Returns the KeyguardManager instance. **/ val Context.keyguardManager: KeyguardManager get() = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager /** Returns the LocationManager instance. **/ val Context.locationManager: LocationManager get() = getSystemService(Context.LOCATION_SERVICE) as LocationManager /** Returns the MediaProjectionManager instance. **/ val Context.mediaProjectionManager: MediaProjectionManager get() = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager /** Returns the MediaSessionManager instance. **/ val Context.mediaSessionManager: MediaSessionManager get() = getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager /** Returns the MidiManager instance. **/ val Context.midiManager: MidiManager get() = getSystemService(Context.MIDI_SERVICE) as MidiManager /** Returns the NetworkStatsManager instance. **/ val Context.networkStatsManager: NetworkStatsManager get() = getSystemService(Context.NETWORK_STATS_SERVICE) as NetworkStatsManager /** Returns the NfcManager instance. **/ val Context.nfcManager: NfcManager get() = getSystemService(Context.NFC_SERVICE) as NfcManager /** Returns the NotificationManager instance. **/ val Context.notificationManager: NotificationManager get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager /** Returns the NsdManager instance. **/ val Context.nsdManager: NsdManager get() = getSystemService(Context.NSD_SERVICE) as NsdManager /** Returns the PowerManager instance. **/ val Context.powerManager: PowerManager get() = getSystemService(Context.POWER_SERVICE) as PowerManager /** Returns the PrintManager instance. **/ val Context.printManager: PrintManager get() = getSystemService(Context.PRINT_SERVICE) as PrintManager /** Returns the RestrictionsManager instance. **/ val Context.restrictionsManager: RestrictionsManager get() = getSystemService(Context.RESTRICTIONS_SERVICE) as RestrictionsManager /** Returns the SearchManager instance. **/ val Context.searchManager: SearchManager get() = getSystemService(Context.SEARCH_SERVICE) as SearchManager /** Returns the SensorManager instance. **/ val Context.sensorManager: SensorManager get() = getSystemService(Context.SENSOR_SERVICE) as SensorManager /** Returns the ShortcutManager instance. **/ val Context.shortcutManager: ShortcutManager get() = getSystemService(Context.SHORTCUT_SERVICE) as ShortcutManager /** Returns the StorageManager instance. **/ val Context.storageManager: StorageManager get() = getSystemService(Context.STORAGE_SERVICE) as StorageManager /** Returns the StorageStatsManager instance. **/ val Context.storageStatsManager: StorageStatsManager get() = getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager /** Returns the SystemHealthManager instance. **/ val Context.systemHealthManager: SystemHealthManager get() = getSystemService(Context.SYSTEM_HEALTH_SERVICE) as SystemHealthManager /** Returns the TelecomManager instance. **/ val Context.telecomManager: TelecomManager get() = getSystemService(Context.TELECOM_SERVICE) as TelecomManager /** Returns the TelephonyManager instance. **/ val Context.telephonyManager: TelephonyManager get() = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager /** Returns the TextClassificationManager instance. **/ val Context.textClassificationManager: TextClassificationManager get() = getSystemService(Context.TEXT_CLASSIFICATION_SERVICE) as TextClassificationManager /** Returns the TvInputManager instance. **/ val Context.tvInputManager: TvInputManager get() = getSystemService(Context.TV_INPUT_SERVICE) as TvInputManager /** Returns the UiModeManager instance. **/ val Context.uiModeManager: UiModeManager get() = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager /** Returns the UsageStatsManager instance. **/ val Context.usageStatsManager: UsageStatsManager get() = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager /** Returns the UsbManager instance. **/ val Context.usbManager: UsbManager get() = getSystemService(Context.USB_SERVICE) as UsbManager /** Returns the UserManager instance. **/ val Context.userManager: UserManager get() = getSystemService(Context.USER_SERVICE) as UserManager /** Returns the WallpaperManager instance. **/ val Context.wallpaperManager: WallpaperManager get() = getSystemService(Context.WALLPAPER_SERVICE) as WallpaperManager /** Returns the WifiAwareManager instance. **/ val Context.wifiAwareManager: WifiAwareManager get() = getSystemService(Context.WIFI_AWARE_SERVICE) as WifiAwareManager /** Returns the WifiManager instance. **/ val Context.wifiManager: WifiManager get() = getSystemService(Context.WIFI_SERVICE) as WifiManager /** Returns the WifiP2pManager instance. **/ val Context.wifiP2pManager: WifiP2pManager get() = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager /** Returns the WindowManager instance. **/ val Context.windowManager: WindowManager get() = getSystemService(Context.WINDOW_SERVICE) as WindowManager
apache-2.0
eee91aadc188dc20cf93ebf533f80efb
33.827273
94
0.806578
5.274438
false
false
false
false
arpitkh96/AmazeFileManager
app/src/test/java/com/amaze/filemanager/shadows/ShadowSmbUtil.kt
1
3924
/* * Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.shadows import com.amaze.filemanager.utils.SmbUtil import jcifs.context.SingletonContext import jcifs.smb.SmbException import jcifs.smb.SmbFile import org.mockito.Mockito.* import org.robolectric.annotation.Implementation import org.robolectric.annotation.Implements @Implements(SmbUtil::class) class ShadowSmbUtil { companion object { const val PATH_CANNOT_DELETE_FILE = "smb://user:[email protected]/access/denied.file" const val PATH_CANNOT_MOVE_FILE = "smb://user:[email protected]/cannot/move.file" const val PATH_CANNOT_RENAME_OLDFILE = "smb://user:[email protected]/cannot/rename.file.old" const val PATH_CAN_RENAME_OLDFILE = "smb://user:[email protected]/rename/old.file" const val PATH_CAN_RENAME_NEWFILE = "smb://user:[email protected]/rename/new.file" var mockDeleteAccessDenied: SmbFile? = null var mockDeleteDifferentNetwork: SmbFile? = null var mockCannotRenameOld: SmbFile? = null var mockCanRename: SmbFile? = null init { mockDeleteAccessDenied = createInternal(PATH_CANNOT_DELETE_FILE).also { `when`(it.delete()).thenThrow(SmbException("Access is denied.")) `when`(it.exists()).thenReturn(true) } mockDeleteDifferentNetwork = createInternal(PATH_CANNOT_MOVE_FILE).also { `when`(it.delete()).thenThrow(SmbException("Cannot rename between different trees")) `when`(it.exists()).thenReturn(true) } mockCanRename = createInternal(PATH_CAN_RENAME_OLDFILE).also { doNothing().`when`(it).renameTo(any()) } mockCannotRenameOld = createInternal(PATH_CANNOT_RENAME_OLDFILE) `when`(mockCannotRenameOld!!.renameTo(any())) .thenThrow(SmbException("Access is denied.")) `when`(mockCannotRenameOld!!.exists()).thenReturn(true) } /** * Shadows SmbUtil.create() * * @see SmbUtil.create */ @JvmStatic @Implementation fun create(path: String): SmbFile { return when (path) { PATH_CANNOT_DELETE_FILE -> mockDeleteAccessDenied!! PATH_CANNOT_MOVE_FILE -> mockDeleteDifferentNetwork!! PATH_CANNOT_RENAME_OLDFILE -> mockCannotRenameOld!! PATH_CAN_RENAME_OLDFILE -> mockCanRename!! else -> createInternal(path).also { doNothing().`when`(it).delete() `when`(it.exists()).thenReturn(false) } } } private fun createInternal(path: String): SmbFile { return mock(SmbFile::class.java).also { `when`(it.name).thenReturn(path.substring(path.lastIndexOf('/') + 1)) `when`(it.path).thenReturn(path) `when`(it.context).thenReturn(SingletonContext.getInstance()) } } } }
gpl-3.0
aceff80d50250be4c952bb8827034828
40.305263
107
0.640163
4.302632
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/building_type/AddBuildingType.kt
1
2523
package de.westnordost.streetcomplete.quests.building_type import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BUILDING class AddBuildingType : OsmFilterQuestType<BuildingType>() { // in the case of man_made, historic, military, aeroway and power, these tags already contain // information about the purpose of the building, so no need to force asking it // or question would be confusing as there is no matching reply in available answers // same goes (more or less) for tourism, amenity, leisure. See #1854, #1891, #3233 override val elementFilter = """ ways, relations with (building = yes or building = unclassified) and !man_made and !historic and !military and !power and !tourism and !attraction and !amenity and !leisure and !aeroway and !description and location != underground and abandoned != yes and abandoned != building and abandoned:building != yes and ruins != yes and ruined != yes """ override val commitMessage = "Add building types" override val wikiLink = "Key:building" override val icon = R.drawable.ic_quest_building override val questTypeAchievements = listOf(BUILDING) override fun getTitle(tags: Map<String, String>) = R.string.quest_buildingType_title override fun createForm() = AddBuildingTypeForm() override fun applyAnswerTo(answer: BuildingType, changes: StringMapChangesBuilder) { if (answer.osmKey == "man_made") { changes.delete("building") changes.add("man_made", answer.osmValue) } else if (answer.osmKey != "building") { changes.addOrModify(answer.osmKey, answer.osmValue) if(answer == BuildingType.ABANDONED) { changes.deleteIfExists("disused") } if(answer == BuildingType.RUINS && changes.getPreviousValue("disused") == "no") { changes.deleteIfExists("disused") } if(answer == BuildingType.RUINS && changes.getPreviousValue("abandoned") == "no") { changes.deleteIfExists("abandoned") } } else { changes.modify("building", answer.osmValue) } } }
gpl-3.0
f7be216ff159bd52b2d048ce025ad0d9
40.360656
97
0.654776
4.733583
false
false
false
false