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
GunoH/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/common/boundTypes.kt
2
2746
// 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.j2k.post.processing.inference.common import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.addToStdlib.safeAs sealed class ClassReference class DescriptorClassReference(val descriptor: ClassDescriptor) : ClassReference() class TypeParameterReference(val descriptor: TypeParameterDescriptor) : ClassReference() object NoClassReference : ClassReference() val ClassDescriptor.classReference: DescriptorClassReference get() = DescriptorClassReference(this) val ClassReference.descriptor: ClassDescriptor? get() = safeAs<DescriptorClassReference>()?.descriptor class TypeParameter(val boundType: BoundType, val variance: Variance) sealed class BoundType { abstract val label: BoundTypeLabel abstract val typeParameters: List<TypeParameter> companion object { val LITERAL = BoundTypeImpl(LiteralLabel, emptyList()) val STAR_PROJECTION = BoundTypeImpl(StarProjectionLabel, emptyList()) val NULL = BoundTypeImpl(NullLiteralLabel, emptyList()) } } class BoundTypeImpl( override val label: BoundTypeLabel, override val typeParameters: List<TypeParameter> ) : BoundType() class WithForcedStateBoundType( val original: BoundType, val forcedState: State ) : BoundType() { override val label: BoundTypeLabel get() = original.label override val typeParameters: List<TypeParameter> get() = original.typeParameters } fun BoundType.withEnhancementFrom(from: BoundType) = when (from) { is BoundTypeImpl -> this is WithForcedStateBoundType -> WithForcedStateBoundType(this, from.forcedState) } fun BoundType.enhanceWith(state: State?) = if (state != null) WithForcedStateBoundType(this, state) else this sealed class BoundTypeLabel class TypeVariableLabel(val typeVariable: TypeVariable) : BoundTypeLabel() class TypeParameterLabel(val typeParameter: TypeParameterDescriptor) : BoundTypeLabel() class GenericLabel(val classReference: ClassReference) : BoundTypeLabel() object NullLiteralLabel : BoundTypeLabel() object LiteralLabel : BoundTypeLabel() object StarProjectionLabel : BoundTypeLabel() fun TypeVariable.asBoundType(): BoundType = BoundTypeImpl(TypeVariableLabel(this), typeParameters) val BoundType.typeVariable: TypeVariable? get() = label.safeAs<TypeVariableLabel>()?.typeVariable val BoundType.isReferenceToClass: Boolean get() = label is TypeVariableLabel || label is GenericLabel
apache-2.0
fc6b5d41e561d18483a140c7d2f19782
35.144737
158
0.786599
5.181132
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeConstructorParameterPropertyFix.kt
2
3235
// 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 import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.* class MakeConstructorParameterPropertyFix( element: KtParameter, private val kotlinValVar: KotlinValVar, className: String? ) : KotlinQuickFixAction<KtParameter>(element) { override fun getFamilyName() = KotlinBundle.message("make.constructor.parameter.a.property.0", "") private val suffix = if (className != null) KotlinBundle.message("in.class.0", className) else "" override fun getText() = KotlinBundle.message("make.constructor.parameter.a.property.0", suffix) override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val element = element ?: return false return !element.hasValOrVar() } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return element.addBefore(kotlinValVar.createKeyword(KtPsiFactory(project))!!, element.nameIdentifier) element.addModifier(KtTokens.PRIVATE_KEYWORD) element.visibilityModifier()?.let { private -> editor?.apply { selectionModel.setSelection(private.startOffset, private.endOffset) caretModel.moveToOffset(private.endOffset) } } } companion object Factory : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val ktReference = Errors.UNRESOLVED_REFERENCE.cast(diagnostic).a as? KtNameReferenceExpression ?: return emptyList() val valOrVar = if (ktReference.getAssignmentByLHS() != null) KotlinValVar.Var else KotlinValVar.Val val ktParameter = ktReference.getPrimaryConstructorParameterWithSameName() ?: return emptyList() val containingClass = ktParameter.containingClass()!! val className = if (containingClass != ktReference.containingClass()) containingClass.nameAsSafeName.asString() else null return listOf(MakeConstructorParameterPropertyFix(ktParameter, valOrVar, className)) } } } fun KtNameReferenceExpression.getPrimaryConstructorParameterWithSameName(): KtParameter? { return nonStaticOuterClasses() .mapNotNull { ktClass -> ktClass.primaryConstructor?.valueParameters?.firstOrNull { it.name == getReferencedName() } } .firstOrNull() }
apache-2.0
58e75c6538e4a62a8dc08c81ad0629ca
48.030303
158
0.752396
5.126783
false
false
false
false
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/quickfixes/SourceOptionQuickFix.kt
2
11637
// 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.idea.maven.externalSystemIntegration.output.quickfixes import com.google.common.primitives.Bytes import com.intellij.build.events.BuildEvent import com.intellij.build.events.MessageEvent import com.intellij.build.events.impl.BuildIssueEventImpl import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.compiler.progress.BuildIssueContributor import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.JavaSdkVersion import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.jrt.JrtFileSystem import com.intellij.pom.Navigatable import com.intellij.pom.java.LanguageLevel import org.jetbrains.idea.maven.externalSystemIntegration.output.LogMessageType import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLogEntryReader import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLogEntryReader.MavenLogEntry import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLoggedEventParser import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenParsingContext import org.jetbrains.idea.maven.model.MavenId import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.project.MavenProjectBundle.message import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenLog import org.jetbrains.idea.maven.utils.MavenUtil import java.nio.charset.StandardCharsets import java.util.* import java.util.concurrent.CompletableFuture import java.util.function.Consumer class SourceOptionQuickFix : MavenLoggedEventParser { override fun supportsType(type: LogMessageType?): Boolean { return type == LogMessageType.ERROR } override fun checkLogLine(parentId: Any, parsingContext: MavenParsingContext, logLine: MavenLogEntry, logEntryReader: MavenLogEntryReader, messageConsumer: Consumer<in BuildEvent?>): Boolean { if (logLine.line.startsWith("Source option 5 is no longer supported.") || logLine.line.startsWith("Source option 1.5 is no longer supported.")) { val targetLine = logEntryReader.readLine() if (targetLine != null && !targetLine.line.startsWith("Target option 1.5 is no longer supported.")) { logEntryReader.pushBack() } val lastErrorProject = parsingContext.startedProjects.last() + ":" val failedProject = parsingContext.projectsInReactor.find { it.startsWith(lastErrorProject) } ?: return false val mavenProject = MavenProjectsManager.getInstance(parsingContext.ideaProject).findProject(MavenId(failedProject)) ?: return false val moduleJdk = MavenUtil.getModuleJdk(MavenProjectsManager.getInstance(parsingContext.ideaProject), mavenProject) ?: return false messageConsumer.accept( BuildIssueEventImpl(parentId, SourceLevelBuildIssue(logLine.line, logLine.line, mavenProject, moduleJdk), MessageEvent.Kind.ERROR)) return true } return false } } class SourceLevelBuildIssue(private val message: String, override val title: String, private val mavenProject: MavenProject, private val moduleJdk: Sdk) : BuildIssue { override val quickFixes: List<UpdateSourceLevelQuickFix> = Collections.singletonList(UpdateSourceLevelQuickFix(mavenProject)) override val description = createDescription() private fun createDescription() = "$message\n<br/>" + quickFixes.map { message("maven.source.level.not.supported.update", LanguageLevel.parse(moduleJdk.versionString)?.toJavaVersion(), it.id, it.mavenProject.displayName) }.joinToString("\n<br/>") override fun getNavigatable(project: Project): Navigatable { return mavenProject.file.let { OpenFileDescriptor(project, it) } } } typealias MessagePredicate = (String) -> Boolean /** * @deprecated use {@link JpsLanguageLevelQuickFix.kt */ class JpsReleaseVersionQuickFix : BuildIssueContributor { override fun createBuildIssue(project: Project, moduleNames: Collection<String>, title: String, message: String, kind: MessageEvent.Kind, virtualFile: VirtualFile?, navigatable: Navigatable?): BuildIssue? { val manager = MavenProjectsManager.getInstance(project) if (!manager.isMavenizedProject) return null if (moduleNames.size != 1) { return null } val moduleName = moduleNames.firstOrNull() ?: return null val predicates = CacheForCompilerErrorMessages.getPredicatesToCheck(project, moduleName) val failedId = extractFailedMavenId(project, moduleName) ?: return null val mavenProject = manager.findProject(failedId) ?: return null val moduleJdk = MavenUtil.getModuleJdk(manager, mavenProject) ?: return null if (predicates.any { it(message) }) return SourceLevelBuildIssue(title, message, mavenProject, moduleJdk) return null } private fun extractFailedMavenId(project: Project, moduleName: String): MavenId? { val module = ModuleManager.getInstance(project).findModuleByName(moduleName) ?: return null return MavenProjectsManager.getInstance(project).findProject(module)?.mavenId ?: return null } } class UpdateSourceLevelQuickFix(val mavenProject: MavenProject) : BuildIssueQuickFix { override val id = ID + mavenProject.mavenId.displayString override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { val languageLevelQuickFix = LanguageLevelQuickFixFactory.getInstance(project, mavenProject) return ProcessQuickFix.perform(languageLevelQuickFix, project, mavenProject) } companion object { val ID = "maven_quickfix_source_level_" } } object CacheForCompilerErrorMessages { private val key = "compiler.err.unsupported.release.version".encodeToByteArray() private val delimiter = ByteArray(2) init { delimiter[0] = 1 // SOH delimiter[1] = 0 // NUL byte } private val DEFAULT_CHECK = listOf<MessagePredicate>( { it.contains("source release") && it.contains("requires target release") }, { it.contains("invalid target release") }, { it.contains("release version") && it.contains("not supported") }, //en { it.contains("\u30EA\u30EA\u30FC\u30B9\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3") && it.contains("\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093") }, //ja { it.contains("\u4E0D\u652F\u6301\u53D1\u884C\u7248\u672C") } //zh_CN ) private val map = WeakHashMap<String, List<MessagePredicate>>() @JvmStatic fun connectToJdkListener(myProject: Project, disposable: Disposable) { myProject.messageBus.connect(disposable).subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, object : ProjectJdkTable.Listener { override fun jdkAdded(jdk: Sdk) { synchronized(map) { map.remove(jdk.name) } } override fun jdkRemoved(jdk: Sdk) { synchronized(map) { map.remove(jdk.name) } } override fun jdkNameChanged(jdk: Sdk, previousName: String) { synchronized(map) { val list = map[previousName] if (list != null) { map[jdk.name] = list } } } }) } fun getPredicatesToCheck(project: Project, moduleName: String): List<MessagePredicate> { val module = ModuleManager.getInstance(project).findModuleByName(moduleName) ?: return DEFAULT_CHECK val sdk = ModuleRootManager.getInstance(module).sdk ?: return DEFAULT_CHECK return synchronized(map) { map.getOrPut(sdk.name) { readFrom(sdk) } } } private fun readFrom(sdk: Sdk): List<MessagePredicate> { val version = JavaSdk.getInstance().getVersion(sdk) if (version == null || !version.isAtLeast(JavaSdkVersion.JDK_1_9)) { return DEFAULT_CHECK } try { val jrtLocalFile = sdk.homeDirectory?.let { JrtFileSystem.getInstance().getRootByLocal(it) } ?: return DEFAULT_CHECK val list = jrtLocalFile.findFileByRelativePath("jdk.compiler/com/sun/tools/javac/resources") ?.children ?.filter { it.name.startsWith("compiler") && it.name.endsWith(".class") } ?.mapNotNull { readFromBinaryFile(it) } ?.toList() if (list.isNullOrEmpty()) return DEFAULT_CHECK else return list } catch (e: Throwable) { MavenLog.LOG.warn(e) return DEFAULT_CHECK } } private fun readFromBinaryFile(file: VirtualFile?): MessagePredicate? { if (file == null) return null try { val allBytes = VfsUtil.loadBytes(file) val indexKey = Bytes.indexOf(allBytes, key) if (indexKey == -1) return null val startFrom = indexKey + key.size + 3 val endIndex = allBytes.findNextSOH(startFrom) if (endIndex == -1 || startFrom == endIndex) return null val message = String(allBytes, startFrom, endIndex - startFrom, StandardCharsets.UTF_8) return toMessagePredicate(message) } catch (e: Throwable) { MavenLog.LOG.warn(e) return null } } private fun toMessagePredicate(message: String): MessagePredicate { val first = message.substringBefore("{0}") val second = message.substringAfter("{0}") return { it.contains(first) && it.contains(second) } } private fun ByteArray.findNextSOH(startFrom: Int): Int { if (startFrom == -1) return -1 var i = startFrom while (i < this.size - 1) { if (this[i] == delimiter[0] && this[i + 1] == delimiter[1]) { return i } i++ } return -1 } } object ProcessQuickFix { fun perform(languageLevelQuickFix: LanguageLevelQuickFix?, project: Project, mavenProject: MavenProject): CompletableFuture<*> { if (languageLevelQuickFix == null) { Notification(MavenUtil.MAVEN_NOTIFICATION_GROUP, "", message("maven.quickfix.cannot.update.source.level.module.not.found", mavenProject.displayName), NotificationType.INFORMATION).notify(project) return CompletableFuture.completedFuture(null) } val moduleJdk = MavenUtil.getModuleJdk(MavenProjectsManager.getInstance(project), languageLevelQuickFix.mavenProject) if (moduleJdk == null) { Notification(MavenUtil.MAVEN_NOTIFICATION_GROUP, "", message("maven.quickfix.cannot.update.source.level.module.not.found", languageLevelQuickFix.mavenProject.displayName), NotificationType.INFORMATION).notify(project) return CompletableFuture.completedFuture(null) } languageLevelQuickFix.perform(LanguageLevel.parse(moduleJdk.versionString)!!) return CompletableFuture.completedFuture(null) } }
apache-2.0
9237ee23436b7d34ca324a8d4af9ff27
41.01083
137
0.711781
4.554599
false
false
false
false
roylanceMichael/yaclib
core/src/main/java/org/roylance/yaclib/core/utilities/TypeScriptUtilities.kt
1
12188
package org.roylance.yaclib.core.utilities import com.google.gson.GsonBuilder import org.roylance.yaclib.YaclibModel import org.roylance.yaclib.core.models.NPMPackage import org.roylance.yaclib.core.services.IProjectBuilderServices import java.io.File import java.nio.file.Paths import java.util.* object TypeScriptUtilities : IProjectBuilderServices { private val neverTarThisDirectory = object : HashSet<String>() { init { add("node_modules") } } private val gson = GsonBuilder().setPrettyPrinting().create() const val ProtobufJsVersion = "5.0.1" const val Proto2TypeScriptVersion = "2.2.0" val protobufJsDependencyBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( ProtobufJsVersion).setGroup("protobufjs").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val roylanceCommonDependencyBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^${YaclibStatics.RoylanceCommonVersion}.0").setGroup("roylance.common").setType( YaclibModel.DependencyType.TYPESCRIPT)!! val proto2TypeScriptDependencyBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( Proto2TypeScriptVersion).setGroup("proto2typescript").setType( YaclibModel.DependencyType.TYPESCRIPT)!! val baseTypeScriptKit = object : ArrayList<YaclibModel.Dependency>() { init { add(protobufJsDependencyBuilder.build()) add(roylanceCommonDependencyBuilder.build()) } } val angularDependencyBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^1.5.7").setGroup("angular").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val angularRouteBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^1.5.7").setGroup("angular-route").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val bytebufferBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^5.0.1").setGroup("bytebuffer").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val longBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^3.2.0").setGroup("long").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val bootstrapBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^3.3.6").setGroup("bootstrap").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val d3Builder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^3.5.17").setGroup("d3").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val dagreD3Builder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^0.4.17").setGroup("dagre-d3").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val fontAwesomeBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^4.6.3").setGroup("font-awesome").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val jqueryBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^3.0.0").setGroup("jquery").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val webpackStreamBuilder = YaclibModel.Dependency.newBuilder().setThirdPartyDependencyVersion( "^3.2.0").setGroup("webpack-stream").setType(YaclibModel.DependencyType.TYPESCRIPT)!! val baseServerTypeScriptKit = object : ArrayList<YaclibModel.Dependency>() { init { add(angularDependencyBuilder.build()) add(angularRouteBuilder.build()) add(bytebufferBuilder.build()) add(longBuilder.build()) add(bootstrapBuilder.build()) add(d3Builder.build()) add(dagreD3Builder.build()) add(fontAwesomeBuilder.build()) add(jqueryBuilder.build()) add(protobufJsDependencyBuilder.build()) add(webpackStreamBuilder.build()) } } fun buildDependency(dependency: YaclibModel.Dependency): String { if (dependency.type == YaclibModel.DependencyType.INTERNAL) { if (dependency.hasNpmRepository() && dependency.npmRepository.npmScope.isNotEmpty()) { return """"${buildFullName(dependency)}": "${buildVersion(dependency)}" """ } else if (dependency.hasNpmRepository() && dependency.npmRepository.repositoryType == YaclibModel.RepositoryType.ARTIFACTORY_NPM) { val dependencyUrl = JavaUtilities.buildRepositoryUrl(dependency.npmRepository) val fileName = ArtifactoryUtilities.buildTarUrl(dependency) return """"${buildFullName(dependency)}": "$dependencyUrl/$fileName" """ } else { return """"${buildFullName(dependency)}": "${buildVersion(dependency)}" """ } } if (dependency.hasNpmRepository() && dependency.npmRepository.npmScope.isNotEmpty()) { return """"${buildFullName(dependency)}": "${buildVersion(dependency)}" """ } else if (dependency.npmRepository.repositoryType == YaclibModel.RepositoryType.ARTIFACTORY_NPM) { return """"${buildFullName(dependency)}": "${dependency.npmRepository.url}" """ } else { return """"${buildFullName(dependency)}": "${buildVersion(dependency)}" """ } } fun buildTypeScriptOutput(referencePath: String, exportFactoryName: String, exportedJS: String): String { return """ /// <reference path="$referencePath" /> declare var dcodeIO:any; $exportedJS export var $exportFactoryName = _root; """ } fun getFirstGroup(group: String): String { val groups = group.split(".") return groups.first() } fun buildNpmModel(location: String): NPMPackage? { val actualFile = File(location, NPMUtilities.PackageNameJson) if (!actualFile.exists()) { return null } return gson.fromJson(actualFile.readText(), NPMPackage::class.java) } override fun incrementVersion(location: String, dependency: YaclibModel.Dependency): YaclibModel.ProcessReport { val projectModel = buildNpmModel( location) ?: return YaclibModel.ProcessReport.getDefaultInstance() val splitVersion = projectModel.version!!.split(".") if (splitVersion.size < 3) { return YaclibModel.ProcessReport.getDefaultInstance() } val majorVersion = splitVersion[0] val newMinorVersion = projectModel.version?.substring(majorVersion.length) projectModel.version = projectModel.version File(location, NPMUtilities.PackageNameJson).writeText(gson.toJson(projectModel)) return YaclibModel.ProcessReport.newBuilder() .setNewMajor(majorVersion) .setNewMinor(newMinorVersion) .setContent(projectModel.version) .build() } override fun updateDependencyVersion(location: String, otherDependency: YaclibModel.Dependency): YaclibModel.ProcessReport { val projectModel = buildNpmModel( location) ?: return YaclibModel.ProcessReport.getDefaultInstance() val currentKey = buildFullName(otherDependency).trim() if (projectModel.dependencies.containsKey(currentKey)) { projectModel.dependencies[currentKey] = buildVersion(otherDependency) } File(location, NPMUtilities.PackageNameJson).writeText(gson.toJson(projectModel)) return YaclibModel.ProcessReport .newBuilder() .build() } override fun getVersion(location: String): YaclibModel.ProcessReport { val projectModel = buildNpmModel( location) ?: return YaclibModel.ProcessReport.getDefaultInstance() val splitVersion = projectModel.version!!.split(".") if (splitVersion.size < 3) { return YaclibModel.ProcessReport.getDefaultInstance() } val majorVersion = splitVersion[0] val minorVersion = projectModel.version?.substring(majorVersion.length) return YaclibModel.ProcessReport.newBuilder() .setNewMinor(minorVersion) .setNewMajor(majorVersion) .setContent(projectModel.version).build() } override fun setVersion(location: String, dependency: YaclibModel.Dependency): YaclibModel.ProcessReport { val projectModel = buildNpmModel( location) ?: return YaclibModel.ProcessReport.getDefaultInstance() projectModel.version = buildVersion(dependency) File(location, NPMUtilities.PackageNameJson).writeText(gson.toJson(projectModel)) return YaclibModel.ProcessReport.newBuilder() .setNewMajor(dependency.majorVersion) .setNewMinor(dependency.minorVersion) .setContent(projectModel.version) .build() } override fun clean(location: String): YaclibModel.ProcessReport { return YaclibModel.ProcessReport.getDefaultInstance() } override fun build(location: String): YaclibModel.ProcessReport { return FileProcessUtilities.executeProcess(location, InitUtilities.TypeScriptCompiler, "") } override fun buildPackage(location: String, dependency: YaclibModel.Dependency): YaclibModel.ProcessReport { return YaclibModel.ProcessReport.getDefaultInstance() } override fun publish(location: String, dependency: YaclibModel.Dependency, apiKey: String): YaclibModel.ProcessReport { val normalLogs = StringBuilder() val errorLogs = StringBuilder() if (dependency.hasNpmRepository() && dependency.npmRepository.repositoryType == YaclibModel.RepositoryType.ARTIFACTORY_NPM && dependency.npmRepository.url.isNotEmpty()) { val tarFileName = Paths.get(location, ArtifactoryUtilities.buildTarFileName(dependency)).toString() val result = FileProcessUtilities.createTarFromDirectory(location, tarFileName, neverTarThisDirectory) if (result) { normalLogs.appendln("successfully created $tarFileName") } else { errorLogs.appendln("error creating $tarFileName") } val scriptToRun = ArtifactoryUtilities.buildUploadTarGzScript(location, dependency) val actualScriptFile = File(location, ArtifactoryUtilities.UploadScriptName) actualScriptFile.writeText(scriptToRun) FileProcessUtilities.executeProcess(location, InitUtilities.Chmod, "${InitUtilities.ChmodExecutable} $tarFileName") FileProcessUtilities.executeProcess(location, InitUtilities.Chmod, "${InitUtilities.ChmodExecutable} $actualScriptFile") println("running upload") val deployReport = FileProcessUtilities.executeProcess(location, actualScriptFile.toString(), "") normalLogs.appendln(deployReport.normalOutput) errorLogs.appendln(deployReport.errorOutput) println("ran upload upload") } else { val publishReport = FileProcessUtilities.executeProcess(location, InitUtilities.NPM, "publish") normalLogs.appendln(publishReport.normalOutput) errorLogs.appendln(publishReport.errorOutput) } return YaclibModel.ProcessReport.newBuilder().setNormalOutput( normalLogs.toString()).setErrorOutput(errorLogs.toString()).build() } override fun restoreDependencies(location: String, doAnonymously: Boolean): YaclibModel.ProcessReport { if (doAnonymously) { FileProcessUtilities.executeProcess(location, InitUtilities.Move, "~/.npmrc ~/.npmrctmp") } val result = FileProcessUtilities.executeProcess(location, InitUtilities.NPM, "install") if (doAnonymously) { FileProcessUtilities.executeProcess(location, InitUtilities.Move, "~/.npmrctmp ~/.npmrc") } return result } private fun buildVersion(dependency: YaclibModel.Dependency): String { if (dependency.type == YaclibModel.DependencyType.INTERNAL) { return "${dependency.majorVersion}.${dependency.minorVersion}.0" } else { return dependency.thirdPartyDependencyVersion } } private fun buildFullName(dependency: YaclibModel.Dependency): String { if (dependency.type == YaclibModel.DependencyType.INTERNAL) { if (dependency.hasNpmRepository() && dependency.npmRepository.npmScope.isNotEmpty()) { return "${dependency.npmRepository.npmScope}/${dependency.group}.${dependency.name}" } else { return "${dependency.group}.${dependency.name}" } } if (dependency.hasNpmRepository() && dependency.npmRepository.npmScope.isNotEmpty()) { return "${dependency.npmRepository.npmScope}/${dependency.group}" } else { return dependency.group } } }
mit
5c45e20afddb650a3374afe4c38a8a9a
39.765886
138
0.734493
5.095318
false
false
false
false
ayatk/biblio
infrastructure/database/src/main/java/com/ayatk/biblio/infrastructure/database/entity/EpisodeEntity.kt
1
1760
/* * Copyright (c) 2016-2018 ayatk. * * 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.ayatk.biblio.infrastructure.database.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.PrimaryKey import java.util.UUID @Entity( tableName = "episode", foreignKeys = [ ForeignKey( parentColumns = arrayOf("code"), childColumns = arrayOf("novel_code"), entity = NovelEntity::class ), ForeignKey( parentColumns = arrayOf("id"), childColumns = arrayOf("index_id"), entity = IndexEntity::class ) ] ) data class EpisodeEntity( /** * codeとpageとindexのIDをハイフンでつなぎ合わせてUUIDに変換したもの */ @PrimaryKey var id: UUID, @ColumnInfo(name = "novel_code", index = true) var code: String, /** * codeとpageをハイフンでつなぎ合わせてUUIDに変換したもの */ @ColumnInfo(name = "index_id", index = true) var indexId: UUID, @ColumnInfo(index = true) var page: Int, var subtitle: String, @ColumnInfo(name = "prev_content") var prevContent: String, var content: String, @ColumnInfo(name = "after_content") var afterContent: String )
apache-2.0
07dc174e0a9147305ccb78f7b0e44892
23.231884
75
0.699761
3.723831
false
false
false
false
octarine-noise/BetterFoliage
src/main/kotlin/mods/octarinecore/client/render/Model.kt
1
5901
package mods.octarinecore.client.render import mods.octarinecore.common.* import mods.octarinecore.minmax import mods.octarinecore.replace import net.minecraft.util.EnumFacing import java.lang.Math.max import java.lang.Math.min /** * Vertex UV coordinates * * Zero-centered: coordinates fall between (-0.5, 0.5) (inclusive) */ data class UV(val u: Double, val v: Double) { companion object { val topLeft = UV(-0.5, -0.5) val topRight = UV(0.5, -0.5) val bottomLeft = UV(-0.5, 0.5) val bottomRight = UV(0.5, 0.5) } val rotate: UV get() = UV(v, -u) fun rotate(n: Int) = when(n % 4) { 0 -> copy() 1 -> UV(v, -u) 2 -> UV(-u, -v) else -> UV(-v, u) } fun clamp(minU: Double = -0.5, maxU: Double = 0.5, minV: Double = -0.5, maxV: Double = 0.5) = UV(u.minmax(minU, maxU), v.minmax(minV, maxV)) fun mirror(mirrorU: Boolean, mirrorV: Boolean) = UV(if (mirrorU) -u else u, if (mirrorV) -v else v) } /** * Model vertex * * @param[xyz] x, y, z coordinates * @param[uv] u, v coordinates * @param[aoShader] [Shader] instance to use with AO rendering * @param[flatShader] [Shader] instance to use with non-AO rendering */ data class Vertex(val xyz: Double3 = Double3(0.0, 0.0, 0.0), val uv: UV = UV(0.0, 0.0), val aoShader: Shader = NoShader, val flatShader: Shader = NoShader) /** * Model quad */ data class Quad(val v1: Vertex, val v2: Vertex, val v3: Vertex, val v4: Vertex) { val verts = arrayOf(v1, v2, v3, v4) inline fun transformV(trans: (Vertex)->Vertex): Quad = transformVI { vertex, idx -> trans(vertex) } inline fun transformVI(trans: (Vertex, Int)->Vertex): Quad = Quad(trans(v1, 0), trans(v2, 1), trans(v3, 2), trans(v4, 3)) val normal: Double3 get() = (v2.xyz - v1.xyz).cross(v4.xyz - v1.xyz).normalize fun move(trans: Double3) = transformV { it.copy(xyz = it.xyz + trans) } fun move(trans: Pair<Double, EnumFacing>) = move(Double3(trans.second) * trans.first) fun scale (scale: Double) = transformV { it.copy(xyz = it.xyz * scale) } fun scale (scale: Double3) = transformV { it.copy(xyz = Double3(it.xyz.x * scale.x, it.xyz.y * scale.y, it.xyz.z * scale.z)) } fun scaleUV (scale: Double) = transformV { it.copy(uv = UV(it.uv.u * scale, it.uv.v * scale)) } fun rotate(rot: Rotation) = transformV { it.copy(xyz = it.xyz.rotate(rot), aoShader = it.aoShader.rotate(rot), flatShader = it.flatShader.rotate(rot)) } fun rotateUV(n: Int) = transformV { it.copy(uv = it.uv.rotate(n)) } fun clampUV(minU: Double = -0.5, maxU: Double = 0.5, minV: Double = -0.5, maxV: Double = 0.5) = transformV { it.copy(uv = it.uv.clamp(minU, maxU, minV, maxV)) } fun mirrorUV(mirrorU: Boolean, mirrorV: Boolean) = transformV { it.copy(uv = it.uv.mirror(mirrorU, mirrorV)) } fun setAoShader(factory: ShaderFactory, predicate: (Vertex, Int)->Boolean = { v, vi -> true }) = transformVI { vertex, idx -> if (!predicate(vertex, idx)) vertex else vertex.copy(aoShader = factory(this@Quad, vertex)) } fun setFlatShader(factory: ShaderFactory, predicate: (Vertex, Int)->Boolean = { v, vi -> true }) = transformVI { vertex, idx -> if (!predicate(vertex, idx)) vertex else vertex.copy(flatShader = factory(this@Quad, vertex)) } fun setFlatShader(shader: Shader) = transformVI { vertex, idx -> vertex.copy(flatShader = shader) } val flipped: Quad get() = Quad(v4, v3, v2, v1) fun cycleVertices(n: Int) = when(n % 4) { 1 -> Quad(v2, v3, v4, v1) 2 -> Quad(v3, v4, v1, v2) 3 -> Quad(v4, v1, v2, v3) else -> this.copy() } } /** * Model. The basic unit of rendering blocks with OctarineCore. * * The model should be positioned so that (0,0,0) is the block center. * The block extends to (-0.5, 0.5) in all directions (inclusive). */ class Model() { constructor(other: List<Quad>) : this() { quads.addAll(other) } val quads = mutableListOf<Quad>() fun Quad.add() = quads.add(this) fun Iterable<Quad>.addAll() = forEach { quads.add(it) } fun transformQ(trans: (Quad)->Quad) = quads.replace(trans) fun transformV(trans: (Vertex)->Vertex) = quads.replace{ it.transformV(trans) } fun verticalRectangle(x1: Double, z1: Double, x2: Double, z2: Double, yBottom: Double, yTop: Double) = Quad( Vertex(Double3(x1, yBottom, z1), UV.bottomLeft), Vertex(Double3(x2, yBottom, z2), UV.bottomRight), Vertex(Double3(x2, yTop, z2), UV.topRight), Vertex(Double3(x1, yTop, z1), UV.topLeft) ) fun horizontalRectangle(x1: Double, z1: Double, x2: Double, z2: Double, y: Double): Quad { val xMin = min(x1, x2); val xMax = max(x1, x2) val zMin = min(z1, z2); val zMax = max(z1, z2) return Quad( Vertex(Double3(xMin, y, zMin), UV.topLeft), Vertex(Double3(xMin, y, zMax), UV.bottomLeft), Vertex(Double3(xMax, y, zMax), UV.bottomRight), Vertex(Double3(xMax, y, zMin), UV.topRight) ) } fun faceQuad(face: EnumFacing): Quad { val base = face.vec * 0.5 val top = faceCorners[face.ordinal].topLeft.first.vec * 0.5 val left = faceCorners[face.ordinal].topLeft.second.vec * 0.5 return Quad( Vertex(base + top + left, UV.topLeft), Vertex(base - top + left, UV.bottomLeft), Vertex(base - top - left, UV.bottomRight), Vertex(base + top - left, UV.topRight) ) } } val fullCube = Model().apply { forgeDirs.forEach { faceQuad(it) .setAoShader(faceOrientedAuto(corner = cornerAo(it.axis), edge = null)) .setFlatShader(faceOrientedAuto(corner = cornerFlat, edge = null)) .add() } }
mit
79ec5f9f4ad3e9d74bbf4f28afab5dd3
39.424658
130
0.603288
3.167472
false
false
false
false
pkleimann/livingdoc2
livingdoc-converters/src/main/kotlin/org/livingdoc/converters/collection/Tokenizer.kt
1
665
package org.livingdoc.converters.collection import org.livingdoc.api.conversion.ConversionException internal object Tokenizer { fun tokenizeToStringList(value: String, delimiter: String = ",") = value.split(delimiter).map { it.trim() } fun tokenizeToMap(value: String, pairDelimiter: String = ";", valueDelimiter: String = ","): Map<String, String> { val pairs = tokenizeToStringList(value, pairDelimiter) return pairs.map { val split = tokenizeToStringList(it, valueDelimiter) if (split.size != 2) throw ConversionException("'$it' is not a valid Pair") split[0] to split[1] }.toMap() } }
apache-2.0
d9030822f723d50233251c7dc8c0b1b4
38.117647
118
0.670677
4.433333
false
false
false
false
google/android-auto-companion-app
android/app/src/main/kotlin/com/google/automotive/companion/TrustedDeviceMethodChannel.kt
1
14367
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.automotive.companion import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Handler import android.os.IBinder import android.os.Looper import android.provider.Settings import android.util.Log import androidx.core.content.getSystemService import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import com.google.android.libraries.car.connectionservice.FeatureManagerServiceBinder import com.google.android.libraries.car.trustagent.FeatureManager import com.google.android.libraries.car.trusteddevice.TrustedDeviceFeature import com.google.android.libraries.car.trusteddevice.TrustedDeviceFeature.EnrollmentError import io.flutter.embedding.engine.dart.DartExecutor import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import java.text.SimpleDateFormat import java.time.Instant import java.util.Date import java.util.Locale import java.util.TimeZone import java.util.UUID import java.util.concurrent.atomic.AtomicInteger import kotlinx.coroutines.runBlocking /** * The flutter method channel used to transfer data between Flutter UI and Android library. */ class TrustedDeviceMethodChannel( private val context: Context, lifecycle: Lifecycle, dartExecutor: DartExecutor ) : MethodChannel.MethodCallHandler, DefaultLifecycleObserver { private val sharedPref = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) private val notificationManager: NotificationManager private val notificationIdCounter: AtomicInteger private var trustedDeviceFeature: TrustedDeviceFeature? = null // Maps device ID to a Car with that ID. private val methodChannel = MethodChannel(dartExecutor, TrustedDeviceConstants.CHANNEL) private val uiHandler = Handler(Looper.getMainLooper()) private enum class UnlockStatus { // The status is not known UNKNOWN, // The unlock is in progress INPROGRESS, // The unlock was successful SUCCESS, // An error was encountered during the unlock process ERROR, } /** The possible errors that can result from a phone-initiated enrollment in trusted device. */ private enum class TrustedDeviceEnrollmentError { UNKNOWN, CAR_NOT_CONNECTED, PASSCODE_NOT_SET, } private val serviceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { val connectedDeviceService = (service as FeatureManagerServiceBinder).getService() trustedDeviceFeature = connectedDeviceService.getFeatureManager(TrustedDeviceFeature::class.java)?.apply { registerCallback(trustedDeviceCallback) isPasscodeRequired = true } } override fun onServiceDisconnected(name: ComponentName?) { trustedDeviceFeature?.unregisterCallback(trustedDeviceCallback) trustedDeviceFeature = null } } private val trustedDeviceCallback = TrustedDeviceCallback() private inner class TrustedDeviceCallback : TrustedDeviceFeature.Callback { override fun onEnrollmentRequested(carId: UUID) {} override fun onEnrollmentSuccess(carId: UUID, initiatedFromCar: Boolean) { val name = (trustedDeviceFeature as FeatureManager).getConnectedCarNameById(carId) if (initiatedFromCar) { pushTrustedDeviceEnrollmentNotification(name) } invokeMethodOnMainThread( TrustedDeviceConstants.ON_TRUST_AGENT_ENROLLMENT_COMPLETED, convertCarInfoToMap(carId.toString(), name) ) } override fun onUnenroll(carId: UUID, initiatedFromCar: Boolean) { if (initiatedFromCar) { val name = (trustedDeviceFeature as FeatureManager).getConnectedCarNameById(carId) pushTrustedDeviceUnenrollmentNotification(name) } invokeMethodOnMainThread( TrustedDeviceConstants.ON_TRUST_AGENT_UNENROLLED, mapOf(ConnectedDeviceConstants.CAR_ID_KEY to carId.toString()), ) } override fun onEnrollmentFailure(carId: UUID, error: EnrollmentError) { Log.e(TAG, "Encountered error during trusted device enrollment: error code $error") val convertedError = when (error) { EnrollmentError.PASSCODE_NOT_SET -> TrustedDeviceEnrollmentError.PASSCODE_NOT_SET EnrollmentError.CAR_NOT_CONNECTED -> TrustedDeviceEnrollmentError.CAR_NOT_CONNECTED else -> TrustedDeviceEnrollmentError.UNKNOWN } val arguments = convertCarInfoToMap(carId.toString(), name = "").toMutableMap().apply { put( TrustedDeviceConstants.TRUST_AGENT_ENROLLMENT_ERROR_KEY, convertedError.ordinal.toString() ) } invokeMethodOnMainThread(TrustedDeviceConstants.ON_TRUST_AGENT_ENROLLMENT_ERROR, arguments) } override fun onUnlockingStarted(carId: UUID) {} override fun onUnlockingSuccess(carId: UUID) { Log.i(TAG, "Successfully unlocked car with id $carId") val name = (trustedDeviceFeature as FeatureManager).getConnectedCarNameById(carId) if (shouldShowUnlockNotification(carId)) { pushTrustedDeviceUnlockNotification(name) } invokeMethodOnMainThread( TrustedDeviceConstants.ON_UNLOCK_STATUS_CHANGED, convertUnlockStatusToMap(carId, UnlockStatus.SUCCESS) ) } override fun onUnlockingFailure(carId: UUID) { invokeMethodOnMainThread( TrustedDeviceConstants.ON_UNLOCK_STATUS_CHANGED, convertUnlockStatusToMap(carId, UnlockStatus.ERROR) ) } } /** Generates a notification ID. */ private fun nextNotificationId(): Int { return notificationIdCounter.getAndIncrement() } private fun createTrustedDeviceNotificationChannel() { val channel = NotificationChannel( TRUSTED_DEVICE_NOTIFICATION_CHANNEL_ID, context.getString(R.string.trusted_device_notification_channel_name), NotificationManager.IMPORTANCE_DEFAULT ) notificationManager.createNotificationChannel(channel) } private fun pushTrustedDeviceEnrollmentNotification(carName: String?) { val name = carName ?: TRUSTED_DEVICE_NOTIFICATION_DEFAULT_CAR_NAME pushNotification( title = context.getString(R.string.trusted_device_enrollment_notification_title), text = context.getString(R.string.trusted_device_enrollment_notification_text, name), notificationId = nextNotificationId() ) } private fun pushTrustedDeviceUnenrollmentNotification(carName: String?) { val name = carName ?: TRUSTED_DEVICE_NOTIFICATION_DEFAULT_CAR_NAME pushNotification( title = context.getString(R.string.trusted_device_unenrollment_notification_title), text = context.getString(R.string.trusted_device_unenrollment_notification_text, name), notificationId = nextNotificationId() ) } private fun pushTrustedDeviceUnlockNotification(carName: String?) { val name = carName ?: TRUSTED_DEVICE_NOTIFICATION_DEFAULT_CAR_NAME pushNotification( title = null, text = context.getString(R.string.trusted_device_unlock_notification_text, name), notificationId = nextNotificationId() ) } private fun pushNotification( title: String?, text: String, notificationId: Int ) { // Open the application whenever the notification is pressed. val notificationIntent = createNotificationIntent(context) val pendingIntent = PendingIntent.getActivity( context, /* requestCode= */ 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE ) val notification = Notification.Builder(context, TRUSTED_DEVICE_NOTIFICATION_CHANNEL_ID) .setContentTitle(title) .setContentText(text) .setSmallIcon(R.drawable.ic_notification) .setShowWhen(true) .setContentIntent(pendingIntent) .setStyle(Notification.BigTextStyle().bigText(text)) .setAutoCancel(true) .build() notificationManager.notify(notificationId, notification) } init { lifecycle.addObserver(this) methodChannel.setMethodCallHandler(this) context.bindService( ConnectedDeviceService.createIntent(context), serviceConnection, Context.BIND_AUTO_CREATE) notificationManager = context.getSystemService<NotificationManager>()!! createTrustedDeviceNotificationChannel() notificationIdCounter = AtomicInteger(context.foregroundServiceNotificationId + 1) } override fun onDestroy(owner: LifecycleOwner) { context.unbindService(serviceConnection) notificationManager.deleteNotificationChannel(TRUSTED_DEVICE_NOTIFICATION_CHANNEL_ID) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { TrustedDeviceConstants.ENROLL_TRUST_AGENT -> enrollTrustAgent(call) TrustedDeviceConstants.STOP_TRUST_AGENT_ENROLLMENT -> stopTrustAgentEnrollment(call) TrustedDeviceConstants.GET_UNLOCK_HISTORY -> getUnlockHistory(call, result) TrustedDeviceConstants.IS_TRUSTED_DEVICE_ENROLLED -> result.success(isTrustedDeviceEnrolled(call)) TrustedDeviceConstants.OPEN_SECURITY_SETTINGS -> openSecuritySettings() TrustedDeviceConstants.SET_DEVICE_UNLOCK_REQUIRED -> setDeviceUnlockRequired(call) TrustedDeviceConstants.IS_DEVICE_UNLOCK_REQUIRED -> result.success(isDeviceUnlockRequired(call)) TrustedDeviceConstants.SHOULD_SHOW_UNLOCK_NOTIFICATION -> result.success(shouldShowUnlockNotification(call)) TrustedDeviceConstants.SET_SHOW_UNLOCK_NOTIFICATION -> setShowUnlockNotification(call) else -> result.notImplemented() } } private fun setDeviceUnlockRequired(call: MethodCall) { trustedDeviceFeature?.setDeviceUnlockRequired( call.argumentDeviceId, call.argumentIsDeviceUnlockRequired ) } private fun isDeviceUnlockRequired(call: MethodCall): Boolean { return trustedDeviceFeature?.isDeviceUnlockRequired(call.argumentDeviceId) ?: true } private fun shouldShowUnlockNotification(call: MethodCall): Boolean { return shouldShowUnlockNotification(call.argumentDeviceId) } private fun shouldShowUnlockNotification(carId: UUID): Boolean = sharedPref.getBoolean(NEED_PUSH_UNLOCK_NOTIFICATION_KEY_PREFIX + carId.toString(), true) private fun setShowUnlockNotification(call: MethodCall) { val deviceId = call.argumentDeviceId val shouldShow = call.argumentShowShowUnlockNotification sharedPref .edit() .putBoolean(NEED_PUSH_UNLOCK_NOTIFICATION_KEY_PREFIX + deviceId, shouldShow) .apply() } private fun isTrustedDeviceEnrolled(call: MethodCall): Boolean { val deviceId = call.argumentDeviceId val manager = trustedDeviceFeature if (manager == null) { return false } return runBlocking { manager.isEnabled(deviceId) } } private fun enrollTrustAgent(call: MethodCall) { val deviceId = call.argumentDeviceId if (trustedDeviceFeature == null) { Log.e(TAG, "ENROLL_TRUST_AGENT: service has not been bound") return } trustedDeviceFeature?.enroll(deviceId) } private fun stopTrustAgentEnrollment(call: MethodCall) { if (trustedDeviceFeature == null) { Log.e(TAG, "STOP_ENROLL_TRUST_AGENT: Service has not been bound. Ignore.") return } val deviceId = call.argumentDeviceId runBlocking { trustedDeviceFeature?.stopEnrollment(deviceId) } } private fun getUnlockHistory(call: MethodCall, result: MethodChannel.Result) { val deviceId = call.argumentDeviceId if (trustedDeviceFeature == null) { Log.e(TAG, "GET_UNLOCK_HISTORY: Service has not been bound. Ignore.") return } val instants = runBlocking { trustedDeviceFeature?.getUnlockHistory(deviceId) } if (instants == null) { Log.e(TAG, "GET_UNLOCK_HISTORY: Unlock history of car: $deviceId is null") result.success(emptyList<Instant>()) return } // create ISO8601 date format val iso8601Format = SimpleDateFormat(ISO_8601_DATE_FORMAT, Locale.US) iso8601Format.timeZone = TimeZone.getTimeZone("UTC") @Suppress("NewApi") // Date.from() is supported with Java8 desugaring result.success(instants.map { instant -> iso8601Format.format(Date.from(instant)) }) } private fun openSecuritySettings() { context.startActivity(Intent(Settings.ACTION_SECURITY_SETTINGS)) } private fun convertUnlockStatusToMap(carId: UUID, unlockStatus: UnlockStatus) = mapOf( ConnectedDeviceConstants.CAR_ID_KEY to carId.toString(), TrustedDeviceConstants.UNLOCK_STATUS_KEY to unlockStatus.ordinal.toString() ) private fun invokeMethodOnMainThread(methodName: String, args: Any = "") { uiHandler.post { methodChannel.invokeMethod(methodName, args) } } companion object { private const val TAG = "TrustedDeviceMethodChannel" // Default car name substitution in notification text. private const val TRUSTED_DEVICE_NOTIFICATION_DEFAULT_CAR_NAME = "your car" private const val TRUSTED_DEVICE_NOTIFICATION_CHANNEL_ID = "trusted_device_notification_channel" private const val SHARED_PREF = "com.google.android.apps.internal.auto.embedded.trusteddeviceapp.TrustedDeviceMethodChannel" /** * `SharedPreferences` key for if a notification should be shown for a car when it is unlocked. * * This value is appended to the car id to differentiate. */ private const val NEED_PUSH_UNLOCK_NOTIFICATION_KEY_PREFIX = "need_push_unlock_notification_key" private const val ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm'Z'" } }
apache-2.0
a1dcd1c10a3539c76220b2f5427d35a8
35.372152
100
0.747894
4.842265
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketInSettings.kt
1
2103
/* * Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.packet import com.mcmoonlake.api.isCombatOrLaterVer import com.mcmoonlake.api.ofValuable import com.mcmoonlake.api.ofValuableNotNull import com.mcmoonlake.api.wrapper.EnumChatVisibility import com.mcmoonlake.api.wrapper.EnumMainHand data class PacketInSettings( var locale: String, var viewDistance: Int, var chatVisibility: EnumChatVisibility, var chatColor: Boolean, var skinDisplayed: Int, var hand: EnumMainHand? ) : PacketInBukkitAbstract("PacketPlayInSettings") { @Deprecated("") constructor() : this("en_US", 12, EnumChatVisibility.FULL, true, 0x80, null) override fun read(data: PacketBuffer) { locale = data.readString() viewDistance = data.readByte().toInt() chatVisibility = ofValuableNotNull(data.readVarInt()) chatColor = data.readBoolean() skinDisplayed = data.readByte().toInt() if(isCombatOrLaterVer) hand = ofValuable(data.readVarInt(), EnumMainHand.RIGHT) } override fun write(data: PacketBuffer) { data.writeString(locale) data.writeByte(viewDistance) data.writeVarInt(chatVisibility.value) data.writeBoolean(chatColor) data.writeByte(skinDisplayed) if(isCombatOrLaterVer) data.writeVarInt(hand?.value ?: EnumMainHand.RIGHT.value) } }
gpl-3.0
dd619d3e8f5684b4ec0825a01e4f26dc
35.894737
80
0.711365
4.427368
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/tracker/importer/internal/TrackerImporterFileResourcesPostCall.kt
1
9360
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.tracker.importer.internal import dagger.Reusable import io.reactivex.Single import javax.inject.Inject import org.hisp.dhis.android.core.enrollment.NewTrackerImporterEnrollment import org.hisp.dhis.android.core.event.NewTrackerImporterEvent import org.hisp.dhis.android.core.fileresource.FileResource import org.hisp.dhis.android.core.fileresource.internal.FileResourceHelper import org.hisp.dhis.android.core.fileresource.internal.FileResourcePostCall import org.hisp.dhis.android.core.fileresource.internal.FileResourceValue import org.hisp.dhis.android.core.maintenance.D2Error import org.hisp.dhis.android.core.trackedentity.NewTrackerImporterTrackedEntity import org.hisp.dhis.android.core.trackedentity.NewTrackerImporterTrackedEntityAttributeValue import org.hisp.dhis.android.core.trackedentity.internal.NewTrackerImporterPayload import org.hisp.dhis.android.core.trackedentity.internal.NewTrackerImporterPayloadWrapper @Reusable internal class TrackerImporterFileResourcesPostCall @Inject internal constructor( private val fileResourcePostCall: FileResourcePostCall, private val fileResourceHelper: FileResourceHelper ) { fun uploadFileResources( payloadWrapper: NewTrackerImporterPayloadWrapper ): Single<NewTrackerImporterPayloadWrapper> { return Single.create { emitter -> val fileResources = fileResourceHelper.getUploadableFileResources() if (fileResources.isEmpty()) { emitter.onSuccess(payloadWrapper) } else { emitter.onSuccess( payloadWrapper.copy( deleted = uploadPayloadFileResources(payloadWrapper.deleted, fileResources), updated = uploadPayloadFileResources(payloadWrapper.updated, fileResources) ) ) } } } private fun uploadPayloadFileResources( payload: NewTrackerImporterPayload, fileResources: List<FileResource> ): NewTrackerImporterPayload { val uploadedAttributes = uploadAttributes(payload.trackedEntities, payload.enrollments, fileResources) val uploadedDataValues = uploadDataValues(payload.events, fileResources) return payload.copy( trackedEntities = uploadedAttributes.first.toMutableList(), enrollments = uploadedAttributes.second.toMutableList(), events = uploadedDataValues.first.toMutableList(), fileResourcesMap = uploadedAttributes.third + uploadedDataValues.second ) } private fun uploadAttributes( entities: List<NewTrackerImporterTrackedEntity>, enrollments: List<NewTrackerImporterEnrollment>, fileResources: List<FileResource> ): Triple<List<NewTrackerImporterTrackedEntity>, List<NewTrackerImporterEnrollment>, Map<String, List<String>>> { // Map from original uid to new uid (the uid from the server) val uploadedFileResourcesMap = mutableMapOf<String, FileResource>() // Map from entity/enrollment uid to the list of associated fileResources val fileResourcesByEntity = mutableMapOf<String, List<String>>() val successfulEntities: List<NewTrackerImporterTrackedEntity> = entities.mapNotNull { entity -> catchErrorToNull { val updatedAttributes = getUpdatedAttributes( entityUid = entity.uid()!!, attributeValues = entity.trackedEntityAttributeValues(), fileResources = fileResources, uploadedFileResources = uploadedFileResourcesMap, fileResourcesByEntity = fileResourcesByEntity ) entity.toBuilder().trackedEntityAttributeValues(updatedAttributes).build() } } val successfulEnrollments: List<NewTrackerImporterEnrollment> = enrollments.mapNotNull { enrollment -> catchErrorToNull { val updatedAttributes = getUpdatedAttributes( entityUid = enrollment.uid()!!, attributeValues = enrollment.attributes(), fileResources = fileResources, uploadedFileResources = uploadedFileResourcesMap, fileResourcesByEntity = fileResourcesByEntity ) enrollment.toBuilder().attributes(updatedAttributes).build() } } return Triple(successfulEntities, successfulEnrollments, fileResourcesByEntity) } private fun getUpdatedAttributes( entityUid: String, attributeValues: List<NewTrackerImporterTrackedEntityAttributeValue>?, fileResources: List<FileResource>, uploadedFileResources: MutableMap<String, FileResource>, fileResourcesByEntity: MutableMap<String, List<String>> ): List<NewTrackerImporterTrackedEntityAttributeValue>? { val entityFileResources = mutableListOf<String>() val updatedAttributes = attributeValues?.map { attributeValue -> fileResourceHelper.findAttributeFileResource(attributeValue, fileResources)?.let { fileResource -> val uploadedFileResource = uploadedFileResources[fileResource.uid()] val newUid = if (uploadedFileResource != null) { uploadedFileResource.uid()!! } else { val fValue = FileResourceValue.AttributeValue(attributeValue.trackedEntityAttribute()!!) fileResourcePostCall.uploadFileResource(fileResource, fValue)?.also { uploadedFileResources[fileResource.uid()!!] = fileResource.toBuilder().uid(it).build() } } newUid?.let { entityFileResources.add(it) } attributeValue.toBuilder().value(newUid).build() } ?: attributeValue } if (entityFileResources.isNotEmpty()) { fileResourcesByEntity[entityUid] = entityFileResources } return updatedAttributes } private fun uploadDataValues( events: List<NewTrackerImporterEvent>, fileResources: List<FileResource> ): Pair<List<NewTrackerImporterEvent>, Map<String, List<String>>> { val uploadedFileResources = mutableMapOf<String, List<String>>() val successfulEvents = events.mapNotNull { event -> catchErrorToNull { val eventFileResources = mutableListOf<String>() val updatedDataValues = event.trackedEntityDataValues()?.map { dataValue -> fileResourceHelper.findDataValueFileResource(dataValue, fileResources)?.let { fileResource -> val fValue = FileResourceValue.EventValue(dataValue.dataElement()!!) val newUid = fileResourcePostCall.uploadFileResource(fileResource, fValue)?.also { eventFileResources.add(it) } dataValue.toBuilder().value(newUid).build() } ?: dataValue } if (eventFileResources.isNotEmpty()) { uploadedFileResources[event.uid()!!] = eventFileResources } event.toBuilder().trackedEntityDataValues(updatedDataValues).build() } } return Pair(successfulEvents, uploadedFileResources) } @Suppress("TooGenericExceptionCaught") private fun <T> catchErrorToNull(f: () -> T): T? { return try { f() } catch (e: java.lang.RuntimeException) { null } catch (e: RuntimeException) { null } catch (e: D2Error) { null } } }
bsd-3-clause
ba35c7535c444725cc22bed58ce63ee0
46.51269
117
0.67735
5.774213
false
false
false
false
google-developer-training/basic-android-kotlin-compose-training-bus-schedule-app
app/src/main/java/com/example/busschedule/ui/BusScheduleScreens.kt
1
10157
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.busschedule.ui import androidx.activity.compose.BackHandler import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.busschedule.R import com.example.busschedule.data.BusSchedule import com.example.busschedule.ui.theme.BusScheduleTheme import java.text.SimpleDateFormat import java.util.* enum class BusScheduleScreens { FullSchedule, RouteSchedule } @Composable fun BusScheduleApp( modifier: Modifier = Modifier, viewModel: BusScheduleViewModel = viewModel(factory = BusScheduleViewModel.factory) ) { val navController = rememberNavController() val fullScheduleTitle = stringResource(R.string.full_schedule) var topAppBarTitle by remember { mutableStateOf(fullScheduleTitle) } val fullSchedule by viewModel.getFullSchedule().collectAsState(emptyList()) val onBackHandler = { topAppBarTitle = fullScheduleTitle navController.navigateUp() } Scaffold( topBar = { BusScheduleTopAppBar( title = topAppBarTitle, canNavigateBack = navController.previousBackStackEntry != null, onBackClick = { onBackHandler() } ) } ) { innerPadding -> NavHost( navController = navController, modifier = modifier.padding(innerPadding), startDestination = BusScheduleScreens.FullSchedule.name ) { composable(BusScheduleScreens.FullSchedule.name) { FullScheduleScreen( busSchedules = fullSchedule, onScheduleClick = { busStopName -> navController.navigate( "${BusScheduleScreens.RouteSchedule.name}/$busStopName" ) topAppBarTitle = busStopName } ) } val busRouteArgument = "busRoute" composable( route = BusScheduleScreens.RouteSchedule.name + "/{$busRouteArgument}", arguments = listOf(navArgument(busRouteArgument) { type = NavType.StringType }) ) { backStackEntry -> val stopName = backStackEntry.arguments?.getString(busRouteArgument) ?: error("busRouteArgument cannot be null") val routeSchedule by viewModel.getScheduleFor(stopName).collectAsState(emptyList()) RouteScheduleScreen( stopName = stopName, busSchedules = routeSchedule, onBack = { onBackHandler() } ) } } } } @Composable fun FullScheduleScreen( busSchedules: List<BusSchedule>, onScheduleClick: (String) -> Unit, modifier: Modifier = Modifier, ) { BusScheduleScreen( busSchedules = busSchedules, onScheduleClick = onScheduleClick, modifier = modifier ) } @Composable fun RouteScheduleScreen( stopName: String, busSchedules: List<BusSchedule>, modifier: Modifier = Modifier, onBack: () -> Unit = {} ) { BackHandler { onBack() } BusScheduleScreen( busSchedules = busSchedules, modifier = modifier, stopName = stopName ) } @Composable fun BusScheduleScreen( busSchedules: List<BusSchedule>, modifier: Modifier = Modifier, stopName: String? = null, onScheduleClick: ((String) -> Unit)? = null, ) { val stopNameText = if (stopName == null) { stringResource(R.string.stop_name) } else { "$stopName ${stringResource(R.string.route_stop_name)}" } Column(modifier) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text(stopNameText) Text(stringResource(R.string.arrival_time)) } Divider() BusScheduleDetails( busSchedules = busSchedules, onScheduleClick = onScheduleClick ) } } /* * Composable for BusScheduleDetails which show list of bus schedule * When [onScheduleClick] is null, [stopName] is replaced with placeholder * as it is assumed [stopName]s are the same as shown * in the list heading display in [BusScheduleScreen] */ @Composable fun BusScheduleDetails( busSchedules: List<BusSchedule>, modifier: Modifier = Modifier, onScheduleClick: ((String) -> Unit)? = null ) { LazyColumn(modifier = modifier, contentPadding = PaddingValues(vertical = 8.dp)) { items( items = busSchedules, key = { busSchedule -> busSchedule.id } ) { schedule -> Row( modifier = Modifier .fillMaxWidth() .clickable(enabled = onScheduleClick != null) { onScheduleClick?.invoke(schedule.stopName) } .padding(vertical = 16.dp, horizontal = 16.dp), horizontalArrangement = Arrangement.SpaceBetween ) { if (onScheduleClick == null) { Text( text = "--", style = MaterialTheme.typography.body1.copy( fontSize = 20.sp, fontWeight = FontWeight(300) ), textAlign = TextAlign.Center, modifier = Modifier.weight(1f) ) } else { Text( text = schedule.stopName, style = MaterialTheme.typography.body1.copy( fontSize = 20.sp, fontWeight = FontWeight(300) ) ) } Text( text = SimpleDateFormat("h:mm a", Locale.getDefault()) .format(Date(schedule.arrivalTimeInMillis.toLong() * 1000)), style = MaterialTheme.typography.body1.copy( fontSize = 20.sp, fontWeight = FontWeight(600) ), textAlign = TextAlign.End, modifier = Modifier.weight(2f) ) } } } } @Composable fun BusScheduleTopAppBar( title: String, canNavigateBack: Boolean, onBackClick: () -> Unit, modifier: Modifier = Modifier ) { if (canNavigateBack) { TopAppBar( title = { Text(title) }, navigationIcon = { IconButton(onClick = onBackClick) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = stringResource( R.string.back ) ) } }, modifier = modifier ) } else { TopAppBar( title = { Text(title) }, modifier = modifier ) } } @Preview(showBackground = true) @Composable fun FullScheduleScreenPreview() { BusScheduleTheme { FullScheduleScreen( busSchedules = List(3) { index -> BusSchedule( index, "Main Street", 111111 ) }, onScheduleClick = {} ) } } @Preview(showBackground = true) @Composable fun RouteScheduleScreenPreview() { BusScheduleTheme { RouteScheduleScreen( stopName = "Main Street", busSchedules = List(3) { index -> BusSchedule( index, "Main Street", 111111 ) } ) } }
apache-2.0
444c38f456bb7140123e59f9d86458d3
32.19281
99
0.5987
5.312238
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter5/5.13.CustomDsl.kt
4
2102
import com.sun.org.apache.xpath.internal.compiler.Keywords fun equals(first: Any, second: Any): Unit { if (first != second) throw RuntimeException("$first was not equal to $second") } fun Any.shouldEqual(other: Any): Unit { if (this != other) throw RuntimeException("$this was not equal to $other") } infix fun <E> Collection<E>.shouldContain(element: E): Unit { if (!this.contains(element)) throw RuntimeException("Collection did not contain $element") } interface Matcher<T> { fun test(lhs: T): Unit infix fun or(other: Matcher<T>): Matcher<T> = object : Matcher<T> { override fun test(lhs: T) { try { [email protected](lhs) } catch (e: RuntimeException) { other.test(lhs) } } } } fun <T> contain(rhs: T) = object : Matcher<Collection<T>> { override fun test(lhs: Collection<T>): Unit { if (!lhs.contains(rhs)) throw RuntimeException("Collection did not contain $rhs") } } fun <T> beEmpty() = object : Matcher<Collection<T>> { override fun test(lhs: Collection<T>) { if (lhs.isNotEmpty()) throw RuntimeException("Collection should be empty") } } infix fun <T> T.should(matcher: Matcher<T>) { matcher.test(this) } class CollectionMatchers<T>(val collection: Collection<T>) { fun contain(rhs: T): Unit { if (!collection.contains(rhs)) throw RuntimeException("Collection did not contain $rhs") } fun notContain(rhs: T): Unit { if (collection.contains(rhs)) throw RuntimeException("Collection should not contain $rhs") } fun haveSizeLessThan(size: Int): Unit { if (collection.size >= size) throw RuntimeException("Collection should have size less than $size") } } infix fun <T> Collection<T>.should(fn: CollectionMatchers<T>.() -> Unit) { val matchers = CollectionMatchers(this) matchers.fn() } fun dsltest() { val listOfNames = listOf("george", "harry", "william") listOfNames should (contain("george") or beEmpty()) listOfNames should { contain("george") contain("harry") notContain("francois") haveSizeLessThan(4) } }
mit
770ba61f55ad437cede392d34dc5fd03
23.453488
75
0.660324
3.662021
false
true
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/system/ApplicationServiceImpl.kt
1
13183
package top.zbeboy.isy.service.system import org.jooq.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import org.springframework.util.ObjectUtils import org.springframework.util.StringUtils import top.zbeboy.isy.domain.Tables.APPLICATION import top.zbeboy.isy.domain.Tables.COLLEGE_APPLICATION import top.zbeboy.isy.domain.tables.daos.ApplicationDao import top.zbeboy.isy.domain.tables.pojos.Application import top.zbeboy.isy.domain.tables.records.ApplicationRecord import top.zbeboy.isy.service.plugin.DataTablesPlugin import top.zbeboy.isy.service.util.SQLQueryUtils import top.zbeboy.isy.web.bean.system.application.ApplicationBean import top.zbeboy.isy.web.bean.tree.TreeBean import top.zbeboy.isy.web.util.DataTablesUtils import java.util.* import javax.annotation.Resource /** * Created by zbeboy 2017-11-17 . **/ @Service("applicationService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) open class ApplicationServiceImpl @Autowired constructor(dslContext: DSLContext) : DataTablesPlugin<ApplicationBean>(), ApplicationService { private val create: DSLContext = dslContext @Resource open lateinit var applicationDao: ApplicationDao @Transactional(propagation = Propagation.REQUIRED, readOnly = false) override fun save(application: Application) { applicationDao.insert(application) } override fun update(application: Application) { applicationDao.update(application) } override fun deletes(ids: List<String>) { applicationDao.deleteById(ids) } override fun findById(id: String): Application { return applicationDao.findById(id) } override fun findByPid(pid: String): List<Application> { var applications: List<Application> = ArrayList() val applicationRecords = create.selectFrom<ApplicationRecord>(APPLICATION) .where(APPLICATION.APPLICATION_PID.eq(pid)) .orderBy(APPLICATION.APPLICATION_SORT.asc()) .fetch() if (applicationRecords.isNotEmpty) { applications = applicationRecords.into(Application::class.java) } return applications } override fun findByPidAndCollegeId(pid: String, collegeId: Int): List<Application> { var applications: List<Application> = ArrayList() val records = create.select() .from(APPLICATION) .join(COLLEGE_APPLICATION) .on(APPLICATION.APPLICATION_ID.eq(COLLEGE_APPLICATION.APPLICATION_ID)) .where(APPLICATION.APPLICATION_PID.eq(pid).and(COLLEGE_APPLICATION.COLLEGE_ID.eq(collegeId))) .orderBy(APPLICATION.APPLICATION_SORT.asc()) .fetch() if (records.isNotEmpty) { applications = records.into(Application::class.java) } return applications } override fun findInPids(pids: List<String>): Result<ApplicationRecord> { return create.selectFrom<ApplicationRecord>(APPLICATION) .where(APPLICATION.APPLICATION_PID.`in`(pids)) .fetch() } override fun findInIdsAndPid(ids: List<String>, pid: String): Result<ApplicationRecord> { return create.selectFrom<ApplicationRecord>(APPLICATION) .where(APPLICATION.APPLICATION_ID.`in`(ids).and(APPLICATION.APPLICATION_PID.eq(pid))) .orderBy(APPLICATION.APPLICATION_SORT) .fetch() } override fun findAllByPage(dataTablesUtils: DataTablesUtils<ApplicationBean>): Result<Record> { return dataPagingQueryAll(dataTablesUtils, create, APPLICATION) } override fun countAll(): Int { return statisticsAll(create, APPLICATION) } override fun countByCondition(dataTablesUtils: DataTablesUtils<ApplicationBean>): Int { return statisticsWithCondition(dataTablesUtils, create, APPLICATION) } override fun findByApplicationName(applicationName: String): List<Application> { return applicationDao.fetchByApplicationName(applicationName) } override fun findByApplicationNameNeApplicationId(applicationName: String, applicationId: String): Result<ApplicationRecord> { return create.selectFrom<ApplicationRecord>(APPLICATION) .where(APPLICATION.APPLICATION_NAME.eq(applicationName).and(APPLICATION.APPLICATION_ID.ne(applicationId))) .fetch() } override fun findByApplicationEnName(applicationEnName: String): List<Application> { return applicationDao.fetchByApplicationEnName(applicationEnName) } override fun findByApplicationEnNameNeApplicationId(applicationEnName: String, applicationId: String): Result<ApplicationRecord> { return create.selectFrom<ApplicationRecord>(APPLICATION) .where(APPLICATION.APPLICATION_EN_NAME.eq(applicationEnName).and(APPLICATION.APPLICATION_ID.ne(applicationId))) .fetch() } override fun findByApplicationUrl(applicationUrl: String): List<Application> { return applicationDao.fetchByApplicationUrl(applicationUrl) } override fun findByApplicationUrlNeApplicationId(applicationUrl: String, applicationId: String): Result<ApplicationRecord> { return create.selectFrom<ApplicationRecord>(APPLICATION) .where(APPLICATION.APPLICATION_URL.eq(applicationUrl).and(APPLICATION.APPLICATION_ID.ne(applicationId))) .fetch() } override fun findByApplicationCode(applicationCode: String): List<Application> { return applicationDao.fetchByApplicationCode(applicationCode) } override fun findByApplicationCodeNeApplicationId(applicationCode: String, applicationId: String): Result<ApplicationRecord> { return create.selectFrom<ApplicationRecord>(APPLICATION) .where(APPLICATION.APPLICATION_CODE.eq(applicationCode).and(APPLICATION.APPLICATION_ID.ne(applicationId))) .fetch() } override fun getApplicationJson(pid: String): List<TreeBean> { return bindingDataToJson(pid) } override fun getApplicationJsonByCollegeId(pid: String, collegeId: Int): List<TreeBean> { return bindingDataToJson(pid, collegeId) } /** * 绑定数据到treeBean * * @param id 父id * @return list treeBean */ private fun bindingDataToJson(id: String): List<TreeBean> { val applications = findByPid(id) val treeBeens: MutableList<TreeBean> = ArrayList() if (!ObjectUtils.isEmpty(applications)) { applications .map { // pid = 0 TreeBean(it.applicationName, bindingDataToJson(it.applicationId), it.applicationId) } .forEach { treeBeens.add(it) } } return treeBeens } /** * 绑定数据到treeBean * * @param id 父id * @param collegeId 院id * @return list treeBean */ private fun bindingDataToJson(id: String, collegeId: Int): List<TreeBean> { val applications = findByPidAndCollegeId(id, collegeId) val treeBeens: MutableList<TreeBean> = ArrayList() if (!ObjectUtils.isEmpty(applications)) { applications .map { // pid = 0 TreeBean(it.applicationName, bindingDataToJson(it.applicationId, collegeId), it.applicationId) } .forEach { treeBeens.add(it) } } return treeBeens } /** * 应用数据全局搜索条件 * * @param dataTablesUtils datatable工具类 * @return 搜索条件 */ override fun searchCondition(dataTablesUtils: DataTablesUtils<ApplicationBean>): Condition? { var a: Condition? = null val search = dataTablesUtils.search if (!ObjectUtils.isEmpty(search)) { val applicationName = StringUtils.trimWhitespace(search!!.getString("applicationName")) val applicationEnName = StringUtils.trimWhitespace(search.getString("applicationEnName")) val applicationCode = StringUtils.trimWhitespace(search.getString("applicationCode")) if (StringUtils.hasLength(applicationName)) { a = APPLICATION.APPLICATION_NAME.like(SQLQueryUtils.likeAllParam(applicationName)) } if (StringUtils.hasLength(applicationEnName)) { a = if (ObjectUtils.isEmpty(a)) { APPLICATION.APPLICATION_EN_NAME.like(SQLQueryUtils.likeAllParam(applicationEnName)) } else { a!!.and(APPLICATION.APPLICATION_EN_NAME.like(SQLQueryUtils.likeAllParam(applicationEnName))) } } if (StringUtils.hasLength(applicationCode)) { a = if (ObjectUtils.isEmpty(a)) { APPLICATION.APPLICATION_CODE.like(SQLQueryUtils.likeAllParam(applicationCode)) } else { a!!.and(APPLICATION.APPLICATION_CODE.like(SQLQueryUtils.likeAllParam(applicationCode))) } } } return a } /** * 应用数据排序 * * @param dataTablesUtils datatable工具类 * @param selectConditionStep 条件 */ override fun sortCondition(dataTablesUtils: DataTablesUtils<ApplicationBean>, selectConditionStep: SelectConditionStep<Record>?, selectJoinStep: SelectJoinStep<Record>?, type: Int) { val orderColumnName = dataTablesUtils.orderColumnName val orderDir = dataTablesUtils.orderDir val isAsc = "asc".equals(orderDir, ignoreCase = true) var sortField: Array<SortField<*>?>? = null if (StringUtils.hasLength(orderColumnName)) { if ("application_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = APPLICATION.APPLICATION_NAME.asc() } else { sortField[0] = APPLICATION.APPLICATION_NAME.desc() } } if ("application_en_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = APPLICATION.APPLICATION_EN_NAME.asc() } else { sortField[0] = APPLICATION.APPLICATION_EN_NAME.desc() } } if ("application_pid".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = APPLICATION.APPLICATION_PID.asc() sortField[1] = APPLICATION.APPLICATION_ID.asc() } else { sortField[0] = APPLICATION.APPLICATION_PID.desc() sortField[1] = APPLICATION.APPLICATION_ID.desc() } } if ("application_url".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = APPLICATION.APPLICATION_URL.asc() } else { sortField[0] = APPLICATION.APPLICATION_URL.desc() } } if ("icon".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = APPLICATION.ICON.asc() sortField[1] = APPLICATION.APPLICATION_ID.asc() } else { sortField[0] = APPLICATION.ICON.desc() sortField[1] = APPLICATION.APPLICATION_ID.desc() } } if ("application_sort".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = APPLICATION.APPLICATION_SORT.asc() } else { sortField[0] = APPLICATION.APPLICATION_SORT.desc() } } if ("application_code".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = APPLICATION.APPLICATION_CODE.asc() } else { sortField[0] = APPLICATION.APPLICATION_CODE.desc() } } if ("application_data_url_start_with".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = APPLICATION.APPLICATION_DATA_URL_START_WITH.asc() } else { sortField[0] = APPLICATION.APPLICATION_DATA_URL_START_WITH.desc() } } } sortToFinish(selectConditionStep, selectJoinStep, type, *sortField!!) } }
mit
c70f337b9bc857887efc24ecaf324051
39.438272
186
0.626899
5.153816
false
false
false
false
nibarius/opera-park-android
app/src/main/java/se/barsk/park/mainui/NetworkState.kt
1
2322
package se.barsk.park.mainui /** * Used to keep track of the state of requests to be able to decide which placeholder * to show if there is no data from the server available. */ class NetworkState { /** * Fail * +---------+ * | | * Init+-----+ +--v---------+---------+ * | | Only failed requests | * | +--^---------+---------+ * +--------v-------+ Fail | | * | +----------------+ | * | First response | | Success * | not received | Success | * | +----------------+ | * +-----^----------+ | | * | +----v---------v-------------+ * +----------------------+Have made successful request| * Reset state +----^---------+-------------+ * | | * +---------+ Success, Fail */ enum class State { // Once there's a server set up a request will be done automatically and a spinner is shown // so it can be assumed that we are waiting for a request when this class is initialized. FIRST_RESPONSE_NOT_RECEIVED, ONLY_FAILED_REQUESTS, HAVE_MADE_SUCCESSFUL_REQUEST } private var state: State = State.FIRST_RESPONSE_NOT_RECEIVED fun isWaitingForFirstResponse() = state == State.FIRST_RESPONSE_NOT_RECEIVED fun hasMadeFailedRequestsOnly() = state == State.ONLY_FAILED_REQUESTS var updateInProgress: Boolean = false private set fun resetState() { state = State.FIRST_RESPONSE_NOT_RECEIVED updateInProgress = false } fun requestStarted() { updateInProgress = true } fun requestFinished(success: Boolean) { updateInProgress = false if (success) { state = State.HAVE_MADE_SUCCESSFUL_REQUEST } else if (!success && state != State.HAVE_MADE_SUCCESSFUL_REQUEST) { state = State.ONLY_FAILED_REQUESTS } } }
mit
71fb5da9f885f4f8b684dc548d19d57c
36.467742
99
0.420327
5.125828
false
false
false
false
google/intellij-community
java/java-tests/testSrc/com/intellij/java/testFramework/fixtures/MultiModuleJava9ProjectDescriptor.kt
5
7339
// 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.java.testFramework.fixtures import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.ex.temp.TempFileSystem import com.intellij.pom.java.LanguageLevel import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType /** * Compile Dependencies: 'main' -> 'm2', 'main' -> 'm4', 'main' -> 'm5', 'main' -> 'm6' => 'm7', 'm6' -> 'm8' * Test dependencies: 'm.test' -> 'm2' */ object MultiModuleJava9ProjectDescriptor : DefaultLightProjectDescriptor() { enum class ModuleDescriptor(internal val moduleName: String, internal val sourceRootName: String? = null, internal val testRootName: String? = null, internal val resourceRootName : String? = null) { MAIN(TEST_MODULE_NAME, testRootName = "test_src"), M2("light_idea_test_m2", sourceRootName = "src_m2"), M3("light_idea_test_m3", sourceRootName = "src_m3"), M4("light_idea_test_m4", sourceRootName = "src_m4"), M5("light_idea_test_m5", sourceRootName = "src_m5"), M6("light_idea_test_m6", sourceRootName = "src_m6", resourceRootName = "res_m6"), M7("light_idea_test_m7", sourceRootName = "src_m7"), M8("light_idea_test_m8", sourceRootName = "src_m8"), M_TEST("light_idea_test_m_test", sourceRootName="m_src_src", testRootName = "m_test_src"); fun sourceRoot(): VirtualFile? = if (this === MAIN) LightPlatformTestCase.getSourceRoot() else findRoot(sourceRootName) fun testRoot(): VirtualFile? = findRoot(testRootName) fun resourceRoot(): VirtualFile? = findRoot(resourceRootName) private fun findRoot(rootName: String?): VirtualFile? = if (rootName == null) null else TempFileSystem.getInstance().findFileByPath("/${rootName}") ?: throw IllegalStateException("Cannot find temp:///${rootName}") } override fun getSdk(): Sdk = IdeaTestUtil.getMockJdk9() override fun setUpProject(project: Project, handler: SetupHandler) { super.setUpProject(project, handler) runWriteAction { val main = ModuleManager.getInstance(project).findModuleByName(TEST_MODULE_NAME)!! val m2 = makeModule(project, ModuleDescriptor.M2) ModuleRootModificationUtil.addDependency(main, m2) makeModule(project, ModuleDescriptor.M3) val m4 = makeModule(project, ModuleDescriptor.M4) ModuleRootModificationUtil.addDependency(main, m4) val m5 = makeModule(project, ModuleDescriptor.M5) ModuleRootModificationUtil.addDependency(main, m5) val m6 = makeModule(project, ModuleDescriptor.M6) ModuleRootModificationUtil.addDependency(main, m6) val m7 = makeModule(project, ModuleDescriptor.M7) ModuleRootModificationUtil.addDependency(m6, m7, DependencyScope.COMPILE, true) val m8 = makeModule(project, ModuleDescriptor.M8) ModuleRootModificationUtil.addDependency(m6, m8) val m_test = makeModule(project, ModuleDescriptor.M_TEST) ModuleRootModificationUtil.addDependency(m_test, m2, DependencyScope.TEST, false) val libDir = "jar://${PathManagerEx.getTestDataPath()}/codeInsight/jigsaw" ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-named-1.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-named-2.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-with-claimed-name.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-auto-1.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-auto-2.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-multi-release.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib_invalid_1_2.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-xml-bind.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-xml-ws.jar!/") ModuleRootModificationUtil.updateModel(main) { val entries = it.orderEntries.toMutableList() entries.add(0, entries.last()) // places an upgrade module before the JDK entries.removeAt(entries.size - 1) it.rearrangeOrderEntries(entries.toTypedArray()) } ModuleRootModificationUtil.addModuleLibrary(m2, "${libDir}/lib-auto-1.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(m4, "${libDir}/lib-auto-2.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(m6, "${libDir}/lib-named-2.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(m8, "lib-with-module-info", listOf("${libDir}/lib-with-module-info.jar!/"), listOf("${libDir}/lib-with-module-info-sources.zip!/src")) } } private fun makeModule(project: Project, descriptor: ModuleDescriptor): Module { val path = "${FileUtil.getTempDirectory()}/${descriptor.moduleName}.iml" val module = createModule(project, path) ModuleRootModificationUtil.updateModel(module) { configureModule(module, it, descriptor) } return module } override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) = configureModule(module, model, ModuleDescriptor.MAIN) private fun configureModule(module: Module, model: ModifiableRootModel, descriptor: ModuleDescriptor) { model.getModuleExtension(LanguageLevelModuleExtension::class.java).languageLevel = LanguageLevel.JDK_1_9 if (descriptor !== ModuleDescriptor.MAIN) { model.sdk = sdk } if (descriptor.sourceRootName != null) { val sourceRoot = createSourceRoot(module, descriptor.sourceRootName) registerSourceRoot(module.project, sourceRoot) model.addContentEntry(sourceRoot).addSourceFolder(sourceRoot, JavaSourceRootType.SOURCE) } if (descriptor.testRootName != null) { val testRoot = createSourceRoot(module, descriptor.testRootName) registerSourceRoot(module.project, testRoot) model.addContentEntry(testRoot).addSourceFolder(testRoot, JavaSourceRootType.TEST_SOURCE) } if (descriptor.resourceRootName != null) { val resourceRoot = createSourceRoot(module, descriptor.resourceRootName) registerSourceRoot(module.project, resourceRoot) model.addContentEntry(resourceRoot).addSourceFolder(resourceRoot, JavaResourceRootType.RESOURCE) } } fun cleanupSourceRoots() = runWriteAction { ModuleDescriptor.values().asSequence() .flatMap { sequenceOf(if (it !== ModuleDescriptor.MAIN) it.sourceRoot() else null, it.testRoot(), it.resourceRoot()) } .filterNotNull() .flatMap { it.children.asSequence() } .forEach { it.delete(this) } } }
apache-2.0
592bc9547b84f18fcbbc21562ce90932
49.965278
184
0.731162
4.442494
false
true
false
false
RuneSuite/client
plugins/src/main/java/org/runestar/client/plugins/groundmarkers/GroundMarkers.kt
1
3481
package org.runestar.client.plugins.groundmarkers import org.runestar.client.api.forms.BasicStrokeForm import org.runestar.client.api.forms.KeyCodeForm import org.runestar.client.api.forms.RgbaForm import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.api.game.GameState import org.runestar.client.api.game.GlobalTile import org.runestar.client.api.game.MiniMenuOption import org.runestar.client.api.game.MiniMenuOpcode import org.runestar.client.api.game.SceneTile import org.runestar.client.api.game.live.Game import org.runestar.client.api.game.live.Keyboard import org.runestar.client.api.game.live.Canvas import org.runestar.client.api.game.live.Scene import org.runestar.client.api.game.live.MiniMenu import org.runestar.client.api.game.live.VisibilityMap import org.runestar.client.api.plugins.PluginSettings import java.awt.Color import java.awt.Graphics2D import java.awt.RenderingHints class GroundMarkers : DisposablePlugin<GroundMarkers.Settings>() { override val defaultSettings = Settings() override val name = "Ground Markers" private val MARK_ACTION = "Mark" private val sceneMarkers = ArrayList<SceneTile>() override fun onStart() { add(Canvas.repaints.subscribe(::onDraw)) add(MiniMenu.optionAdditions.subscribe(::onMenuOptionAdded)) add(MiniMenu.actions.subscribe(::onMenuAction)) add(Scene.reloads.subscribe { reloadSceneMarkers() }) reloadSceneMarkers() } override fun onStop() { sceneMarkers.clear() } private fun reloadSceneMarkers() { sceneMarkers.clear() for (globalTile in settings.markers) { Game.fromTemplate(globalTile).filterTo(sceneMarkers) { it.isLoaded } } } private fun onDraw(g: Graphics2D) { if (Game.state != GameState.LOGGED_IN || sceneMarkers.isEmpty()) return g.color = settings.color.value g.stroke = settings.stroke.value g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) for (sceneMarker in sceneMarkers) { if (!VisibilityMap.isVisible(sceneMarker)) continue g.draw(sceneMarker.outline()) } } private fun onMenuOptionAdded(menuOption: MiniMenuOption) { if (menuOption.opcode != MiniMenuOpcode.WALK || !Keyboard.isKeyPressed(settings.keyCode.value)) return MiniMenu.addOption(MiniMenuOption.of(MiniMenuOpcode.CANCEL, 0, 0, 0, "", MARK_ACTION, false)) } private fun onMenuAction(menuOption: MiniMenuOption) { if (menuOption.opcode != MiniMenuOpcode.CANCEL || menuOption.action != MARK_ACTION) return val selectedTile = Game.selectedTile ?: return val gt = Game.toTemplate(selectedTile) val sts = Game.fromTemplate(gt) val idx = settings.markers.indexOf(gt) synchronized(settings) { if (idx != -1) { settings.markers.removeAt(idx) sceneMarkers.removeAll(sts) } else { settings.markers.add(gt) sceneMarkers.addAll(sts) } return@synchronized } settings.write() } class Settings( val stroke: BasicStrokeForm = BasicStrokeForm(1f), val color: RgbaForm = RgbaForm(Color.YELLOW), val keyCode: KeyCodeForm = KeyCodeForm("SHIFT"), val markers: ArrayList<GlobalTile> = ArrayList() ) : PluginSettings() }
mit
5dfa46f1256d6a3cfbe7f3c23e700fae
36.44086
110
0.691755
4.214286
false
false
false
false
cd1/motofretado
app/src/main/java/com/gmail/cristiandeives/motofretado/ActivityInVehicleFenceService.kt
1
6065
package com.gmail.cristiandeives.motofretado import android.app.PendingIntent import android.app.Service import android.content.BroadcastReceiver import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.os.IBinder import android.os.Messenger import android.support.annotation.MainThread import android.support.annotation.UiThread import android.util.Log import com.google.android.gms.awareness.Awareness import com.google.android.gms.awareness.fence.DetectedActivityFence import com.google.android.gms.awareness.fence.FenceUpdateRequest import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient @MainThread internal class ActivityInVehicleFenceService : Service(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { companion object { internal const val EXTRA_MESSENGER = "messenger" internal const val FENCE_KEY = "FENCE_KEY" private val TAG = ActivityInVehicleFenceService::class.java.simpleName private const val ACTIVITY_CHANGED_REQUEST_CODE = 1 } private lateinit var mGoogleApiClient: GoogleApiClient private lateinit var mResultReceiver: BroadcastReceiver private lateinit var mReceiverIntentFilter: IntentFilter private lateinit var mMessenger: Messenger private var mReceiverPendingIntent: PendingIntent? = null override fun onCreate() { Log.v(TAG, "> onCreate()") mGoogleApiClient = GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Awareness.API) .build() mResultReceiver = ActivityInVehicleFenceReceiver() mReceiverIntentFilter = IntentFilter(ActivityInVehicleFenceReceiver.RESULT_ACTION) Log.v(TAG, "< onCreate()") } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { Log.v(TAG, "> onStartCommand(intent=$intent, flags=$flags, startId=$startId)") val messenger = intent.extras?.get(EXTRA_MESSENGER) if (messenger is Messenger) { mMessenger = messenger val receiverIntent = Intent(ActivityInVehicleFenceReceiver.RESULT_ACTION) receiverIntent.putExtra(ActivityInVehicleFenceReceiver.EXTRA_MESSENGER, mMessenger) mReceiverPendingIntent = PendingIntent.getBroadcast( this, ACTIVITY_CHANGED_REQUEST_CODE, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT ) Log.d(TAG, "connecting to Google Play Services") mGoogleApiClient.connect() } else { Log.w(TAG, "could not find a Messenger in the Intent") } val ret = START_REDELIVER_INTENT Log.v(TAG, "< onStartCommand(intent=$intent, flags=$flags, startId=$startId): $ret") return ret } override fun onDestroy() { Log.v(TAG, "> onDestroy()") removeActivityUpdates() Log.d(TAG, "disconnecting from Google Play Services") mGoogleApiClient.disconnect() mMessenger.sendMessage(TrackBusPresenter.MyHandler.MSG_ACTIVITY_DETECTION_SERVICE_DISCONNECTED) Log.v(TAG, "< onDestroy()") } override fun onBind(intent: Intent): IBinder? { Log.v(TAG, "onBind(intent=$intent): null") return null } override fun onConnected(connectionHint: Bundle?) { Log.v(TAG, "> onConnected(connectionHint=$connectionHint)") requestActivityUpdates() mMessenger.sendMessage(TrackBusPresenter.MyHandler.MSG_ACTIVITY_DETECTION_SERVICE_CONNECTED) Log.v(TAG, "< onConnected(connectionHint=$connectionHint)") } override fun onConnectionSuspended(cause: Int) { Log.v(TAG, "> onConnectionSuspended(cause=$cause)") removeActivityUpdates() mMessenger.sendMessage(TrackBusPresenter.MyHandler.MSG_ACTIVITY_DETECTION_SERVICE_DISCONNECTED) Log.v(TAG, "< onConnectionSuspended(cause=$cause)") } override fun onConnectionFailed(result: ConnectionResult) { Log.v(TAG, "> onConnectionFailed(result=$result)") Log.e(TAG, "Google Play Services connection failed: ${result.errorMessage}") mMessenger.sendMessage(TrackBusPresenter.MyHandler.MSG_GMS_CONNECTION_FAILED) stopSelf() Log.v(TAG, "< onConnectionFailed(result=$result)") } @UiThread private fun requestActivityUpdates() { Log.d(TAG, "registering activity fence") val fence = DetectedActivityFence.during(DetectedActivityFence.IN_VEHICLE) val registerRequest = FenceUpdateRequest.Builder() .addFence(FENCE_KEY, fence, mReceiverPendingIntent) .build() Awareness.FenceApi.updateFences(mGoogleApiClient, registerRequest).setResultCallback { result -> if (result.isSuccess) { Log.v(TAG, "fence registered successfully") } else { Log.v(TAG, "fence failed to register: ${result.statusMessage}") } } Log.d(TAG, "registering BroadcastReceiver") registerReceiver(mResultReceiver, mReceiverIntentFilter) } @UiThread private fun removeActivityUpdates() { Log.d(TAG, "unregistering activity fence") if (mGoogleApiClient.isConnected) { val unregisterRequest = FenceUpdateRequest.Builder() .removeFence(FENCE_KEY) .build() Awareness.FenceApi.updateFences(mGoogleApiClient, unregisterRequest).setResultCallback { result -> if (result.isSuccess) { Log.v(TAG, "fence unregistered successfully") } else { Log.v(TAG, "fence failed to unregister: ${result.statusMessage}") } } Log.d(TAG, "unregistering BroadcastReceiver") unregisterReceiver(mResultReceiver) } } }
gpl-3.0
9ec36ee5e1a463f8b3ecf9eb04c0fe7e
36.444444
139
0.671558
4.979475
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/grammar/dumb/Variant.kt
1
3128
package org.jetbrains.grammar.dumb import com.intellij.psi.tree.IElementType import java.util.HashSet import java.util.ArrayList import org.jetbrains.haskell.parser.HaskellTokenType import org.jetbrains.grammar.HaskellLexerTokens /** * Created by atsky on 14/11/14. */ abstract class Variant { fun add(tokenType : HaskellTokenType): NonTerminalVariant { return NonTerminalVariant(Terminal(tokenType), listOf(this)) } fun add(rule: String): NonTerminalVariant { return NonTerminalVariant(NonTerminal(rule), listOf(this)) } open fun makeAnalysis(grammar: Map<String, Rule>) { } abstract fun isCanBeEmpty(): Boolean abstract fun makeDeepAnalysis(grammar: Map<String, Rule>) abstract fun accepts(token: IElementType?): Boolean } class TerminalVariant(val elementType: IElementType?) : Variant() { override fun isCanBeEmpty(): Boolean { return true } override fun makeDeepAnalysis(grammar: Map<String, Rule>) { } override fun accepts(token: IElementType?): Boolean { return true } } class NonTerminalVariant(val term: Term, val next: List<Variant>) : Variant() { var canBeEmpty: Boolean = false var hasCurly: Boolean = false var first: Set<IElementType>? = null override fun isCanBeEmpty(): Boolean { return canBeEmpty } override fun toString(): String { val builder = StringBuilder() if (term is NonTerminal) { builder.append(" " + term.rule) } else if (term is Terminal) { builder.append(" '" + term.tokenType + "'") } return "{" + builder.toString() + " }" } override fun makeDeepAnalysis(grammar: Map<String, Rule>) { if (first == null) { makeAnalysis(grammar) } hasCurly = first!!.contains(HaskellLexerTokens.VCCURLY) for (n in next) { n.makeDeepAnalysis(grammar) } } override fun accepts(token: IElementType?): Boolean { return canBeEmpty || hasCurly || first!!.contains(token) } override fun makeAnalysis(grammar: Map<String, Rule>) { canBeEmpty = true if (term is NonTerminal) { val rule = grammar[term.rule]!! rule.makeAnalysis(grammar) if (!rule.canBeEmpty) { canBeEmpty = false } else { for (n in next) { n.makeAnalysis(grammar) canBeEmpty = canBeEmpty || n.isCanBeEmpty() } } } else { canBeEmpty = false } if (term is NonTerminal) { val result = HashSet<IElementType>() val rule = grammar[term.rule]!! result.addAll(rule.first!!) if (rule.canBeEmpty) { for (n in next) { if (n is NonTerminalVariant) { result.addAll(n.first!!) } } } first = result } else { first = setOf((term as Terminal).tokenType) } } }
apache-2.0
26320b5a3ef8a01ad14f25ffc28eae17
24.647541
79
0.573529
4.732224
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectSerializersImpl.kt
1
46900
// 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.ide.impl.jps.serialization import com.intellij.diagnostic.AttachmentFactory import com.intellij.openapi.components.ExpandMacroToPathMap import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.components.impl.ModulePathMacroManager import com.intellij.openapi.components.impl.ProjectPathMacroManager import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.trace import com.intellij.openapi.module.impl.ModulePath import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.projectModel.ProjectModelBundle import com.intellij.util.PathUtil import com.intellij.util.containers.BidirectionalMap import com.intellij.util.containers.BidirectionalMultiMap import com.intellij.util.text.UniqueNameGenerator import com.intellij.workspaceModel.ide.* import com.intellij.workspaceModel.ide.impl.FileInDirectorySourceNames import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.impl.reportErrorAndAttachStorage import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import org.jdom.Element import org.jdom.JDOMException import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.util.JpsPathUtil import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.stream.Collectors class JpsProjectSerializersImpl(directorySerializersFactories: List<JpsDirectoryEntitiesSerializerFactory<*>>, moduleListSerializers: List<JpsModuleListSerializer>, reader: JpsFileContentReader, private val entityTypeSerializers: List<JpsFileEntityTypeSerializer<*>>, private val configLocation: JpsProjectConfigLocation, private val externalStorageMapping: JpsExternalStorageMapping, private val enableExternalStorage: Boolean, private val virtualFileManager: VirtualFileUrlManager, fileInDirectorySourceNames: FileInDirectorySourceNames) : JpsProjectSerializers { private val lock = Any() val moduleSerializers = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsModuleListSerializer>() internal val serializerToDirectoryFactory = BidirectionalMap<JpsFileEntitiesSerializer<*>, JpsDirectoryEntitiesSerializerFactory<*>>() private val internalSourceToExternal = HashMap<JpsFileEntitySource, JpsFileEntitySource>() internal val fileSerializersByUrl = BidirectionalMultiMap<String, JpsFileEntitiesSerializer<*>>() internal val fileIdToFileName = Int2ObjectOpenHashMap<String>() // Map of module serializer to boolean that defines whenever modules.xml is external or not private val moduleSerializerToExternalSourceBool = mutableMapOf<JpsFileEntitiesSerializer<*>, Boolean>() init { synchronized(lock) { for (factory in directorySerializersFactories) { createDirectorySerializers(factory, fileInDirectorySourceNames).associateWithTo(serializerToDirectoryFactory) { factory } } val enabledModuleListSerializers = moduleListSerializers.filter { enableExternalStorage || !it.isExternalStorage } val moduleFiles = enabledModuleListSerializers.flatMap { ser -> ser.loadFileList(reader, virtualFileManager).map { Triple(it.first, it.second, ser.isExternalStorage) } } for ((moduleFile, moduleGroup, isOriginallyExternal) in moduleFiles) { val directoryUrl = virtualFileManager.getParentVirtualUrl(moduleFile)!! val internalSource = bindExistingSource(fileInDirectorySourceNames, ModuleEntity::class.java, moduleFile.fileName, directoryUrl) ?: createFileInDirectorySource(directoryUrl, moduleFile.fileName) for (moduleListSerializer in enabledModuleListSerializers) { val moduleSerializer = moduleListSerializer.createSerializer(internalSource, moduleFile, moduleGroup) moduleSerializers[moduleSerializer] = moduleListSerializer moduleSerializerToExternalSourceBool[moduleSerializer] = isOriginallyExternal } } val allFileSerializers = entityTypeSerializers.filter { enableExternalStorage || !it.isExternalStorage } + serializerToDirectoryFactory.keys + moduleSerializers.keys allFileSerializers.forEach { fileSerializersByUrl.put(it.fileUrl.url, it) } } } internal val directorySerializerFactoriesByUrl = directorySerializersFactories.associateBy { it.directoryUrl } val moduleListSerializersByUrl = moduleListSerializers.associateBy { it.fileUrl } private fun createFileInDirectorySource(directoryUrl: VirtualFileUrl, fileName: String): JpsFileEntitySource.FileInDirectory { val source = JpsFileEntitySource.FileInDirectory(directoryUrl, configLocation) // Don't convert to links[key] = ... because it *may* became autoboxing fileIdToFileName.put(source.fileNameId, fileName) LOG.debug { "createFileInDirectorySource: ${source.fileNameId}=$fileName" } return source } private fun createDirectorySerializers(factory: JpsDirectoryEntitiesSerializerFactory<*>, fileInDirectorySourceNames: FileInDirectorySourceNames): List<JpsFileEntitiesSerializer<*>> { val osPath = JpsPathUtil.urlToOsPath(factory.directoryUrl) val libPath = Paths.get(osPath) val files = when { Files.isDirectory(libPath) -> Files.list(libPath).use { stream -> stream.filter { path: Path -> PathUtil.getFileExtension(path.toString()) == "xml" && Files.isRegularFile(path) } .collect(Collectors.toList()) } else -> emptyList() } return files.map { val fileName = it.fileName.toString() val directoryUrl = virtualFileManager.fromUrl(factory.directoryUrl) val entitySource = bindExistingSource(fileInDirectorySourceNames, factory.entityClass, fileName, directoryUrl) ?: createFileInDirectorySource(directoryUrl, fileName) factory.createSerializer("${factory.directoryUrl}/$fileName", entitySource, virtualFileManager) } } private fun bindExistingSource(fileInDirectorySourceNames: FileInDirectorySourceNames, entityType: Class<out WorkspaceEntity>, fileName: String, directoryUrl: VirtualFileUrl): JpsFileEntitySource.FileInDirectory? { val source = fileInDirectorySourceNames.findSource(entityType, fileName) if (source == null || source.directory != directoryUrl) return null fileIdToFileName.put(source.fileNameId, fileName) LOG.debug { "bindExistingSource: ${source.fileNameId}=$fileName" } return source } override fun reloadFromChangedFiles(change: JpsConfigurationFilesChange, reader: JpsFileContentReader, errorReporter: ErrorReporter): Pair<Set<EntitySource>, MutableEntityStorage> { val obsoleteSerializers = ArrayList<JpsFileEntitiesSerializer<*>>() val newFileSerializers = ArrayList<JpsFileEntitiesSerializer<*>>() val addedFileUrls = change.addedFileUrls.flatMap { val file = JpsPathUtil.urlToFile(it) if (file.isDirectory) { file.list()?.map { fileName -> "$it/$fileName" } ?: emptyList() } else listOf(it) }.toSet() val affectedFileLoaders: LinkedHashSet<JpsFileEntitiesSerializer<*>> val changedSources = HashSet<JpsFileEntitySource>() synchronized(lock) { for (addedFileUrl in addedFileUrls) { // The file may already be processed during class initialization if (fileSerializersByUrl.containsKey(addedFileUrl)) continue val factory = directorySerializerFactoriesByUrl[PathUtil.getParentPath(addedFileUrl)] val newFileSerializer = factory?.createSerializer(addedFileUrl, createFileInDirectorySource( virtualFileManager.fromUrl(factory.directoryUrl), PathUtil.getFileName(addedFileUrl)), virtualFileManager) if (newFileSerializer != null) { newFileSerializers.add(newFileSerializer) serializerToDirectoryFactory[newFileSerializer] = factory } } for (changedUrl in change.changedFileUrls) { val serializerFactory = moduleListSerializersByUrl[changedUrl] if (serializerFactory != null) { val newFileUrls = serializerFactory.loadFileList(reader, virtualFileManager) val oldSerializers: List<JpsFileEntitiesSerializer<*>> = moduleSerializers.getKeysByValue(serializerFactory) ?: emptyList() val oldFileUrls = oldSerializers.mapTo(HashSet()) { it.fileUrl } val newFileUrlsSet = newFileUrls.mapTo(HashSet()) { it.first } val obsoleteSerializersForFactory = oldSerializers.filter { it.fileUrl !in newFileUrlsSet } obsoleteSerializersForFactory.forEach { moduleSerializers.remove(it, serializerFactory) moduleSerializerToExternalSourceBool.remove(it) } val newFileSerializersForFactory = newFileUrls.filter { it.first !in oldFileUrls }.map { serializerFactory.createSerializer(createFileInDirectorySource(virtualFileManager.getParentVirtualUrl(it.first)!!, it.first.fileName), it.first, it.second) } newFileSerializersForFactory.associateWithTo(moduleSerializerToExternalSourceBool) { serializerFactory.isExternalStorage } newFileSerializersForFactory.associateWithTo(moduleSerializers) { serializerFactory } obsoleteSerializers.addAll(obsoleteSerializersForFactory) newFileSerializers.addAll(newFileSerializersForFactory) } } for (newSerializer in newFileSerializers) { fileSerializersByUrl.put(newSerializer.fileUrl.url, newSerializer) } for (obsoleteSerializer in obsoleteSerializers) { fileSerializersByUrl.remove(obsoleteSerializer.fileUrl.url, obsoleteSerializer) } affectedFileLoaders = LinkedHashSet(newFileSerializers) addedFileUrls.flatMapTo(affectedFileLoaders) { fileSerializersByUrl.getValues(it) } change.changedFileUrls.flatMapTo(affectedFileLoaders) { fileSerializersByUrl.getValues(it) } affectedFileLoaders.mapTo(changedSources) { it.internalEntitySource } for (fileUrl in change.removedFileUrls) { val directorySerializer = directorySerializerFactoriesByUrl[fileUrl] if (directorySerializer != null) { val serializers = serializerToDirectoryFactory.getKeysByValue(directorySerializer)?.toList() ?: emptyList() for (serializer in serializers) { fileSerializersByUrl.removeValue(serializer) obsoleteSerializers.add(serializer) serializerToDirectoryFactory.remove(serializer, directorySerializer) } } else { val obsolete = fileSerializersByUrl.getValues(fileUrl) fileSerializersByUrl.removeKey(fileUrl) obsoleteSerializers.addAll(obsolete) obsolete.forEach { serializerToDirectoryFactory.remove(it) } } } obsoleteSerializers.mapTo(changedSources) { it.internalEntitySource } obsoleteSerializers.asSequence().map { it.internalEntitySource }.filterIsInstance(JpsFileEntitySource.FileInDirectory::class.java).forEach { fileIdToFileName.remove(it.fileNameId) LOG.debug { "remove association for ${it.fileNameId}" } } } val builder = MutableEntityStorage.create() affectedFileLoaders.forEach { loadEntitiesAndReportExceptions(it, builder, reader, errorReporter) } return Pair(changedSources, builder) } override suspend fun loadAll(reader: JpsFileContentReader, builder: MutableEntityStorage, errorReporter: ErrorReporter, project: Project?): List<EntitySource> { val serializers = synchronized(lock) { fileSerializersByUrl.values.toList() } val builders = coroutineScope { serializers.map { serializer -> async { val result = MutableEntityStorage.create() loadEntitiesAndReportExceptions(serializer, result, reader, errorReporter) result } } }.awaitAll() val sourcesToUpdate = removeDuplicatingEntities(builders, serializers, project) val squashedBuilder = squash(builders) builder.addDiff(squashedBuilder) return sourcesToUpdate } private fun loadEntitiesAndReportExceptions(serializer: JpsFileEntitiesSerializer<*>, builder: MutableEntityStorage, reader: JpsFileContentReader, errorReporter: ErrorReporter) { fun reportError(e: Exception, url: VirtualFileUrl) { errorReporter.reportError(ProjectModelBundle.message("module.cannot.load.error", url.presentableUrl, e.localizedMessage), url) } try { serializer.loadEntities(builder, reader, errorReporter, virtualFileManager) } catch (e: JDOMException) { reportError(e, serializer.fileUrl) } catch (e: IOException) { reportError(e, serializer.fileUrl) } } // Check if the same module is loaded from different source. This may happen in case of two `modules.xml` with the same module. // See IDEA-257175 // This code may be removed if we'll get rid of storing modules.xml and friends in external storage (cache/external_build_system) private fun removeDuplicatingEntities(builders: List<MutableEntityStorage>, serializers: List<JpsFileEntitiesSerializer<*>>, project: Project?): List<EntitySource> { if (project == null) return emptyList() val modules = mutableMapOf<String, MutableList<Triple<ModuleId, MutableEntityStorage, JpsFileEntitiesSerializer<*>>>>() val libraries = mutableMapOf<LibraryId, MutableList<Pair<MutableEntityStorage, JpsFileEntitiesSerializer<*>>>>() val artifacts = mutableMapOf<ArtifactId, MutableList<Pair<MutableEntityStorage, JpsFileEntitiesSerializer<*>>>>() builders.forEachIndexed { i, builder -> if (enableExternalStorage) { builder.entities(ModuleEntity::class.java).forEach { module -> val moduleId = module.symbolicId modules.computeIfAbsent(moduleId.name.lowercase(Locale.US)) { ArrayList() }.add(Triple(moduleId, builder, serializers[i])) } } builder.entities(LibraryEntity::class.java).filter { it.tableId == LibraryTableId.ProjectLibraryTableId }.forEach { library -> libraries.computeIfAbsent(library.symbolicId) { ArrayList() }.add(builder to serializers[i]) } builder.entities(ArtifactEntity::class.java).forEach { artifact -> artifacts.computeIfAbsent(artifact.symbolicId) { ArrayList() }.add(builder to serializers[i]) } } val sourcesToUpdate = mutableListOf<EntitySource>() for ((_, buildersWithModule) in modules) { if (buildersWithModule.size <= 1) continue var correctModuleFound = false var leftModuleId = 0 // Leave only first module with "correct" entity source // If there is no such module, leave the last one buildersWithModule.forEachIndexed { index, (moduleId, builder, ser) -> val originalExternal = moduleSerializerToExternalSourceBool[ser] ?: return@forEachIndexed val moduleEntity = builder.resolve(moduleId)!! if (index != buildersWithModule.lastIndex) { if (!correctModuleFound && originalExternal) { correctModuleFound = true leftModuleId = index } else { sourcesToUpdate += moduleEntity.entitySource builder.removeEntity(moduleEntity) } } else { if (correctModuleFound) { sourcesToUpdate += moduleEntity.entitySource builder.removeEntity(moduleEntity) } else { leftModuleId = index } } } reportIssue(project, buildersWithModule.mapTo(HashSet()) { it.first }, buildersWithModule.map { it.third }, leftModuleId) } for ((libraryId, buildersWithSerializers) in libraries) { if (buildersWithSerializers.size <= 1) continue val defaultFileName = FileUtil.sanitizeFileName(libraryId.name) + ".xml" val hasImportedEntity = buildersWithSerializers.any { (builder, _) -> builder.resolve(libraryId)!!.entitySource is JpsImportedEntitySource } val entitiesToRemove = buildersWithSerializers.mapNotNull { (builder, serializer) -> val library = builder.resolve(libraryId)!! val entitySource = library.entitySource if (entitySource !is JpsFileEntitySource.FileInDirectory) return@mapNotNull null val fileName = serializer.fileUrl.fileName if (fileName != defaultFileName || enableExternalStorage && hasImportedEntity) Triple(builder, library, fileName) else null } LOG.warn("Multiple configuration files were found for '${libraryId.name}' library.") if (entitiesToRemove.isNotEmpty() && entitiesToRemove.size < buildersWithSerializers.size) { for ((builder, entity) in entitiesToRemove) { sourcesToUpdate.add(entity.entitySource) builder.removeEntity(entity) } LOG.warn("Libraries defined in ${entitiesToRemove.joinToString { it.third }} files will ignored and these files will be removed.") } else { LOG.warn("Cannot determine which configuration file should be ignored: ${buildersWithSerializers.map { it.second }}") } } for ((artifactId, buildersWithSerializers) in artifacts) { if (buildersWithSerializers.size <= 1) continue val defaultFileName = FileUtil.sanitizeFileName(artifactId.name) + ".xml" val hasImportedEntity = buildersWithSerializers.any { (builder, _) -> builder.resolve(artifactId)!!.entitySource is JpsImportedEntitySource } val entitiesToRemove = buildersWithSerializers.mapNotNull { (builder, serializer) -> val artifact = builder.resolve(artifactId)!! val entitySource = artifact.entitySource if (entitySource !is JpsFileEntitySource.FileInDirectory) return@mapNotNull null val fileName = serializer.fileUrl.fileName if (fileName != defaultFileName || enableExternalStorage && hasImportedEntity) Triple(builder, artifact, fileName) else null } LOG.warn("Multiple configuration files were found for '${artifactId.name}' artifact.") if (entitiesToRemove.isNotEmpty() && entitiesToRemove.size < buildersWithSerializers.size) { for ((builder, entity) in entitiesToRemove) { sourcesToUpdate.add(entity.entitySource) builder.removeEntity(entity) } LOG.warn("Artifacts defined in ${entitiesToRemove.joinToString { it.third }} files will ignored and these files will be removed.") } else { LOG.warn("Cannot determine which configuration file should be ignored: ${buildersWithSerializers.map { it.second }}") } } return sourcesToUpdate } private fun reportIssue(project: Project, moduleIds: Set<ModuleId>, serializers: List<JpsFileEntitiesSerializer<*>>, leftModuleId: Int) { var serializerCounter = -1 val attachments = mutableMapOf<String, Attachment>() val serializersInfo = serializers.joinToString(separator = "\n\n") { serializerCounter++ it as ModuleImlFileEntitiesSerializer val externalFileUrl = it.let { it.externalModuleListSerializer?.createSerializer(it.internalEntitySource, it.fileUrl, it.modulePath.group) }?.fileUrl val fileUrl = it.fileUrl val internalModuleListSerializerUrl = it.internalModuleListSerializer?.fileUrl val externalModuleListSerializerUrl = it.externalModuleListSerializer?.fileUrl if (externalFileUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(externalFileUrl.url))) { attachments[externalFileUrl.url] = AttachmentFactory.createAttachment(externalFileUrl.toPath(), false) } if (FileUtil.exists(JpsPathUtil.urlToPath(fileUrl.url))) { attachments[fileUrl.url] = AttachmentFactory.createAttachment(fileUrl.toPath(), false) } if (internalModuleListSerializerUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(internalModuleListSerializerUrl))) { attachments[internalModuleListSerializerUrl] = AttachmentFactory.createAttachment( Path.of(JpsPathUtil.urlToPath(internalModuleListSerializerUrl) ), false) } if (externalModuleListSerializerUrl != null && FileUtil.exists(JpsPathUtil.urlToPath(externalModuleListSerializerUrl))) { attachments[externalModuleListSerializerUrl] = AttachmentFactory.createAttachment( Path.of(JpsPathUtil.urlToPath(externalModuleListSerializerUrl)), false ) } """ Serializer info #$serializerCounter: Is external: ${moduleSerializerToExternalSourceBool[it]} fileUrl: ${fileUrl.presentableUrl} externalFileUrl: ${externalFileUrl?.presentableUrl} internal modules.xml: $internalModuleListSerializerUrl external modules.xml: $externalModuleListSerializerUrl """.trimIndent() } val text = """ |Trying to load multiple modules with the same name. | |Project: ${project.name} |Module: ${moduleIds.map { it.name }} |Amount of modules: ${serializers.size} |Leave module of nth serializer: $leftModuleId | |$serializersInfo """.trimMargin() LOG.error(text, *attachments.values.toTypedArray()) } private fun squash(builders: List<MutableEntityStorage>): MutableEntityStorage { var result = builders while (result.size > 1) { result = result.chunked(2) { list -> val res = list.first() if (list.size == 2) res.addDiff(list.last()) res } } return result.singleOrNull() ?: MutableEntityStorage.create() } @TestOnly override fun saveAllEntities(storage: EntityStorage, writer: JpsFileContentWriter) { moduleListSerializersByUrl.values.forEach { saveModulesList(it, storage, writer) } val allSources = storage.entitiesBySource { true }.keys saveEntities(storage, allSources, writer) } internal fun getActualFileUrl(source: EntitySource): String? { val actualFileSource = getActualFileSource(source) ?: return null return when (actualFileSource) { is JpsFileEntitySource.ExactFile -> actualFileSource.file.url is JpsFileEntitySource.FileInDirectory -> { val fileName = fileIdToFileName.get(actualFileSource.fileNameId) ?: run { // We have a situations when we don't have an association at for `fileIdToFileName` entity source returned from `getActualFileSource` // but we have it for the original `JpsImportedEntitySource.internalFile` and base on it we try to calculate actual file url if (source is JpsImportedEntitySource && source.internalFile is JpsFileEntitySource.FileInDirectory && source.storedExternally) { fileIdToFileName.get((source.internalFile as JpsFileEntitySource.FileInDirectory).fileNameId)?.substringBeforeLast(".")?.let { "$it.xml" } } else null } if (fileName != null) actualFileSource.directory.url + "/" + fileName else null } else -> error("Unexpected implementation of JpsFileEntitySource: ${actualFileSource.javaClass}") } } private fun getActualFileSource(source: EntitySource): JpsFileEntitySource? { return when (source) { is JpsImportedEntitySource -> { if (source.storedExternally) { //todo remove obsolete entries internalSourceToExternal.getOrPut(source.internalFile) { externalStorageMapping.getExternalSource(source.internalFile) } } else { source.internalFile } } else -> getInternalFileSource(source) } } override fun getAllModulePaths(): List<ModulePath> { synchronized(lock) { return fileSerializersByUrl.values.filterIsInstance<ModuleImlFileEntitiesSerializer>().mapTo(LinkedHashSet()) { it.modulePath }.toList() } } override fun saveEntities(storage: EntityStorage, affectedSources: Set<EntitySource>, writer: JpsFileContentWriter) { val affectedModuleListSerializers = HashSet<JpsModuleListSerializer>() val serializersToRun = HashMap<JpsFileEntitiesSerializer<*>, MutableMap<Class<out WorkspaceEntity>, MutableSet<WorkspaceEntity>>>() synchronized(lock) { if (LOG.isTraceEnabled) { LOG.trace("save entities; current serializers (${fileSerializersByUrl.values.size}):") fileSerializersByUrl.values.forEach { LOG.trace(it.toString()) } } val affectedEntityTypeSerializers = HashSet<JpsFileEntityTypeSerializer<*>>() fun processObsoleteSource(fileUrl: String, deleteModuleFile: Boolean) { val obsoleteSerializers = fileSerializersByUrl.getValues(fileUrl) fileSerializersByUrl.removeKey(fileUrl) LOG.trace { "processing obsolete source $fileUrl: serializers = $obsoleteSerializers" } obsoleteSerializers.forEach { // Clean up module files content val moduleListSerializer = moduleSerializers.remove(it) if (moduleListSerializer != null) { if (deleteModuleFile) { moduleListSerializer.deleteObsoleteFile(fileUrl, writer) } LOG.trace { "affected module list: $moduleListSerializer" } affectedModuleListSerializers.add(moduleListSerializer) } // Remove libraries under `.idea/libraries` folder val directoryFactory = serializerToDirectoryFactory.remove(it) if (directoryFactory != null) { writer.saveComponent(fileUrl, directoryFactory.componentName, null) } // Remove libraries under `external_build_system/libraries` folder if (it in entityTypeSerializers) { if (getFilteredEntitiesForSerializer(it as JpsFileEntityTypeSerializer, storage).isEmpty()) { it.deleteObsoleteFile(fileUrl, writer) } else { affectedEntityTypeSerializers.add(it) } } } } val sourcesStoredInternally = affectedSources.asSequence().filterIsInstance<JpsImportedEntitySource>() .filter { !it.storedExternally } .associateBy { it.internalFile } val internalSourcesOfCustomModuleEntitySources = affectedSources.mapNotNullTo(HashSet()) { (it as? CustomModuleEntitySource)?.internalSource } /* Entities added via JPS and imported entities stored in internal storage must be passed to serializers together, otherwise incomplete data will be stored. It isn't necessary to save entities stored in external storage when their internal parts are affected, but add them to the list to ensure that obsolete *.iml files will be removed if their modules are stored in external storage. */ val entitiesToSave = storage.entitiesBySource { source -> source in affectedSources || source in sourcesStoredInternally || source is JpsImportedEntitySource && source.internalFile in affectedSources || source in internalSourcesOfCustomModuleEntitySources || source is CustomModuleEntitySource && source.internalSource in affectedSources } if (LOG.isTraceEnabled) { LOG.trace("Affected sources: $affectedSources") LOG.trace("Entities to save:") for ((source, entities) in entitiesToSave) { LOG.trace(" $source: $entities") } } val internalSourceConvertedToImported = affectedSources.filterIsInstance<JpsImportedEntitySource>().mapTo(HashSet()) { it.internalFile } val sourcesStoredExternally = entitiesToSave.keys.asSequence().filterIsInstance<JpsImportedEntitySource>() .filter { it.storedExternally } .associateBy { it.internalFile } val obsoleteSources = affectedSources - entitiesToSave.keys LOG.trace { "Obsolete sources: $obsoleteSources" } for (source in obsoleteSources) { val fileUrl = getActualFileUrl(source) if (fileUrl != null) { val affectedImportedSourceStoredExternally = when { source is JpsImportedEntitySource && source.storedExternally -> sourcesStoredInternally[source.internalFile] source is JpsImportedEntitySource && !source.storedExternally -> sourcesStoredExternally[source.internalFile] source is JpsFileEntitySource -> sourcesStoredExternally[source] else -> null } // When user removes module from project we don't delete corresponding *.iml file located under project directory by default // (because it may be included in other projects). However we do remove the module file if module actually wasn't removed, just // its storage has been changed, e.g. if module was marked as imported from external system, or the place where module imported // from external system was changed, or part of a module configuration is imported from external system and data stored in *.iml // file was removed. val deleteObsoleteFile = source in internalSourceConvertedToImported || (affectedImportedSourceStoredExternally != null && affectedImportedSourceStoredExternally !in obsoleteSources) processObsoleteSource(fileUrl, deleteObsoleteFile) val actualSource = if (source is JpsImportedEntitySource && !source.storedExternally) source.internalFile else source if (actualSource is JpsFileEntitySource.FileInDirectory) { fileIdToFileName.remove(actualSource.fileNameId) LOG.debug { "remove association for obsolete source $actualSource" } } } } fun processNewlyAddedDirectoryEntities(entitiesMap: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>) { directorySerializerFactoriesByUrl.values.forEach { factory -> val added = entitiesMap[factory.entityClass] if (added != null) { val newSerializers = createSerializersForDirectoryEntities(factory, added) newSerializers.forEach { serializerToDirectoryFactory[it.key] = factory fileSerializersByUrl.put(it.key.fileUrl.url, it.key) } newSerializers.forEach { (serializer, entitiesMap) -> mergeSerializerEntitiesMap(serializersToRun, serializer, entitiesMap) } } } } entitiesToSave.forEach { (source, entities) -> val actualFileSource = getActualFileSource(source) if (actualFileSource is JpsFileEntitySource.FileInDirectory) { val fileNameByEntity = calculateFileNameForEntity(actualFileSource, source, entities) val oldFileName = fileIdToFileName.get(actualFileSource.fileNameId) if (oldFileName != fileNameByEntity) { // Don't convert to links[key] = ... because it *may* became autoboxing fileIdToFileName.put(actualFileSource.fileNameId, fileNameByEntity) LOG.debug { "update association for ${actualFileSource.fileNameId} to $fileNameByEntity (was $oldFileName)" } if (oldFileName != null) { processObsoleteSource("${actualFileSource.directory.url}/$oldFileName", true) } val existingSerializers = fileSerializersByUrl.getValues("${actualFileSource.directory.url}/$fileNameByEntity").filter { it in serializerToDirectoryFactory } if (existingSerializers.isNotEmpty()) { val existingSources = existingSerializers.map { it.internalEntitySource } val entitiesWithOldSource = storage.entitiesBySource { it in existingSources } val entitiesSymbolicIds = entitiesWithOldSource.values .flatMap { it.values } .flatten() .filterIsInstance<WorkspaceEntityWithSymbolicId>() .joinToString(separator = "||") { "$it (SymbolicId: ${it.symbolicId})" } //technically this is not an error, but cases when different entities have the same default file name are rare so let's report this // as error for now to find real cause of IDEA-265327 val message = """ |Cannot save entities to $fileNameByEntity because it's already used for other entities; |Current entity source: $actualFileSource |Old file name: $oldFileName |Existing serializers: $existingSerializers |Their entity sources: $existingSources |Entities with these sources in the storage: ${entitiesWithOldSource.mapValues { (_, value) -> value.values }} |Entities with symbolic ids: $entitiesSymbolicIds |Original entities to save: ${entities.values.flatten().joinToString(separator = "||") { "$it (Persistent Id: ${(it as? WorkspaceEntityWithSymbolicId)?.symbolicId})" }} """.trimMargin() reportErrorAndAttachStorage(message, storage) } if (existingSerializers.isEmpty() || existingSerializers.any { it.internalEntitySource != actualFileSource }) { processNewlyAddedDirectoryEntities(entities) } } } val url = getActualFileUrl(source) val internalSource = getInternalFileSource(source) if (url != null && internalSource != null && (ModuleEntity::class.java in entities || FacetEntity::class.java in entities || ModuleGroupPathEntity::class.java in entities || ContentRootEntity::class.java in entities || SourceRootEntity::class.java in entities || ExcludeUrlEntity::class.java in entities )) { val existingSerializers = fileSerializersByUrl.getValues(url) val moduleGroup = (entities[ModuleGroupPathEntity::class.java]?.first() as? ModuleGroupPathEntity)?.path?.joinToString("/") if (existingSerializers.isEmpty() || existingSerializers.any { it is ModuleImlFileEntitiesSerializer && it.modulePath.group != moduleGroup }) { moduleListSerializersByUrl.values.forEach { moduleListSerializer -> if (moduleListSerializer.entitySourceFilter(source)) { if (existingSerializers.isNotEmpty()) { existingSerializers.forEach { if (it is ModuleImlFileEntitiesSerializer) { moduleSerializers.remove(it) fileSerializersByUrl.remove(url, it) } } } val newSerializer = moduleListSerializer.createSerializer(internalSource, virtualFileManager.fromUrl(url), moduleGroup) fileSerializersByUrl.put(url, newSerializer) moduleSerializers[newSerializer] = moduleListSerializer affectedModuleListSerializers.add(moduleListSerializer) } } } for (serializer in existingSerializers) { val moduleListSerializer = moduleSerializers[serializer] val storedExternally = moduleSerializerToExternalSourceBool[serializer] if (moduleListSerializer != null && storedExternally != null && (moduleListSerializer.isExternalStorage == storedExternally && !moduleListSerializer.entitySourceFilter(source) || moduleListSerializer.isExternalStorage != storedExternally && moduleListSerializer.entitySourceFilter(source))) { moduleSerializerToExternalSourceBool[serializer] = !storedExternally affectedModuleListSerializers.add(moduleListSerializer) } } } } entitiesToSave.forEach { (source, entities) -> val serializers = fileSerializersByUrl.getValues(getActualFileUrl(source)) serializers.filter { it !is JpsFileEntityTypeSerializer }.forEach { serializer -> mergeSerializerEntitiesMap(serializersToRun, serializer, entities) } } for (serializer in entityTypeSerializers) { if (entitiesToSave.any { serializer.mainEntityClass in it.value } || serializer in affectedEntityTypeSerializers) { val entitiesMap = mutableMapOf(serializer.mainEntityClass to getFilteredEntitiesForSerializer(serializer, storage)) serializer.additionalEntityTypes.associateWithTo(entitiesMap) { storage.entities(it).toList() } fileSerializersByUrl.put(serializer.fileUrl.url, serializer) mergeSerializerEntitiesMap(serializersToRun, serializer, entitiesMap) } } } if (affectedModuleListSerializers.isNotEmpty()) { moduleListSerializersByUrl.values.forEach { saveModulesList(it, storage, writer) } } serializersToRun.forEach { saveEntitiesBySerializer(it.key, it.value.mapValues { entitiesMapEntry -> entitiesMapEntry.value.toList() }, storage, writer) } } override fun changeEntitySourcesToDirectoryBasedFormat(builder: MutableEntityStorage) { for (factory in directorySerializerFactoriesByUrl.values) { factory.changeEntitySourcesToDirectoryBasedFormat(builder, configLocation) } } private fun mergeSerializerEntitiesMap(existingSerializer2EntitiesMap: HashMap<JpsFileEntitiesSerializer<*>, MutableMap<Class<out WorkspaceEntity>, MutableSet<WorkspaceEntity>>>, serializer: JpsFileEntitiesSerializer<*>, entitiesMap: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>) { val existingEntitiesMap = existingSerializer2EntitiesMap.computeIfAbsent(serializer) { HashMap() } entitiesMap.forEach { (type, entity) -> val existingEntities = existingEntitiesMap.computeIfAbsent(type) { HashSet() } existingEntities.addAll(entity) } } private fun calculateFileNameForEntity(source: JpsFileEntitySource.FileInDirectory, originalSource: EntitySource, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? { val directoryFactory = directorySerializerFactoriesByUrl[source.directory.url] if (directoryFactory != null) { return getDefaultFileNameForEntity(directoryFactory, entities) } if (ModuleEntity::class.java in entities || FacetEntity::class.java in entities || ContentRootEntity::class.java in entities || SourceRootEntity::class.java in entities || ExcludeUrlEntity::class.java in entities ) { val moduleListSerializer = moduleListSerializersByUrl.values.find { it.entitySourceFilter(originalSource) } if (moduleListSerializer != null) { return getFileNameForModuleEntity(moduleListSerializer, entities) } } return null } private fun <E : WorkspaceEntity> getDefaultFileNameForEntity(directoryFactory: JpsDirectoryEntitiesSerializerFactory<E>, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? { @Suppress("UNCHECKED_CAST") val entity = entities[directoryFactory.entityClass]?.singleOrNull() as? E ?: return null return FileUtil.sanitizeFileName(directoryFactory.getDefaultFileName(entity)) + ".xml" } private fun getFileNameForModuleEntity(moduleListSerializer: JpsModuleListSerializer, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>): String? { val entity = entities[ModuleEntity::class.java]?.singleOrNull() as? ModuleEntity if (entity != null) { return moduleListSerializer.getFileName(entity) } val contentRootEntity = entities[ContentRootEntity::class.java]?.firstOrNull() as? ContentRootEntity if (contentRootEntity != null) { return moduleListSerializer.getFileName(contentRootEntity.module) } val sourceRootEntity = entities[SourceRootEntity::class.java]?.firstOrNull() as? SourceRootEntity if (sourceRootEntity != null) { return moduleListSerializer.getFileName(sourceRootEntity.contentRoot.module) } val excludeUrlEntity = entities[ExcludeUrlEntity::class.java]?.firstOrNull() as? ExcludeUrlEntity val module = excludeUrlEntity?.contentRoot?.module if (module != null) { return moduleListSerializer.getFileName(module) } val additionalEntity = entities[FacetEntity::class.java]?.firstOrNull() as? FacetEntity ?: return null return moduleListSerializer.getFileName(additionalEntity.module) } private fun <E : WorkspaceEntity> getFilteredEntitiesForSerializer(serializer: JpsFileEntityTypeSerializer<E>, storage: EntityStorage): List<E> { return storage.entities(serializer.mainEntityClass).filter(serializer.entityFilter).toList() } private fun <E : WorkspaceEntity> saveEntitiesBySerializer(serializer: JpsFileEntitiesSerializer<E>, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, storage: EntityStorage, writer: JpsFileContentWriter) { @Suppress("UNCHECKED_CAST") serializer.saveEntities(entities[serializer.mainEntityClass] as? Collection<E> ?: emptyList(), entities, storage, writer) } private fun <E : WorkspaceEntity> createSerializersForDirectoryEntities(factory: JpsDirectoryEntitiesSerializerFactory<E>, entities: List<WorkspaceEntity>) : Map<JpsFileEntitiesSerializer<*>, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>> { val serializers = serializerToDirectoryFactory.getKeysByValue(factory) ?: emptyList() val nameGenerator = UniqueNameGenerator(serializers) { PathUtil.getFileName(it.fileUrl.url) } return entities.asSequence() .filter { @Suppress("UNCHECKED_CAST") factory.entityFilter(it as E) } .associate { entity -> @Suppress("UNCHECKED_CAST") val defaultFileName = FileUtil.sanitizeFileName(factory.getDefaultFileName(entity as E)) val fileName = nameGenerator.generateUniqueName(defaultFileName, "", ".xml") val entityMap = mapOf<Class<out WorkspaceEntity>, List<WorkspaceEntity>>(factory.entityClass to listOf(entity)) val currentSource = entity.entitySource as? JpsFileEntitySource.FileInDirectory val source = if (currentSource != null && fileIdToFileName.get(currentSource.fileNameId) == fileName) currentSource else createFileInDirectorySource(virtualFileManager.fromUrl(factory.directoryUrl), fileName) factory.createSerializer("${factory.directoryUrl}/$fileName", source, virtualFileManager) to entityMap } } private fun saveModulesList(it: JpsModuleListSerializer, storage: EntityStorage, writer: JpsFileContentWriter) { LOG.trace("saving modules list") it.saveEntitiesList(storage.entities(ModuleEntity::class.java), writer) } companion object { private val LOG = logger<JpsProjectSerializersImpl>() } } class CachingJpsFileContentReader(private val configLocation: JpsProjectConfigLocation) : JpsFileContentReader { private val projectPathMacroManager = ProjectPathMacroManager.createInstance( configLocation::projectFilePath, { JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString) }, null ) private val fileContentCache = ConcurrentHashMap<String, Map<String, Element>>() override fun loadComponent(fileUrl: String, componentName: String, customModuleFilePath: String?): Element? { val content = fileContentCache.computeIfAbsent(fileUrl + customModuleFilePath) { loadComponents(fileUrl, customModuleFilePath) } return content[componentName] } override fun getExpandMacroMap(fileUrl: String): ExpandMacroToPathMap { return getMacroManager(fileUrl, null).expandMacroMap } private fun loadComponents(fileUrl: String, customModuleFilePath: String?): Map<String, Element> { val macroManager = getMacroManager(fileUrl, customModuleFilePath) val file = Paths.get(JpsPathUtil.urlToPath(fileUrl)) return if (Files.isRegularFile(file)) loadStorageFile(file, macroManager) else emptyMap() } private fun getMacroManager(fileUrl: String, customModuleFilePath: String?): PathMacroManager { val path = JpsPathUtil.urlToPath(fileUrl) return if (FileUtil.extensionEquals(fileUrl, "iml") || isExternalModuleFile(path)) { ModulePathMacroManager.createInstance(configLocation::projectFilePath) { customModuleFilePath ?: path } } else { projectPathMacroManager } } } internal fun Element.getAttributeValueStrict(name: String): String = getAttributeValue(name) ?: throw JDOMException("Expected attribute $name under ${this.name} element") internal fun Element.getChildTagStrict(name: String): Element = getChild(name) ?: throw JDOMException("Expected tag $name under ${this.name} element") fun isExternalModuleFile(filePath: String): Boolean { val parentPath = PathUtil.getParentPath(filePath) return FileUtil.extensionEquals(filePath, "xml") && PathUtil.getFileName(parentPath) == "modules" && PathUtil.getFileName(PathUtil.getParentPath(parentPath)) != ".idea" } internal fun getInternalFileSource(source: EntitySource) = when (source) { is JpsFileDependentEntitySource -> source.originalSource is CustomModuleEntitySource -> source.internalSource is JpsFileEntitySource -> source else -> null }
apache-2.0
7f4b522e003f6379fa089129c00f4ab4
50.708931
181
0.697996
5.83769
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/postfix-templates-k1/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KtPostfixTemplateProvider.kt
1
10050
// 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.codeInsight.postfix import com.intellij.codeInsight.template.postfix.templates.* import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil.findElementOfClassAtRange import com.intellij.util.Function import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyze import org.jetbrains.kotlin.idea.intentions.negate import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiverOrThis import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.isBoolean class KtPostfixTemplateProvider : PostfixTemplateProvider { private val templatesSet by lazy { setOf( KtNotPostfixTemplate(this), KtIfExpressionPostfixTemplate(this), KtElseExpressionPostfixTemplate(this), KtNotNullPostfixTemplate("notnull", this), KtNotNullPostfixTemplate("nn", this), KtIsNullPostfixTemplate(this), KtWhenExpressionPostfixTemplate(this), KtTryPostfixTemplate(this), KtIntroduceVariablePostfixTemplate("val", this), KtIntroduceVariablePostfixTemplate("var", this), KtForEachPostfixTemplate("for", this), KtForEachPostfixTemplate("iter", this), KtForReversedPostfixTemplate("forr", this), KtForWithIndexPostfixTemplate("fori", this), KtForLoopNumbersPostfixTemplate("fori", this), KtForLoopReverseNumbersPostfixTemplate("forr", this), KtAssertPostfixTemplate(this), KtParenthesizedPostfixTemplate(this), KtSoutPostfixTemplate(this), KtReturnPostfixTemplate(this), KtWhilePostfixTemplate(this), KtWrapWithListOfPostfixTemplate(this), KtWrapWithSetOfPostfixTemplate(this), KtWrapWithArrayOfPostfixTemplate(this), KtWrapWithSequenceOfPostfixTemplate(this), KtSpreadPostfixTemplate(this), KtArgumentPostfixTemplate(this), KtWithPostfixTemplate(this), ) } override fun getTemplates() = templatesSet override fun isTerminalSymbol(currentChar: Char) = currentChar == '.' || currentChar == '!' override fun afterExpand(file: PsiFile, editor: Editor) { } override fun preCheck(copyFile: PsiFile, realEditor: Editor, currentOffset: Int) = copyFile override fun preExpand(file: PsiFile, editor: Editor) { } companion object { /** * In tests only one expression should be suggested, so in case there are many of them, save relevant items */ @get:TestOnly @Volatile var previouslySuggestedExpressions = emptyList<String>() } } private class KtNotPostfixTemplate(provider: PostfixTemplateProvider) : NotPostfixTemplate( KtPostfixTemplatePsiInfo, createExpressionSelector { it.isBoolean() }, provider ) private class KtIntroduceVariablePostfixTemplate( val kind: String, provider: PostfixTemplateProvider ) : PostfixTemplateWithExpressionSelector(kind, kind, "$kind name = expression", createExpressionSelector(), provider) { override fun expandForChooseExpression(expression: PsiElement, editor: Editor) { KotlinIntroduceVariableHandler.doRefactoring( expression.project, editor, expression as KtExpression, isVar = kind == "var", occurrencesToReplace = null, onNonInteractiveFinish = null ) } } internal object KtPostfixTemplatePsiInfo : PostfixTemplatePsiInfo() { override fun createExpression(context: PsiElement, prefix: String, suffix: String) = KtPsiFactory(context.project).createExpression(prefix + context.text + suffix) override fun getNegatedExpression(element: PsiElement) = (element as KtExpression).negate() } internal fun createExpressionSelector( checkCanBeUsedAsValue: Boolean = true, statementsOnly: Boolean = false, typePredicate: ((KotlinType) -> Boolean)? = null ): PostfixTemplateExpressionSelector { val predicate: ((KtExpression, BindingContext) -> Boolean)? = if (typePredicate != null) { expression, bindingContext -> expression.getType(bindingContext)?.let(typePredicate) ?: false } else null return createExpressionSelectorWithComplexFilter(checkCanBeUsedAsValue, statementsOnly, predicate) } internal fun createExpressionSelectorWithComplexFilter( // Do not suggest expressions like 'val a = 1'/'for ...' checkCanBeUsedAsValue: Boolean = true, statementsOnly: Boolean = false, predicate: ((KtExpression, BindingContext) -> Boolean)? = null ): PostfixTemplateExpressionSelector = KtExpressionPostfixTemplateSelector(checkCanBeUsedAsValue, statementsOnly, predicate) private class KtExpressionPostfixTemplateSelector( private val checkCanBeUsedAsValue: Boolean, private val statementsOnly: Boolean, private val predicate: ((KtExpression, BindingContext) -> Boolean)? ) : PostfixTemplateExpressionSelector { private fun filterElement(element: PsiElement): Boolean { if (element !is KtExpression) return false if (element.parent is KtThisExpression) return false // Can't be independent expressions if (element.isSelector || element.parent is KtUserType || element.isOperationReference || element is KtBlockExpression) return false // Both KtLambdaExpression and KtFunctionLiteral have the same offset, so we add only one of them -> KtLambdaExpression if (element is KtFunctionLiteral) return false if (statementsOnly) { // We use getQualifiedExpressionForReceiverOrThis because when postfix completion is run on some statement like: // foo().try<caret> // `element` points to `foo()` call, while we need to select the whole statement with `try` selector // to check if it's in a statement position if (!KtPsiUtil.isStatement(element.getQualifiedExpressionForReceiverOrThis())) return false } if (checkCanBeUsedAsValue && !element.canBeUsedAsValue()) return false return predicate?.invoke(element, element.safeAnalyze(element.getResolutionFacade(), BodyResolveMode.PARTIAL)) ?: true } private fun KtExpression.canBeUsedAsValue() = !KtPsiUtil.isAssignment(this) && !this.isNamedDeclaration && this !is KtLoopExpression && // if's only with else may be treated as expressions !isIfWithoutElse private val KtExpression.isIfWithoutElse: Boolean get() = (this is KtIfExpression && this.elseKeyword == null) override fun getExpressions(context: PsiElement, document: Document, offset: Int): List<PsiElement> { val originalFile = context.containingFile.originalFile val textRange = context.textRange val originalElement = findElementOfClassAtRange(originalFile, textRange.startOffset, textRange.endOffset, context::class.java) ?: return emptyList() val expressions = originalElement.parentsWithSelf .filterIsInstance<KtExpression>() .takeWhile { !it.isBlockBodyInDeclaration } val boundExpression = expressions.firstOrNull { it.parent.endOffset > offset } val boundElementParent = boundExpression?.parent val filteredByOffset = expressions.takeWhile { it != boundElementParent }.toMutableList() if (boundElementParent is KtDotQualifiedExpression && boundExpression == boundElementParent.receiverExpression) { val qualifiedExpressionEnd = boundElementParent.endOffset expressions .dropWhile { it != boundElementParent } .drop(1) .takeWhile { it.endOffset == qualifiedExpressionEnd } .toCollection(filteredByOffset) } val result = filteredByOffset.filter(this::filterElement) if (isUnitTestMode() && result.size > 1) { KtPostfixTemplateProvider.previouslySuggestedExpressions = result.map { it.text } } return result } override fun hasExpression(context: PsiElement, copyDocument: Document, newOffset: Int): Boolean = getExpressions(context, copyDocument, newOffset).isNotEmpty() override fun getRenderer() = Function(PsiElement::getText) } private val KtExpression.isOperationReference: Boolean get() = this.node.elementType == KtNodeTypes.OPERATION_REFERENCE private val KtElement.isBlockBodyInDeclaration: Boolean get() = this is KtBlockExpression && (parent as? KtElement)?.isNamedDeclarationWithBody == true private val KtElement.isNamedDeclaration: Boolean get() = this is KtNamedDeclaration && !isAnonymousFunction private val KtElement.isNamedDeclarationWithBody: Boolean get() = this is KtDeclarationWithBody && !isAnonymousFunction private val KtDeclaration.isAnonymousFunction: Boolean get() = this is KtFunctionLiteral || (this is KtNamedFunction && this.name == null) private val KtExpression.isSelector: Boolean get() = parent is KtQualifiedExpression && (parent as KtQualifiedExpression).selectorExpression == this
apache-2.0
ee92dc6728333bf2d1a3aa06cd5e2ca5
43.866071
140
0.723781
5.447154
false
false
false
false
JetBrains/intellij-community
platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/ModuleImlFileEntitiesSerializer.kt
1
47733
// 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.ide.impl.jps.serialization import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.module.impl.ModulePath import com.intellij.openapi.project.ExternalStorageConfigurationManager import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.openapi.roots.TestModuleProperties import com.intellij.openapi.util.JDOMUtil import com.intellij.projectModel.ProjectModelBundle import com.intellij.util.io.exists import com.intellij.workspaceModel.ide.* import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Attribute import org.jdom.Element import org.jdom.JDOMException import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.model.serialization.JpsProjectLoader import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension.* import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer.* import org.jetbrains.jps.util.JpsPathUtil import java.io.StringReader import java.nio.file.Path import java.util.* internal const val DEPRECATED_MODULE_MANAGER_COMPONENT_NAME = "DeprecatedModuleOptionManager" internal const val TEST_MODULE_PROPERTIES_COMPONENT_NAME = "TestModuleProperties" private const val MODULE_ROOT_MANAGER_COMPONENT_NAME = "NewModuleRootManager" private const val URL_ATTRIBUTE = "url" private val STANDARD_MODULE_OPTIONS = setOf( "type", "external.system.id", "external.system.module.version", "external.linked.project.path", "external.linked.project.id", "external.root.project.path", "external.system.module.group", "external.system.module.type" ) private val MODULE_OPTIONS_TO_CHECK = setOf( "external.system.module.version", "external.linked.project.path", "external.linked.project.id", "external.root.project.path", "external.system.module.group", "external.system.module.type" ) internal open class ModuleImlFileEntitiesSerializer(internal val modulePath: ModulePath, override val fileUrl: VirtualFileUrl, override val internalEntitySource: JpsFileEntitySource, private val virtualFileManager: VirtualFileUrlManager, internal val internalModuleListSerializer: JpsModuleListSerializer? = null, internal val externalModuleListSerializer: JpsModuleListSerializer? = null, private val externalStorageConfigurationManager: ExternalStorageConfigurationManager? = null) : JpsFileEntitiesSerializer<ModuleEntity> { override val mainEntityClass: Class<ModuleEntity> get() = ModuleEntity::class.java protected open val skipLoadingIfFileDoesNotExist get() = false override fun equals(other: Any?) = other?.javaClass == javaClass && (other as ModuleImlFileEntitiesSerializer).modulePath == modulePath override fun hashCode() = modulePath.hashCode() override fun loadEntities(builder: MutableEntityStorage, reader: JpsFileContentReader, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) { val externalStorageEnabled = externalStorageConfigurationManager?.isEnabled ?: false if (!externalStorageEnabled) { val moduleLoadedInfo = loadModuleEntity(reader, builder, errorReporter, virtualFileManager) if (moduleLoadedInfo != null) { createFacetSerializer().loadFacetEntities(builder, moduleLoadedInfo.moduleEntity, reader) } } else { val externalSerializer = externalModuleListSerializer?.createSerializer(internalEntitySource, fileUrl, modulePath.group) as ModuleImlFileEntitiesSerializer? val moduleLoadedInfo = externalSerializer?.loadModuleEntity(reader, builder, errorReporter, virtualFileManager) var moduleEntity = moduleLoadedInfo?.moduleEntity if (moduleLoadedInfo != null) { val entitySource = getOtherEntitiesEntitySource(reader) loadContentRoots(moduleLoadedInfo.customRootsSerializer, builder, moduleLoadedInfo.moduleEntity, reader, moduleLoadedInfo.customDir, errorReporter, virtualFileManager, entitySource, true) } else { moduleEntity = loadModuleEntity(reader, builder, errorReporter, virtualFileManager)?.moduleEntity } if (moduleEntity != null) { createFacetSerializer().loadFacetEntities(builder, moduleEntity, reader) externalSerializer?.createFacetSerializer()?.loadFacetEntities(builder, moduleEntity, reader) } } } private class ModuleLoadedInfo( val moduleEntity: ModuleEntity, val customRootsSerializer: CustomModuleRootsSerializer?, val customDir: String?, ) private fun loadModuleEntity(reader: JpsFileContentReader, builder: MutableEntityStorage, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager): ModuleLoadedInfo? { if (skipLoadingIfFileDoesNotExist && !fileUrl.toPath().exists()) { return null } val moduleOptions: Map<String?, String?> val customRootsSerializer: CustomModuleRootsSerializer? val customDir: String? val externalSystemOptions: Map<String?, String?> val externalSystemId: String? val entitySourceForModuleAndOtherEntities = try { moduleOptions = readModuleOptions(reader) val pair = readExternalSystemOptions(reader, moduleOptions) externalSystemOptions = pair.first externalSystemId = pair.second customRootsSerializer = moduleOptions[JpsProjectLoader.CLASSPATH_ATTRIBUTE]?.let { customSerializerId -> val serializer = CustomModuleRootsSerializer.EP_NAME.extensionList.firstOrNull { it.id == customSerializerId } if (serializer == null) { errorReporter.reportError(ProjectModelBundle.message("error.message.unknown.classpath.provider", fileUrl.fileName, customSerializerId), fileUrl) } return@let serializer } customDir = moduleOptions[JpsProjectLoader.CLASSPATH_DIR_ATTRIBUTE] val externalSystemEntitySource = createEntitySource(externalSystemId) val moduleEntitySource = customRootsSerializer?.createEntitySource(fileUrl, internalEntitySource, customDir, virtualFileManager) ?: externalSystemEntitySource if (moduleEntitySource is DummyParentEntitySource) { Pair(moduleEntitySource, externalSystemEntitySource) } else { Pair(moduleEntitySource, moduleEntitySource) } } catch (e: JDOMException) { builder.addModuleEntity(modulePath.moduleName, listOf(ModuleDependencyItem.ModuleSourceDependency), internalEntitySource) throw e } val moduleEntity = builder.addModuleEntity(modulePath.moduleName, listOf(ModuleDependencyItem.ModuleSourceDependency), entitySourceForModuleAndOtherEntities.first) val entitySource = entitySourceForModuleAndOtherEntities.second val moduleGroup = modulePath.group if (moduleGroup != null) { builder.addModuleGroupPathEntity(moduleGroup.split('/'), moduleEntity, entitySource) } val moduleType = moduleOptions["type"] if (moduleType != null) { builder.modifyEntity(moduleEntity) { type = moduleType } } @Suppress("UNCHECKED_CAST") val customModuleOptions = moduleOptions.filter { (key, value) -> key != null && value != null && key !in STANDARD_MODULE_OPTIONS } as Map<String, String> if (customModuleOptions.isNotEmpty()) { builder.addModuleCustomImlDataEntity(null, customModuleOptions, moduleEntity, entitySource) } CUSTOM_MODULE_COMPONENT_SERIALIZER_EP.extensionList.forEach { it.loadComponent(builder, moduleEntity, reader, fileUrl, errorReporter, virtualFileManager) } // Don't forget to load external system options even if custom root serializer exist loadExternalSystemOptions(builder, moduleEntity, reader, externalSystemOptions, externalSystemId, entitySource) loadContentRoots(customRootsSerializer, builder, moduleEntity, reader, customDir, errorReporter, virtualFileManager, moduleEntity.entitySource, false) loadTestModuleProperty(builder, moduleEntity, reader, entitySource) return ModuleLoadedInfo(moduleEntity, customRootsSerializer, customDir) } /** * [loadingAdditionalRoots] - true if we load additional information of the module. For example, content roots that are defined by user * in maven project. */ private fun loadContentRoots(customRootsSerializer: CustomModuleRootsSerializer?, builder: MutableEntityStorage, moduleEntity: ModuleEntity, reader: JpsFileContentReader, customDir: String?, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager, contentRootEntitySource: EntitySource, loadingAdditionalRoots: Boolean) { if (customRootsSerializer != null) { customRootsSerializer.loadRoots(builder, moduleEntity, reader, customDir, fileUrl, internalModuleListSerializer, errorReporter, virtualFileManager) } else { val rootManagerElement = reader.loadComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, getBaseDirPath())?.clone() if (rootManagerElement != null) { loadRootManager(rootManagerElement, moduleEntity, builder, virtualFileManager, contentRootEntitySource, loadingAdditionalRoots) } } } private fun getOtherEntitiesEntitySource(reader: JpsFileContentReader): EntitySource { val moduleOptions = readModuleOptions(reader) val pair = readExternalSystemOptions(reader, moduleOptions) return createEntitySource(pair.second) } protected open fun getBaseDirPath(): String? = null protected open fun readExternalSystemOptions(reader: JpsFileContentReader, moduleOptions: Map<String?, String?>): Pair<Map<String?, String?>, String?> { val externalSystemId = moduleOptions["external.system.id"] ?: if (moduleOptions[ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY] == true.toString()) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID else null return Pair(moduleOptions, externalSystemId) } private fun readModuleOptions(reader: JpsFileContentReader): Map<String?, String?> { val component = reader.loadComponent(fileUrl.url, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, getBaseDirPath()) ?: return emptyMap() return component.getChildren("option").associateBy({ it.getAttributeValue("key") }, { it.getAttributeValue("value") }) } protected open fun loadExternalSystemOptions(builder: MutableEntityStorage, module: ModuleEntity, reader: JpsFileContentReader, externalSystemOptions: Map<String?, String?>, externalSystemId: String?, entitySource: EntitySource) { if (!shouldCreateExternalSystemModuleOptions(externalSystemId, externalSystemOptions, MODULE_OPTIONS_TO_CHECK)) return val optionsEntity = builder.getOrCreateExternalSystemModuleOptions(module, entitySource) builder.modifyEntity(optionsEntity) { externalSystem = externalSystemId externalSystemModuleVersion = externalSystemOptions["external.system.module.version"] linkedProjectPath = externalSystemOptions["external.linked.project.path"] linkedProjectId = externalSystemOptions["external.linked.project.id"] rootProjectPath = externalSystemOptions["external.root.project.path"] externalSystemModuleGroup = externalSystemOptions["external.system.module.group"] externalSystemModuleType = externalSystemOptions["external.system.module.type"] } } internal fun shouldCreateExternalSystemModuleOptions(externalSystemId: String?, externalSystemOptions: Map<String?, String?>, moduleOptionsToCheck: Set<String>): Boolean { if (externalSystemId != null) return true return externalSystemOptions.any { (key, value) -> value != null && key in moduleOptionsToCheck } } private fun loadRootManager(rootManagerElement: Element, moduleEntity: ModuleEntity, builder: MutableEntityStorage, virtualFileManager: VirtualFileUrlManager, contentRotEntitySource: EntitySource, loadingAdditionalRoots: Boolean) { val alreadyLoadedContentRoots = moduleEntity.contentRoots.associateBy { it.url.url } for (contentElement in rootManagerElement.getChildrenAndDetach(CONTENT_TAG)) { val contentRootUrlString = contentElement.getAttributeValueStrict(URL_ATTRIBUTE) // Either we'll load content root right now, or it was already loaded from an external storage var contentRoot = alreadyLoadedContentRoots[contentRootUrlString] if (contentRoot == null) { val contentRootUrl = contentRootUrlString .let { virtualFileManager.fromUrl(it) } val excludePatterns = contentElement.getChildren(EXCLUDE_PATTERN_TAG) .map { it.getAttributeValue(EXCLUDE_PATTERN_ATTRIBUTE) } contentRoot = builder.addContentRootEntity(contentRootUrl, emptyList(), excludePatterns, moduleEntity, contentRotEntitySource) } loadSourceRoots(contentElement, virtualFileManager, builder, contentRoot, contentRotEntitySource) loadContentRootExcludes(contentElement, virtualFileManager, builder, contentRoot, contentRotEntitySource) } fun Element.readScope(): ModuleDependencyItem.DependencyScope { val attributeValue = getAttributeValue(SCOPE_ATTRIBUTE) ?: return ModuleDependencyItem.DependencyScope.COMPILE return try { ModuleDependencyItem.DependencyScope.valueOf(attributeValue) } catch (e: IllegalArgumentException) { ModuleDependencyItem.DependencyScope.COMPILE } } fun Element.isExported() = getAttributeValue(EXPORTED_ATTRIBUTE) != null val moduleLibraryNames = mutableSetOf<String>() var nextUnnamedLibraryIndex = 1 val dependencyItems = rootManagerElement.getChildrenAndDetach(ORDER_ENTRY_TAG).mapTo(ArrayList()) { dependencyElement -> when (val orderEntryType = dependencyElement.getAttributeValue(TYPE_ATTRIBUTE)) { SOURCE_FOLDER_TYPE -> ModuleDependencyItem.ModuleSourceDependency JDK_TYPE -> ModuleDependencyItem.SdkDependency(dependencyElement.getAttributeValueStrict(JDK_NAME_ATTRIBUTE), dependencyElement.getAttributeValue(JDK_TYPE_ATTRIBUTE)) INHERITED_JDK_TYPE -> ModuleDependencyItem.InheritedSdkDependency LIBRARY_TYPE -> { val level = dependencyElement.getAttributeValueStrict(LEVEL_ATTRIBUTE) val parentId = LibraryNameGenerator.getLibraryTableId(level) val libraryId = LibraryId(dependencyElement.getAttributeValueStrict(NAME_ATTRIBUTE), parentId) ModuleDependencyItem.Exportable.LibraryDependency(libraryId, dependencyElement.isExported(), dependencyElement.readScope()) } MODULE_LIBRARY_TYPE -> { val libraryElement = dependencyElement.getChildTagStrict(LIBRARY_TAG) // TODO. Probably we want a fixed name based on hashed library roots val nameAttributeValue = libraryElement.getAttributeValue(NAME_ATTRIBUTE) val originalName = nameAttributeValue ?: "${LibraryNameGenerator.UNNAMED_LIBRARY_NAME_PREFIX}${nextUnnamedLibraryIndex++}" val name = LibraryNameGenerator.generateUniqueLibraryName(originalName) { it in moduleLibraryNames } moduleLibraryNames.add(name) val tableId = LibraryTableId.ModuleLibraryTableId(moduleEntity.symbolicId) loadLibrary(name, libraryElement, tableId, builder, contentRotEntitySource, virtualFileManager, false) val libraryId = LibraryId(name, tableId) ModuleDependencyItem.Exportable.LibraryDependency(libraryId, dependencyElement.isExported(), dependencyElement.readScope()) } MODULE_TYPE -> { val depModuleName = dependencyElement.getAttributeValueStrict(MODULE_NAME_ATTRIBUTE) ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(depModuleName), dependencyElement.isExported(), dependencyElement.readScope(), dependencyElement.getAttributeValue("production-on-test") != null) } else -> throw JDOMException("Unexpected '$TYPE_ATTRIBUTE' attribute in '$ORDER_ENTRY_TAG' tag: $orderEntryType") } } if (dependencyItems.none { it is ModuleDependencyItem.ModuleSourceDependency }) { dependencyItems.add(ModuleDependencyItem.ModuleSourceDependency) } if (!loadingAdditionalRoots) { val inheritedCompilerOutput = rootManagerElement.getAttributeAndDetach(INHERIT_COMPILER_OUTPUT_ATTRIBUTE) val languageLevel = rootManagerElement.getAttributeAndDetach(MODULE_LANGUAGE_LEVEL_ATTRIBUTE) val excludeOutput = rootManagerElement.getChildAndDetach(EXCLUDE_OUTPUT_TAG) != null val compilerOutput = rootManagerElement.getChildAndDetach(OUTPUT_TAG)?.getAttributeValue(URL_ATTRIBUTE) val compilerOutputForTests = rootManagerElement.getChildAndDetach(TEST_OUTPUT_TAG)?.getAttributeValue(URL_ATTRIBUTE) // According to our logic, java settings entity should produce one of the following attributes. // So, if we don't meet one, we don't create a java settings entity if (inheritedCompilerOutput != null || compilerOutput != null) { builder.addJavaModuleSettingsEntity( inheritedCompilerOutput = inheritedCompilerOutput?.toBoolean() ?: false, excludeOutput = excludeOutput, compilerOutput = compilerOutput?.let { virtualFileManager.fromUrl(it) }, compilerOutputForTests = compilerOutputForTests?.let { virtualFileManager.fromUrl(it) }, languageLevelId = languageLevel, module = moduleEntity, source = contentRotEntitySource ) } else if (javaPluginPresent()) { builder addEntity JavaModuleSettingsEntity(true, true, contentRotEntitySource) { this.module = moduleEntity } } } if (!JDOMUtil.isEmpty(rootManagerElement)) { val customImlData = moduleEntity.customImlData if (customImlData == null) { builder.addModuleCustomImlDataEntity( rootManagerTagCustomData = JDOMUtil.write(rootManagerElement), customModuleOptions = emptyMap(), module = moduleEntity, source = contentRotEntitySource ) } else { builder.modifyEntity(customImlData) { rootManagerTagCustomData = JDOMUtil.write(rootManagerElement) } } } if (!loadingAdditionalRoots) { builder.modifyEntity(moduleEntity) { dependencies = dependencyItems } } } private fun loadContentRootExcludes( contentElement: Element, virtualFileManager: VirtualFileUrlManager, builder: MutableEntityStorage, contentRootEntity: ContentRootEntity, entitySource: EntitySource, ) { contentElement .getChildren(EXCLUDE_FOLDER_TAG) .map { virtualFileManager.fromUrl(it.getAttributeValueStrict(URL_ATTRIBUTE)) } .forEach { exclude -> builder addEntity ExcludeUrlEntity(exclude, entitySource) { this.contentRoot = contentRootEntity } } } private fun loadSourceRoots(contentElement: Element, virtualFileManager: VirtualFileUrlManager, builder: MutableEntityStorage, contentRootEntity: ContentRootEntity, sourceRootSource: EntitySource) { val orderOfItems = mutableListOf<VirtualFileUrl>() for (sourceRootElement in contentElement.getChildren(SOURCE_FOLDER_TAG)) { val url = sourceRootElement.getAttributeValueStrict(URL_ATTRIBUTE) val isTestSource = sourceRootElement.getAttributeValue(IS_TEST_SOURCE_ATTRIBUTE)?.toBoolean() == true val type = sourceRootElement.getAttributeValue(SOURCE_ROOT_TYPE_ATTRIBUTE) ?: (if (isTestSource) JAVA_TEST_ROOT_TYPE_ID else JAVA_SOURCE_ROOT_TYPE_ID) val virtualFileUrl = virtualFileManager.fromUrl(url) orderOfItems += virtualFileUrl val sourceRoot = builder.addSourceRootEntity(contentRootEntity, virtualFileUrl, type, sourceRootSource) if (type == JAVA_SOURCE_ROOT_TYPE_ID || type == JAVA_TEST_ROOT_TYPE_ID) { builder.addJavaSourceRootEntity(sourceRoot, sourceRootElement.getAttributeValue(IS_GENERATED_ATTRIBUTE)?.toBoolean() ?: false, sourceRootElement.getAttributeValue(PACKAGE_PREFIX_ATTRIBUTE) ?: "") } else if (type == JAVA_RESOURCE_ROOT_ID || type == JAVA_TEST_RESOURCE_ROOT_ID) { builder.addJavaResourceRootEntity(sourceRoot, sourceRootElement.getAttributeValue(IS_GENERATED_ATTRIBUTE)?.toBoolean() ?: false, sourceRootElement.getAttributeValue(RELATIVE_OUTPUT_PATH_ATTRIBUTE) ?: "") } else { val elem = sourceRootElement.clone() elem.removeAttribute(URL_ATTRIBUTE) elem.removeAttribute(SOURCE_ROOT_TYPE_ATTRIBUTE) if (!JDOMUtil.isEmpty(elem)) { builder.addCustomSourceRootPropertiesEntity(sourceRoot, JDOMUtil.write(elem)) } } } storeSourceRootsOrder(orderOfItems, contentRootEntity, builder) } private fun loadTestModuleProperty(builder: MutableEntityStorage, moduleEntity: ModuleEntity, reader: JpsFileContentReader, entitySource: EntitySource) { if (!TestModuleProperties.testModulePropertiesBridgeEnabled()) return val component = reader.loadComponent(fileUrl.url, TEST_MODULE_PROPERTIES_COMPONENT_NAME) ?: return val productionModuleName = component.getAttribute(PRODUCTION_MODULE_NAME_ATTRIBUTE).value if (productionModuleName.isEmpty()) return builder.modifyEntity(moduleEntity) { this.testProperties = TestModulePropertiesEntity(ModuleId(productionModuleName), entitySource) } } private fun Element.getChildrenAndDetach(cname: String): List<Element> { val result = getChildren(cname).toList() result.forEach { it.detach() } return result } private fun Element.getAttributeAndDetach(name: String): String? { val result = getAttributeValue(name) removeAttribute(name) return result } private fun Element.getChildAndDetach(cname: String): Element? = getChild(cname)?.also { it.detach() } override fun saveEntities(mainEntities: Collection<ModuleEntity>, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, storage: EntityStorage, writer: JpsFileContentWriter) { val module = mainEntities.singleOrNull() if (module != null && acceptsSource(module.entitySource)) { saveModuleEntities(module, entities, storage, writer) } else if (ContentRootEntity::class.java in entities || SourceRootEntity::class.java in entities || ExcludeUrlEntity::class.java in entities) { val contentEntities = entities[ContentRootEntity::class.java] as? List<ContentRootEntity> ?: emptyList() val sourceRootEntities = (entities[SourceRootEntity::class.java] as? List<SourceRootEntity>)?.toMutableSet() ?: mutableSetOf() val excludeRoots = (entities[ExcludeUrlEntity::class.java] as? List<ExcludeUrlEntity>)?.filter { it.contentRoot != null }?.toMutableSet() ?: mutableSetOf() val rootElement = JDomSerializationUtil.createComponentElement(MODULE_ROOT_MANAGER_COMPONENT_NAME) if (contentEntities.isNotEmpty()) { contentEntities.forEach { it.sourceRoots.filter { sourceRootEntity -> acceptsSource(sourceRootEntity.entitySource) }.forEach { sourceRootEntity -> sourceRootEntities.remove(sourceRootEntity) } it.excludedUrls.filter { exclude -> acceptsSource(exclude.entitySource) }.forEach { exclude -> excludeRoots.remove(exclude) } } saveContentEntities(contentEntities, rootElement) writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, rootElement) } if (sourceRootEntities.isNotEmpty() || excludeRoots.isNotEmpty()) { val excludes = excludeRoots.groupBy { it.contentRoot!!.url }.toMutableMap() if (sourceRootEntities.isNotEmpty()) { sourceRootEntities.groupBy { it.contentRoot }.forEach { contentRoot, sourceRoots -> val contentRootTag = Element(CONTENT_TAG) contentRootTag.setAttribute(URL_ATTRIBUTE, contentRoot.url.url) saveSourceRootEntities(sourceRoots, contentRootTag, contentRoot.getSourceRootsComparator()) excludes[contentRoot.url]?.let { saveExcludeUrls(contentRootTag, it) excludes.remove(contentRoot.url) } rootElement.addContent(contentRootTag) writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, rootElement) } } excludes.forEach { url, exclude -> val contentRootTag = Element(CONTENT_TAG) contentRootTag.setAttribute(URL_ATTRIBUTE, url.url) saveExcludeUrls(contentRootTag, exclude) rootElement.addContent(contentRootTag) writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, rootElement) } } } else { writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, null) writer.saveComponent(fileUrl.url, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, null) } createFacetSerializer().saveFacetEntities(module, entities, writer, this::acceptsSource) } protected open fun createFacetSerializer(): FacetsSerializer { return FacetsSerializer(fileUrl, internalEntitySource, JpsFacetSerializer.FACET_MANAGER_COMPONENT_NAME, null, false) } protected open fun acceptsSource(entitySource: EntitySource): Boolean { return entitySource is JpsFileEntitySource || entitySource is CustomModuleEntitySource || entitySource is JpsFileDependentEntitySource && (entitySource as? JpsImportedEntitySource)?.storedExternally != true } private fun saveModuleEntities(module: ModuleEntity, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, storage: EntityStorage, writer: JpsFileContentWriter) { val externalSystemOptions = module.exModuleOptions val customImlData = module.customImlData saveModuleOptions(externalSystemOptions, module.type, customImlData, writer) val moduleOptions = customImlData?.customModuleOptions val customSerializerId = moduleOptions?.get(JpsProjectLoader.CLASSPATH_ATTRIBUTE) if (customSerializerId != null) { val serializer = CustomModuleRootsSerializer.EP_NAME.extensionList.firstOrNull { it.id == customSerializerId } if (serializer != null) { val customDir = moduleOptions[JpsProjectLoader.CLASSPATH_DIR_ATTRIBUTE] serializer.saveRoots(module, entities, writer, customDir, fileUrl, storage, virtualFileManager) writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, null) } else { LOG.warn("Classpath storage provider $customSerializerId not found") } } else { saveRootManagerElement(module, customImlData, entities, writer) } for (it in CUSTOM_MODULE_COMPONENT_SERIALIZER_EP.extensionList) { it.saveComponent(module, fileUrl, writer) } saveTestModuleProperty(module, writer) } private fun saveRootManagerElement(module: ModuleEntity, customImlData: ModuleCustomImlDataEntity?, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, writer: JpsFileContentWriter) { val rootManagerElement = JDomSerializationUtil.createComponentElement(MODULE_ROOT_MANAGER_COMPONENT_NAME) saveJavaSettings(module.javaSettings, rootManagerElement) if (customImlData != null) { val rootManagerTagCustomData = customImlData.rootManagerTagCustomData if (rootManagerTagCustomData != null) { val element = JDOMUtil.load(StringReader(rootManagerTagCustomData)) JDOMUtil.merge(rootManagerElement, element) } } rootManagerElement.attributes.sortWith(knownAttributesComparator) //todo ensure that custom data is written in proper order val contentEntities = module.contentRoots.filter { acceptsSource(it.entitySource) }.sortedBy { it.url.url } saveContentEntities(contentEntities, rootManagerElement) @Suppress("UNCHECKED_CAST") val moduleLibraries = (entities[LibraryEntity::class.java] as List<LibraryEntity>? ?: emptyList()).associateBy { it.name } module.dependencies.forEach { rootManagerElement.addContent(saveDependencyItem(it, moduleLibraries)) } writer.saveComponent(fileUrl.url, MODULE_ROOT_MANAGER_COMPONENT_NAME, rootManagerElement) } private fun saveContentEntities(contentEntities: List<ContentRootEntity>, rootManagerElement: Element) { contentEntities.forEach { contentEntry -> val contentRootTag = Element(CONTENT_TAG) contentRootTag.setAttribute(URL_ATTRIBUTE, contentEntry.url.url) saveSourceRootEntities(contentEntry.sourceRoots.filter { acceptsSource(it.entitySource) }, contentRootTag, contentEntry.getSourceRootsComparator()) saveExcludeUrls(contentRootTag, contentEntry.excludedUrls.filter { acceptsSource(it.entitySource) }) contentEntry.excludedPatterns.forEach { contentRootTag.addContent(Element(EXCLUDE_PATTERN_TAG).setAttribute(EXCLUDE_PATTERN_ATTRIBUTE, it)) } rootManagerElement.addContent(contentRootTag) } } private fun saveExcludeUrls(contentRootTag: Element, excludeUrls: List<ExcludeUrlEntity>) { excludeUrls.forEach { contentRootTag.addContent(Element(EXCLUDE_FOLDER_TAG).setAttribute(URL_ATTRIBUTE, it.url.url)) } } private fun saveSourceRootEntities(sourceRoots: Collection<SourceRootEntity>, contentRootTag: Element, sourceRootEntityComparator: Comparator<SourceRootEntity>) { var mySourceRoots = sourceRoots mySourceRoots = mySourceRoots.sortedWith(sourceRootEntityComparator) mySourceRoots.forEach { contentRootTag.addContent(saveSourceRoot(it)) } } private fun createEntitySource(externalSystemId: String?): EntitySource { if (externalSystemId == null) return internalEntitySource return createExternalEntitySource(externalSystemId) } protected open fun createExternalEntitySource(externalSystemId: String): EntitySource = JpsImportedEntitySource(internalEntitySource, externalSystemId, false) private fun javaPluginPresent() = PluginManagerCore.getPlugin(PluginId.findId("com.intellij.java")) != null private fun saveJavaSettings(javaSettings: JavaModuleSettingsEntity?, rootManagerElement: Element) { if (javaSettings == null) { if (javaPluginPresent()) { rootManagerElement.setAttribute(INHERIT_COMPILER_OUTPUT_ATTRIBUTE, true.toString()) rootManagerElement.addContent(Element(EXCLUDE_OUTPUT_TAG)) } return } if (javaSettings.inheritedCompilerOutput) { rootManagerElement.setAttribute(INHERIT_COMPILER_OUTPUT_ATTRIBUTE, true.toString()) } else { val outputUrl = javaSettings.compilerOutput?.url if (outputUrl != null) { rootManagerElement.addContent(Element(OUTPUT_TAG).setAttribute(URL_ATTRIBUTE, outputUrl)) } val testOutputUrl = javaSettings.compilerOutputForTests?.url if (testOutputUrl != null) { rootManagerElement.addContent(Element(TEST_OUTPUT_TAG).setAttribute(URL_ATTRIBUTE, testOutputUrl)) } } if (javaSettings.excludeOutput) { rootManagerElement.addContent(Element(EXCLUDE_OUTPUT_TAG)) } javaSettings.languageLevelId?.let { rootManagerElement.setAttribute(MODULE_LANGUAGE_LEVEL_ATTRIBUTE, it) } } private fun saveDependencyItem(dependencyItem: ModuleDependencyItem, moduleLibraries: Map<String, LibraryEntity>) = when (dependencyItem) { is ModuleDependencyItem.ModuleSourceDependency -> createOrderEntryTag(SOURCE_FOLDER_TYPE).setAttribute("forTests", "false") is ModuleDependencyItem.SdkDependency -> createOrderEntryTag(JDK_TYPE).apply { setAttribute(JDK_NAME_ATTRIBUTE, dependencyItem.sdkName) val sdkType = dependencyItem.sdkType setAttribute(JDK_TYPE_ATTRIBUTE, sdkType) } is ModuleDependencyItem.InheritedSdkDependency -> createOrderEntryTag(INHERITED_JDK_TYPE) is ModuleDependencyItem.Exportable.LibraryDependency -> { val library = dependencyItem.library if (library.tableId is LibraryTableId.ModuleLibraryTableId) { createOrderEntryTag(MODULE_LIBRARY_TYPE).apply { setExportedAndScopeAttributes(dependencyItem) addContent(saveLibrary(moduleLibraries.getValue(library.name), null, false)) } } else { createOrderEntryTag(LIBRARY_TYPE).apply { setExportedAndScopeAttributes(dependencyItem) setAttribute(NAME_ATTRIBUTE, library.name) setAttribute(LEVEL_ATTRIBUTE, library.tableId.level) } } } is ModuleDependencyItem.Exportable.ModuleDependency -> createOrderEntryTag(MODULE_TYPE).apply { setAttribute(MODULE_NAME_ATTRIBUTE, dependencyItem.module.name) setExportedAndScopeAttributes(dependencyItem) if (dependencyItem.productionOnTest) { setAttribute("production-on-test", "") } } } protected open fun saveModuleOptions(externalSystemOptions: ExternalSystemModuleOptionsEntity?, moduleType: String?, customImlData: ModuleCustomImlDataEntity?, writer: JpsFileContentWriter) { val optionsMap = TreeMap<String, String?>() if (externalSystemOptions != null) { if (externalSystemOptions.externalSystem == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID) { optionsMap[ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY] = true.toString() } else { optionsMap["external.system.id"] = externalSystemOptions.externalSystem } optionsMap["external.root.project.path"] = externalSystemOptions.rootProjectPath optionsMap["external.linked.project.id"] = externalSystemOptions.linkedProjectId optionsMap["external.linked.project.path"] = externalSystemOptions.linkedProjectPath optionsMap["external.system.module.type"] = externalSystemOptions.externalSystemModuleType optionsMap["external.system.module.group"] = externalSystemOptions.externalSystemModuleGroup optionsMap["external.system.module.version"] = externalSystemOptions.externalSystemModuleVersion } optionsMap["type"] = moduleType if (customImlData != null) { optionsMap.putAll(customImlData.customModuleOptions) } val componentTag = JDomSerializationUtil.createComponentElement(DEPRECATED_MODULE_MANAGER_COMPONENT_NAME) for ((name, value) in optionsMap) { if (value != null) { componentTag.addContent(Element("option").setAttribute("key", name).setAttribute("value", value)) } } if (componentTag.children.isNotEmpty()) { writer.saveComponent(fileUrl.url, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, componentTag) } } private fun Element.setExportedAndScopeAttributes(item: ModuleDependencyItem.Exportable) { if (item.exported) { setAttribute(EXPORTED_ATTRIBUTE, "") } if (item.scope != ModuleDependencyItem.DependencyScope.COMPILE) { setAttribute(SCOPE_ATTRIBUTE, item.scope.name) } } private fun createOrderEntryTag(type: String) = Element(ORDER_ENTRY_TAG).setAttribute(TYPE_ATTRIBUTE, type) private fun saveSourceRoot(sourceRoot: SourceRootEntity): Element { val sourceRootTag = Element(SOURCE_FOLDER_TAG) sourceRootTag.setAttribute(URL_ATTRIBUTE, sourceRoot.url.url) val rootType = sourceRoot.rootType if (rootType !in listOf(JAVA_SOURCE_ROOT_TYPE_ID, JAVA_TEST_ROOT_TYPE_ID)) { sourceRootTag.setAttribute(SOURCE_ROOT_TYPE_ATTRIBUTE, rootType) } val javaRootProperties = sourceRoot.asJavaSourceRoot() if (javaRootProperties != null) { sourceRootTag.setAttribute(IS_TEST_SOURCE_ATTRIBUTE, (rootType == JAVA_TEST_ROOT_TYPE_ID).toString()) val packagePrefix = javaRootProperties.packagePrefix if (packagePrefix.isNotEmpty()) { sourceRootTag.setAttribute(PACKAGE_PREFIX_ATTRIBUTE, packagePrefix) } if (javaRootProperties.generated) { sourceRootTag.setAttribute(IS_GENERATED_ATTRIBUTE, true.toString()) } } val javaResourceRootProperties = sourceRoot.asJavaResourceRoot() if (javaResourceRootProperties != null) { val relativeOutputPath = javaResourceRootProperties.relativeOutputPath if (relativeOutputPath.isNotEmpty()) { sourceRootTag.setAttribute(RELATIVE_OUTPUT_PATH_ATTRIBUTE, relativeOutputPath) } if (javaResourceRootProperties.generated) { sourceRootTag.setAttribute(IS_GENERATED_ATTRIBUTE, true.toString()) } } val customProperties = sourceRoot.customSourceRootProperties if (customProperties != null) { val element = JDOMUtil.load(StringReader(customProperties.propertiesXmlTag)) JDOMUtil.merge(sourceRootTag, element) } return sourceRootTag } private fun saveTestModuleProperty(moduleEntity: ModuleEntity, writer: JpsFileContentWriter) { if (!TestModuleProperties.testModulePropertiesBridgeEnabled()) return val testProperties = moduleEntity.testProperties ?: return val testModulePropertyTag = Element(TEST_MODULE_PROPERTIES_COMPONENT_NAME) testModulePropertyTag.setAttribute(PRODUCTION_MODULE_NAME_ATTRIBUTE, testProperties.productionModuleId.presentableName) writer.saveComponent(fileUrl.url, TEST_MODULE_PROPERTIES_COMPONENT_NAME, testModulePropertyTag) } override val additionalEntityTypes: List<Class<out WorkspaceEntity>> get() = listOf(SourceRootOrderEntity::class.java) override fun toString(): String = "ModuleImlFileEntitiesSerializer($fileUrl)" companion object { private val LOG = logger<ModuleImlFileEntitiesSerializer>() // The comparator has reversed priority. So, the last entry of this list will be printed as a first attribute in the xml tag. private val orderOfKnownAttributes = listOf( INHERIT_COMPILER_OUTPUT_ATTRIBUTE, MODULE_LANGUAGE_LEVEL_ATTRIBUTE, URL_ATTRIBUTE, "name" ) // Reversed comparator for attributes. Unknown attributes will be pushed to the end (since they return -1 in the [indexOf]). private val knownAttributesComparator = Comparator<Attribute> { o1, o2 -> orderOfKnownAttributes.indexOf(o1.name).compareTo(orderOfKnownAttributes.indexOf(o2.name)) }.reversed() private val CUSTOM_MODULE_COMPONENT_SERIALIZER_EP = ExtensionPointName.create<CustomModuleComponentSerializer>("com.intellij.workspaceModel.customModuleComponentSerializer") } } internal open class ModuleListSerializerImpl(override val fileUrl: String, private val virtualFileManager: VirtualFileUrlManager, private val externalModuleListSerializer: JpsModuleListSerializer? = null, private val externalStorageConfigurationManager: ExternalStorageConfigurationManager? = null) : JpsModuleListSerializer { companion object { internal fun createModuleEntitiesSerializer(fileUrl: VirtualFileUrl, moduleGroup: String?, source: JpsFileEntitySource, virtualFileManager: VirtualFileUrlManager, internalModuleListSerializer: JpsModuleListSerializer? = null, externalModuleListSerializer: JpsModuleListSerializer? = null, externalStorageConfigurationManager: ExternalStorageConfigurationManager? = null) = ModuleImlFileEntitiesSerializer(ModulePath(JpsPathUtil.urlToPath(fileUrl.url), moduleGroup), fileUrl, source, virtualFileManager, internalModuleListSerializer, externalModuleListSerializer, externalStorageConfigurationManager) } override val isExternalStorage: Boolean get() = false open val componentName: String get() = "ProjectModuleManager" override val entitySourceFilter: (EntitySource) -> Boolean get() = { it is JpsFileEntitySource || it is CustomModuleEntitySource || it is JpsFileDependentEntitySource && (it as? JpsImportedEntitySource)?.storedExternally != true } override fun getFileName(entity: ModuleEntity): String { return "${entity.name}.iml" } override fun createSerializer(internalSource: JpsFileEntitySource, fileUrl: VirtualFileUrl, moduleGroup: String?): JpsFileEntitiesSerializer<ModuleEntity> { return createModuleEntitiesSerializer(fileUrl, moduleGroup, internalSource, virtualFileManager, this, externalModuleListSerializer, externalStorageConfigurationManager) } override fun loadFileList(reader: JpsFileContentReader, virtualFileManager: VirtualFileUrlManager): List<Pair<VirtualFileUrl, String?>> { val moduleManagerTag = reader.loadComponent(fileUrl, componentName) ?: return emptyList() return ModuleManagerBridgeImpl.getPathsToModuleFiles(moduleManagerTag).map { Path.of(it.path).toVirtualFileUrl(virtualFileManager) to it.group } } override fun saveEntitiesList(entities: Sequence<ModuleEntity>, writer: JpsFileContentWriter) { val entitiesToSave = entities .filter { entitySourceFilter(it.entitySource) || it.contentRoots.any { cr -> entitySourceFilter(cr.entitySource) } || it.sourceRoots.any { sr -> entitySourceFilter(sr.entitySource) } || it.contentRoots.any { cr -> cr.excludedUrls.any { ex -> entitySourceFilter(ex.entitySource) } } || it.facets.any { entitySourceFilter(it.entitySource) } } .mapNotNullTo(ArrayList()) { module -> getSourceToSave(module)?.let { Pair(it, module) } } .sortedBy { it.second.name } val componentTag: Element? if (entitiesToSave.isNotEmpty()) { val modulesTag = Element("modules") entitiesToSave .forEach { (source, module) -> val moduleTag = Element("module") val fileUrl = getModuleFileUrl(source, module) moduleTag.setAttribute("fileurl", fileUrl) moduleTag.setAttribute("filepath", JpsPathUtil.urlToPath(fileUrl)) module.groupPath?.let { moduleTag.setAttribute("group", it.path.joinToString("/")) } modulesTag.addContent(moduleTag) } componentTag = JDomSerializationUtil.createComponentElement(componentName) componentTag.addContent(modulesTag) } else { componentTag = null } writer.saveComponent(fileUrl, componentName, componentTag) } protected open fun getSourceToSave(module: ModuleEntity): JpsFileEntitySource.FileInDirectory? { val entitySource = module.entitySource if (entitySource is CustomModuleEntitySource) { return entitySource.internalSource as? JpsFileEntitySource.FileInDirectory } if (entitySource is JpsFileDependentEntitySource) { return entitySource.originalSource as? JpsFileEntitySource.FileInDirectory } return entitySource as? JpsFileEntitySource.FileInDirectory } override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) { writer.saveComponent(fileUrl, JpsFacetSerializer.FACET_MANAGER_COMPONENT_NAME, null) writer.saveComponent(fileUrl, MODULE_ROOT_MANAGER_COMPONENT_NAME, null) writer.saveComponent(fileUrl, DEPRECATED_MODULE_MANAGER_COMPONENT_NAME, null) writer.saveComponent(fileUrl, TEST_MODULE_PROPERTIES_COMPONENT_NAME, null) } private fun getModuleFileUrl(source: JpsFileEntitySource.FileInDirectory, module: ModuleEntity) = source.directory.url + "/" + module.name + ".iml" override fun toString(): String = "ModuleListSerializerImpl($fileUrl)" } fun storeSourceRootsOrder(orderOfItems: MutableList<VirtualFileUrl>, contentRootEntity: ContentRootEntity, builder: MutableEntityStorage) { if (orderOfItems.size > 1) { // Save the order in which sourceRoots appear in the module val orderingEntity = contentRootEntity.sourceRootOrder if (orderingEntity == null) { builder.addEntity(SourceRootOrderEntity(orderOfItems, contentRootEntity.entitySource) { this.contentRootEntity = contentRootEntity }) } else { builder.modifyEntity(orderingEntity) { orderOfSourceRoots = orderOfItems } } } } fun ContentRootEntity.getSourceRootsComparator(): Comparator<SourceRootEntity> { val order = (sourceRootOrder?.orderOfSourceRoots ?: emptyList()).withIndex().associateBy({ it.value }, { it.index }) return compareBy<SourceRootEntity> { order[it.url] ?: order.size }.thenBy { it.url.url } }
apache-2.0
27af4ed0df39d9b457a298b9274165cd
50.161844
177
0.702659
5.80411
false
false
false
false
JetBrains/intellij-community
python/src/com/jetbrains/python/packaging/toolwindow/PyPackagingToolWindowPanel.kt
1
19344
// 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.jetbrains.python.packaging.toolwindow import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.components.service import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.ui.* import com.intellij.ui.components.* import com.intellij.ui.dsl.builder.* import com.intellij.ui.jcef.JCEFHtmlPanel import com.intellij.util.Alarm import com.intellij.util.Alarm.ThreadToUse import com.intellij.util.SingleAlarm import com.intellij.util.childScope import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import com.intellij.util.ui.NamedColorUtil import com.intellij.util.ui.UIUtil import com.jetbrains.python.PyBundle.message import com.jetbrains.python.packaging.PyPackageUtil import com.jetbrains.python.packaging.common.PythonLocalPackageSpecification import com.jetbrains.python.packaging.common.PythonPackageDetails import com.jetbrains.python.packaging.common.PythonVcsPackageSpecification import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.awt.BorderLayout import java.awt.Component import java.awt.Dimension import java.awt.event.ActionEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* import javax.swing.event.DocumentEvent class PyPackagingToolWindowPanel(private val project: Project, toolWindow: ToolWindow) : SimpleToolWindowPanel(false, true), Disposable { private val packagingScope = ApplicationManager.getApplication().coroutineScope.childScope(Dispatchers.Default) private var selectedPackage: DisplayablePackage? = null private var selectedPackageDetails: PythonPackageDetails? = null // UI elements private val packageNameLabel = JLabel().apply { font = JBFont.h4().asBold(); isVisible = false } private val versionLabel = JLabel().apply { isVisible = false } private val documentationLink = HyperlinkLabel(message("python.toolwindow.packages.documentation.link")).apply { addHyperlinkListener { if (documentationUrl != null) BrowserUtil.browse(documentationUrl!!) } isVisible = false } private val searchTextField: SearchTextField private val searchAlarm: Alarm private val installButton: JBOptionButton private val uninstallAction: JComponent private val progressBar: JProgressBar private val versionSelector: JBComboBoxLabel private val descriptionPanel: JCEFHtmlPanel private var documentationUrl: String? = null private val packageListPanel: JPanel private val tablesView: PyPackagingTablesView private val noPackagePanel = JBPanelWithEmptyText().apply { emptyText.text = message("python.toolwindow.packages.description.panel.placeholder") } // layout private var mainPanel: JPanel? = null private var splitter: OnePixelSplitter? = null private val leftPanel: JScrollPane private val rightPanel: JComponent internal var contentVisible: Boolean get() = mainPanel!!.isVisible set(value) { mainPanel!!.isVisible = value } private val latestText: String get() = message("python.toolwindow.packages.latest.version.label") private val fromVcsText: String get() = message("python.toolwindow.packages.add.package.from.vcs") private val fromDiscText: String get() = message("python.toolwindow.packages.add.package.from.disc") init { val service = project.service<PyPackagingToolWindowService>() Disposer.register(service, this) withEmptyText(message("python.toolwindow.packages.no.interpreter.text")) descriptionPanel = PyPackagingJcefHtmlPanel(service.project) Disposer.register(toolWindow.disposable, descriptionPanel) versionSelector = JBComboBoxLabel().apply { text = latestText isVisible = false addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent?) { val versions = listOf(latestText) + (selectedPackageDetails?.availableVersions ?: emptyList()) JBPopupFactory.getInstance().createListPopup( object : BaseListPopupStep<String>(null, versions) { override fun onChosen(@NlsContexts.Label selectedValue: String, finalChoice: Boolean): PopupStep<*>? { [email protected] = selectedValue return FINAL_CHOICE } }, 8).showUnderneathOf(this@apply) } }) } // todo[akniazev]: add options to install with args installButton = JBOptionButton(null, null).apply { isVisible = false } val uninstallToolbar = ActionManager.getInstance() .createActionToolbar(ActionPlaces.TOOLWINDOW_CONTENT, DefaultActionGroup(DefaultActionGroup().apply { add(object : AnAction(message("python.toolwindow.packages.delete.package")) { override fun actionPerformed(e: AnActionEvent) { if (selectedPackage is InstalledPackage) { packagingScope.launch(Dispatchers.Main) { startProgress() withContext(Dispatchers.IO) { service.deletePackage(selectedPackage as InstalledPackage) } stopProgress() } } else error("Trying to delete package, that is not InstalledPackage") } }) isPopup = true with(templatePresentation) { putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true) icon = AllIcons.Actions.More } }), true) uninstallToolbar.targetComponent = this uninstallAction = uninstallToolbar.component progressBar = JProgressBar(JProgressBar.HORIZONTAL).apply { maximumSize.width = 200 minimumSize.width = 200 preferredSize.width = 200 isVisible = false isIndeterminate = true } packageListPanel = JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) alignmentX = LEFT_ALIGNMENT background = UIUtil.getListBackground() } tablesView = PyPackagingTablesView(project, packageListPanel, this) leftPanel = ScrollPaneFactory.createScrollPane(packageListPanel, true) rightPanel = borderPanel { add(borderPanel { border = SideBorder(JBColor.GRAY, SideBorder.BOTTOM) preferredSize = Dimension(preferredSize.width, 50) minimumSize = Dimension(minimumSize.width, 50) maximumSize = Dimension(maximumSize.width, 50) add(boxPanel { add(Box.createHorizontalStrut(10)) add(packageNameLabel) add(Box.createHorizontalStrut(10)) add(documentationLink) }, BorderLayout.WEST) add(boxPanel { alignmentX = Component.RIGHT_ALIGNMENT add(progressBar) add(versionSelector) add(versionLabel) add(installButton) add(uninstallAction) add(Box.createHorizontalStrut(10)) }, BorderLayout.EAST) }, BorderLayout.NORTH) add(descriptionPanel.component, BorderLayout.CENTER) } searchTextField = object : SearchTextField(false) { init { preferredSize = Dimension(250, 30) minimumSize = Dimension(250, 30) maximumSize = Dimension(250, 30) textEditor.border = JBUI.Borders.empty(0, 6, 0, 0) textEditor.isOpaque = true textEditor.emptyText.text = message("python.toolwindow.packages.search.text.placeholder") } override fun onFieldCleared() { service.handleSearch("") } } searchAlarm = SingleAlarm({ service.handleSearch(searchTextField.text.trim()) }, 500, service, ThreadToUse.SWING_THREAD, ModalityState.NON_MODAL) searchTextField.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { searchAlarm.cancelAndRequest() } }) initOrientation(service, true) trackOrientation(service) } private fun initOrientation(service: PyPackagingToolWindowService, horizontal: Boolean) { val second = if (splitter?.secondComponent == rightPanel) rightPanel else noPackagePanel val proportionKey = if (horizontal) HORIZONTAL_SPLITTER_KEY else VERTICAL_SPLITTER_KEY splitter = OnePixelSplitter(!horizontal, proportionKey, 0.3f).apply { firstComponent = leftPanel secondComponent = second } val actionGroup = DefaultActionGroup() actionGroup.add(object : AnAction({ message("python.toolwindow.packages.reload.repositories.action")}, AllIcons.Actions.Refresh) { override fun actionPerformed(e: AnActionEvent) { service.reloadPackages() } }) actionGroup.add(object : AnAction({ message("python.toolwindow.packages.manage.repositories.action") }, AllIcons.General.GearPlain) { override fun actionPerformed(e: AnActionEvent) { service.manageRepositories() } }) val actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLWINDOW_CONTENT, actionGroup,true) actionToolbar.targetComponent = this val installFromLocationLink = DropDownLink(message("python.toolwindow.packages.add.package.action"), listOf(fromVcsText, fromDiscText)) { val specification = when (it) { fromDiscText -> showInstallFromDiscDialog(service) fromVcsText -> showInstallFromVcsDialog(service) else -> throw IllegalStateException("Unknown operation") } if (specification != null) { packagingScope.launch { service.installPackage(specification) } } } mainPanel = borderPanel { val topToolbar = boxPanel { border = SideBorder(NamedColorUtil.getBoundsColor(), SideBorder.BOTTOM) preferredSize = Dimension(preferredSize.width, 30) minimumSize = Dimension(minimumSize.width, 30) maximumSize = Dimension(maximumSize.width, 30) add(searchTextField) actionToolbar.component.maximumSize = Dimension(70, actionToolbar.component.maximumSize.height) add(actionToolbar.component) add(installFromLocationLink) } add(topToolbar, BorderLayout.NORTH) add(splitter!!, BorderLayout.CENTER) } setContent(mainPanel!!) } private fun showInstallFromVcsDialog(service: PyPackagingToolWindowService): PythonVcsPackageSpecification? { var editable = false var link = "" val systems = listOf(message("python.toolwindow.packages.add.package.vcs.git"), message("python.toolwindow.packages.add.package.vcs.svn"), message("python.toolwindow.packages.add.package.vcs.hg"), message("python.toolwindow.packages.add.package.vcs.bzr")) var vcs = systems.first() val panel = panel { row { comboBox(systems) .bindItem({ vcs }, { vcs = it!! }) textField() .columns(COLUMNS_MEDIUM) .bindText({ link }, { link = it }) .align(AlignX.FILL) } row { checkBox(message("python.toolwindow.packages.add.package.as.editable")) .bindSelected({ editable }, { editable = it }) } } val shouldInstall = dialog(message("python.toolwindow.packages.add.package.dialog.title"), panel, project = service.project, resizable = true).showAndGet() if (shouldInstall) { val prefix = when (vcs) { message("python.toolwindow.packages.add.package.vcs.git") -> "git+" message("python.toolwindow.packages.add.package.vcs.svn") -> "svn+" message("python.toolwindow.packages.add.package.vcs.hg") -> "hg+" message("python.toolwindow.packages.add.package.vcs.bzr") -> "bzr+" else -> throw IllegalStateException("Unknown VCS") } return PythonVcsPackageSpecification(link, link, prefix, editable) } return null } private fun showInstallFromDiscDialog(service: PyPackagingToolWindowService): PythonLocalPackageSpecification? { var editable = false val textField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(message("python.toolwindow.packages.add.package.path.selector"), "", service.project, FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) } val panel = panel { row(message("python.toolwindow.packages.add.package.path")) { cell(textField) .columns(COLUMNS_MEDIUM) .align(AlignX.FILL) } row { checkBox(message("python.toolwindow.packages.add.package.as.editable")) .bindSelected({ editable }, { editable = it }) } } val shouldInstall = dialog(message("python.toolwindow.packages.add.package.dialog.title"), panel, project = service.project, resizable = true).showAndGet() return if (shouldInstall) PythonLocalPackageSpecification(textField.text, textField.text, editable) else null } private fun trackOrientation(service: PyPackagingToolWindowService) { service.project.messageBus.connect(service).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener { var myHorizontal = true override fun stateChanged(toolWindowManager: ToolWindowManager) { val toolWindow = toolWindowManager.getToolWindow("Python Packages") if (toolWindow == null || toolWindow.isDisposed) return val isHorizontal = toolWindow.anchor.isHorizontal if (myHorizontal != isHorizontal) { myHorizontal = isHorizontal val content = toolWindow.contentManager.contents.find { it?.component is PyPackagingToolWindowPanel } val panel = content?.component as? PyPackagingToolWindowPanel ?: return panel.initOrientation(service, myHorizontal) } } }) } fun packageSelected(selectedPackage: DisplayablePackage) { val service = project.service<PyPackagingToolWindowService>() val managementEnabled = PyPackageUtil.packageManagementEnabled(service.currentSdk, true, false) showHeaderForPackage(selectedPackage, managementEnabled) this.selectedPackage = selectedPackage packagingScope.launch(Dispatchers.IO) { val packageDetails = service.detailsForPackage(selectedPackage) val installActions = if (managementEnabled) { PythonPackagingToolwindowActionProvider.EP_NAME .extensionList .firstNotNullOf { it.getInstallActions(packageDetails, service.manager) } } else emptyList() withContext(Dispatchers.Main) { selectedPackageDetails = packageDetails if (splitter?.secondComponent != rightPanel) { splitter!!.secondComponent = rightPanel } val renderedDescription = with(packageDetails) { when { !description.isNullOrEmpty() -> service.convertToHTML(descriptionContentType, description!!) !summary.isNullOrEmpty() -> service.wrapHtml(summary!!) else -> NO_DESCRIPTION } } descriptionPanel.setHtml(renderedDescription) documentationUrl = packageDetails.documentationUrl documentationLink.isVisible = documentationUrl != null if (installActions.isNotEmpty()) { installButton.action = wrapAction(installActions.first(), packageDetails) if (installActions.size > 1) { installButton.options = installActions .asSequence().drop(1).map { wrapAction(it, packageDetails) }.toList().toTypedArray() } installButton.repaint() } else hideInstallableControls() } } } private fun wrapAction(installAction: PythonPackageInstallAction, details: PythonPackageDetails): Action { return object : AbstractAction(installAction.text) { override fun actionPerformed(e: ActionEvent?) { val version = if (versionSelector.text == latestText) null else versionSelector.text packagingScope.launch(Dispatchers.IO) { val specification = details.toPackageSpecification(version) installAction.installPackage(specification) } } } } fun showSearchResult(installed: List<InstalledPackage>, repoData: List<PyPackagesViewData>) { tablesView.showSearchResult(installed, repoData) } fun resetSearch(installed: List<InstalledPackage>, repos: List<PyPackagesViewData>) { tablesView.resetSearch(installed, repos) } fun startProgress() { progressBar.isVisible = true hideInstallableControls() hideInstalledControls() } fun stopProgress() { progressBar.isVisible = false } private fun showInstalledControls(managementSupported: Boolean) { hideInstallableControls() progressBar.isVisible = false versionLabel.isVisible = true uninstallAction.isVisible = managementSupported } private fun showInstallableControls(managementSupported: Boolean) { hideInstalledControls() progressBar.isVisible = false versionSelector.isVisible = managementSupported versionSelector.text = latestText installButton.isVisible = managementSupported } private fun hideInstalledControls() { versionLabel.isVisible = false uninstallAction.isVisible = false } private fun hideInstallableControls() { installButton.isVisible = false versionSelector.isVisible = false } private fun showHeaderForPackage(selectedPackage: DisplayablePackage, managementSupported: Boolean) { packageNameLabel.text = selectedPackage.name packageNameLabel.isVisible = true documentationLink.isVisible = false if (selectedPackage is InstalledPackage) { @Suppress("HardCodedStringLiteral") versionLabel.text = selectedPackage.instance.version showInstalledControls(managementSupported) } else { showInstallableControls(managementSupported) } } fun setEmpty() { hideInstalledControls() hideInstallableControls() listOf(packageNameLabel, packageNameLabel, documentationLink).forEach { it.isVisible = false } splitter?.secondComponent = noPackagePanel } override fun dispose() { packagingScope.cancel() } companion object { private const val HORIZONTAL_SPLITTER_KEY = "Python.PackagingToolWindow.Horizontal" private const val VERTICAL_SPLITTER_KEY = "Python.PackagingToolWindow.Vertical" val NO_DESCRIPTION: String get() = message("python.toolwindow.packages.no.description.placeholder") } }
apache-2.0
c6756912531bf09270fa133f345addf6
37.923541
159
0.712883
5.029641
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/override-implement-k2/src/org/jetbrains/kotlin/idea/core/overrideImplement/KtGenerateMembersHandler.kt
1
15414
// 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.core.overrideImplement import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.idea.core.insertMembersAfter import org.jetbrains.kotlin.idea.core.moveCaretIntoGeneratedElement import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.renderer.declarations.impl.KtDeclarationRendererForSource import org.jetbrains.kotlin.analysis.api.renderer.declarations.modifiers.renderers.KtRendererModifierFilter import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClassBody import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.prevSiblingOfSameType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull @ApiStatus.Internal abstract class KtGenerateMembersHandler( final override val toImplement: Boolean ) : AbstractGenerateMembersHandler<KtClassMember>() { @OptIn(KtAllowAnalysisOnEdt::class) override fun generateMembers( editor: Editor, classOrObject: KtClassOrObject, selectedElements: Collection<KtClassMember>, copyDoc: Boolean ) { // Using allowAnalysisOnEdt here because we don't want to pre-populate all possible textual overrides before user selection. val (commands, insertedBlocks) = allowAnalysisOnEdt { val entryMembers = analyze(classOrObject) { this.generateMembers(editor, classOrObject, selectedElements, copyDoc) } val insertedBlocks = insertMembersAccordingToPreferredOrder(entryMembers, editor, classOrObject) // Reference shortening is done in a separate analysis session because the session need to be aware of the newly generated // members. val commands = analyze(classOrObject) { insertedBlocks.mapNotNull { block -> val declarations = block.declarations.mapNotNull { it.element } val first = declarations.firstOrNull() ?: return@mapNotNull null val last = declarations.last() collectPossibleReferenceShortenings(first.containingKtFile, TextRange(first.startOffset, last.endOffset)) } } commands to insertedBlocks } runWriteAction { commands.forEach { it.invokeShortening() } val project = classOrObject.project val codeStyleManager = CodeStyleManager.getInstance(project) insertedBlocks.forEach { block -> block.declarations.forEach { declaration -> declaration.element?.let { element -> codeStyleManager.reformat( element ) } } } insertedBlocks.firstOrNull()?.declarations?.firstNotNullOfOrNull { it.element }?.let { moveCaretIntoGeneratedElement(editor, it) } } } @OptIn(ExperimentalStdlibApi::class) private fun KtAnalysisSession.generateMembers( editor: Editor, currentClass: KtClassOrObject, selectedElements: Collection<KtClassMember>, copyDoc: Boolean ): List<MemberEntry> { if (selectedElements.isEmpty()) return emptyList() val selectedMemberSymbolsAndGeneratedPsi: Map<KtCallableSymbol, KtCallableDeclaration> = selectedElements.associate { it.symbol to generateMember(currentClass.project, it, currentClass, copyDoc) } val classBody = currentClass.body val offset = editor.caretModel.offset // Insert members at the cursor position if the cursor is within the class body. Or, if there is no body, generate the body and put // stuff in it. if (classBody == null || isCursorInsideClassBodyExcludingBraces(classBody, offset)) { return selectedMemberSymbolsAndGeneratedPsi.values.map { MemberEntry.NewEntry(it) } } // Insert members at positions such that the result aligns with ordering of members in super types. return getMembersOrderedByRelativePositionsInSuperTypes(currentClass, selectedMemberSymbolsAndGeneratedPsi) } private fun isCursorInsideClassBodyExcludingBraces(classBody: KtClassBody, offset: Int): Boolean { return classBody.textRange.contains(offset) && classBody.lBrace?.textRange?.contains(offset) == false && classBody.rBrace?.textRange?.contains(offset) == false } /** * Given a class and some stub implementation of overridden members, output all the callable members in the desired order. For example, * consider the following code * * ``` * interface Super { * fun a() * fun b() * fun c() * } * * class Sub: Super { * override fun b() {} * } * ``` * * Now this method is invoked with `Sub` as [currentClass] and `Super.a` and `Super.c` as [newMemberSymbolsAndGeneratedPsi]. This * method outputs `[NewEntry(Sub.a), ExistingEntry(Sub.b), NewEntry(Sub.c)]`. * * How does this work? * * Initially we put all existing members in [currentClass] into a doubly linked list in the order they appear in the source code. Then, * for each new member, the algorithm finds a target node nearby which this new member should be inserted. If the algorithm fails to * find a desired target node, then the new member is inserted at the end. * * With the above code as an example, initially the doubly linked list contains `[ExistingEntry(Sub.b)]`. Then for `a`, the algorithm * somehow (explained below) finds `ExistingEntry(Sub.b)` as the target node before which the new member `a` should be inserted. So now * the doubly linked list contains `[NewEntry(Sub.a), ExistingEntry(Sub.b)]`. Similar steps are done for `c`. * * How does the algorithm find the target node and how does it decide whether to insert the new member before or after the target node? * * Throughout the algorithm, we maintain a map that tracks super member declarations for each member in the doubly linked list. For * example, initially, the map contains `{ Super.b -> ExistingEntry(Sub.b) }` * * Given a new member, the algorithm first finds the PSI that declares this member in the super class. Then it traverses all the * sibling members before this PSI element. With the above example, there is nothing before `Super.a`. Next it traverses all the * sibling members after this PSI element. With the above example, it finds `Super.b`, which exists in the map. So the algorithm now * knows `Sub.a` should be inserted before `Sub.b`. * * @param currentClass the class where the generated member code will be placed in * @param newMemberSymbolsAndGeneratedPsi the generated members to insert into the class. For each entry in the map, the key is a * callable symbol for an overridable member that the user has picked to override (or implement), and the value is the stub * implementation for the chosen symbol. */ private fun KtAnalysisSession.getMembersOrderedByRelativePositionsInSuperTypes( currentClass: KtClassOrObject, newMemberSymbolsAndGeneratedPsi: Map<KtCallableSymbol, KtCallableDeclaration> ): List<MemberEntry> { // This doubly linked list tracks the preferred ordering of members. val sentinelHeadNode = DoublyLinkedNode<MemberEntry>() val sentinelTailNode = DoublyLinkedNode<MemberEntry>() sentinelHeadNode.append(sentinelTailNode) // Traverse existing members in the current class and populate // - a doubly linked list tracking the order // - a map that tracks a member (as a doubly linked list node) in the current class and its overridden members in super classes (as // a PSI element). This map is to allow fast look up from a super PSI element to a member entry in the current class val existingDeclarations = currentClass.declarations.filterIsInstance<KtCallableDeclaration>() val superPsiToMemberEntry = mutableMapOf<PsiElement, DoublyLinkedNode<MemberEntry>>().apply { for (existingDeclaration in existingDeclarations) { val node: DoublyLinkedNode<MemberEntry> = DoublyLinkedNode(MemberEntry.ExistingEntry(existingDeclaration)) sentinelTailNode.prepend(node) val callableSymbol = existingDeclaration.getSymbol() as? KtCallableSymbol ?: continue for (overriddenSymbol in callableSymbol.getAllOverriddenSymbols()) { put(overriddenSymbol.psi ?: continue, node) } } } // Note on implementation: here we need the original ordering defined in the source code, so we stick to PSI rather than using // `KtMemberScope` because the latter does not guarantee members are traversed in the original order. For example the // FIR implementation groups overloaded functions together. outer@ for ((selectedSymbol, generatedPsi) in newMemberSymbolsAndGeneratedPsi) { val superSymbol = selectedSymbol.originalOverriddenSymbol val superPsi = superSymbol?.psi if (superPsi == null) { // This normally should not happen, but we just try to play safe here. sentinelTailNode.prepend(DoublyLinkedNode(MemberEntry.NewEntry(generatedPsi))) continue } var currentPsi = superSymbol.psi?.prevSibling while (currentPsi != null) { val matchedNode = superPsiToMemberEntry[currentPsi] if (matchedNode != null) { val newNode = DoublyLinkedNode<MemberEntry>(MemberEntry.NewEntry(generatedPsi)) matchedNode.append(newNode) superPsiToMemberEntry[superPsi] = newNode continue@outer } currentPsi = currentPsi.prevSibling } currentPsi = superSymbol.psi?.nextSibling while (currentPsi != null) { val matchedNode = superPsiToMemberEntry[currentPsi] if (matchedNode != null) { val newNode = DoublyLinkedNode<MemberEntry>(MemberEntry.NewEntry(generatedPsi)) matchedNode.prepend(newNode) superPsiToMemberEntry[superPsi] = newNode continue@outer } currentPsi = currentPsi.nextSibling } val newNode = DoublyLinkedNode<MemberEntry>(MemberEntry.NewEntry(generatedPsi)) superPsiToMemberEntry[superPsi] = newNode sentinelTailNode.prepend(newNode) } return sentinelHeadNode.toListSkippingNulls() } @OptIn(ExperimentalStdlibApi::class) private fun insertMembersAccordingToPreferredOrder( symbolsInPreferredOrder: List<MemberEntry>, editor: Editor, currentClass: KtClassOrObject ): List<InsertedBlock> { if (symbolsInPreferredOrder.isEmpty()) return emptyList() var firstAnchor: PsiElement? = null if (symbolsInPreferredOrder.first() is MemberEntry.NewEntry) { val firstExistingEntry = symbolsInPreferredOrder.firstIsInstanceOrNull<MemberEntry.ExistingEntry>() if (firstExistingEntry != null) { firstAnchor = firstExistingEntry.psi.prevSiblingOfSameType() ?: currentClass.body?.lBrace } } val insertionBlocks = mutableListOf<InsertionBlock>() var currentAnchor = firstAnchor val currentBatch = mutableListOf<KtCallableDeclaration>() fun updateBatch() { if (currentBatch.isNotEmpty()) { insertionBlocks += InsertionBlock(currentBatch.toList(), currentAnchor) currentBatch.clear() } } for (entry in symbolsInPreferredOrder) { when (entry) { is MemberEntry.ExistingEntry -> { updateBatch() currentAnchor = entry.psi } is MemberEntry.NewEntry -> { currentBatch += entry.psi } } } updateBatch() return runWriteAction { insertionBlocks.map { (newDeclarations, anchor) -> InsertedBlock(insertMembersAfter(editor, currentClass, newDeclarations, anchor = anchor)) } } } private class DoublyLinkedNode<T>(val t: T? = null) { private var prev: DoublyLinkedNode<T>? = null private var next: DoublyLinkedNode<T>? = null fun append(node: DoublyLinkedNode<T>) { val next = this.next this.next = node node.prev = this node.next = next next?.prev = node } fun prepend(node: DoublyLinkedNode<T>) { val prev = this.prev this.prev = node node.next = this node.prev = prev prev?.next = node } @OptIn(ExperimentalStdlibApi::class) fun toListSkippingNulls(): List<T> { var current: DoublyLinkedNode<T>? = this return buildList { while (current != null) { current?.let { if (it.t != null) add(it.t) current = it.next } } } } } private sealed class MemberEntry { data class ExistingEntry(val psi: KtCallableDeclaration) : MemberEntry() data class NewEntry(val psi: KtCallableDeclaration) : MemberEntry() } companion object { val renderer = KtDeclarationRendererForSource.WITH_SHORT_NAMES.with { modifiersRenderer = modifiersRenderer.with { modifierFilter = KtRendererModifierFilter.onlyWith(KtTokens.OVERRIDE_KEYWORD) } } } /** A block of code (represented as a list of Kotlin declarations) that should be inserted at a given anchor. */ private data class InsertionBlock(val declarations: List<KtDeclaration>, val anchor: PsiElement?) /** A block of generated code. The code is represented as a list of Kotlin declarations that are defined one after another. */ private data class InsertedBlock(val declarations: List<SmartPsiElementPointer<KtDeclaration>>) }
apache-2.0
6354850cff74c7d65523fe1ec1a46f2a
47.62776
139
0.662579
5.514848
false
false
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/clients/beehive/BeehiveRepository.kt
1
8163
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.clients.beehive import com.neatorobotics.sdk.android.authentication.NeatoAuthentication import com.neatorobotics.sdk.android.clients.Resource import com.neatorobotics.sdk.android.clients.ResourceState import com.neatorobotics.sdk.android.clients.beehive.json.BeehiveJSONParser import com.neatorobotics.sdk.android.models.* import com.neatorobotics.sdk.android.utils.DELETE import com.neatorobotics.sdk.android.utils.GET import com.neatorobotics.sdk.android.utils.POST import com.neatorobotics.sdk.android.utils.PUT import org.json.JSONObject class BeehiveRepository(val endpoint: String, private val errorsProvider: BeehiveErrorsProvider = BeehiveErrorsProvider()) { var client = BeehiveHttpClient() suspend fun logOut(): Resource<Boolean> { val params = JSONObject("{\"token\":\"" + NeatoAuthentication.oauth2AccessToken + "\"}") val result = client.call(POST, "$endpoint/oauth2/revoke", params) return when (result.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code), false) } } suspend fun getUser(): Resource<UserInfo> { val result = client.call(GET, "$endpoint/users/me") return when (result.status) { Resource.Status.SUCCESS -> Resource.success(BeehiveJSONParser.parseUser(result.data)) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun updateUser(params: JSONObject): Resource<Boolean> { val response = client.call(PUT, "$endpoint/users/me", params) return when (response.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(response.code, getDescriptiveErrorMessage(response.code)) } } suspend fun updateRobot(robot: Robot, params: JSONObject): Resource<Boolean> { val response = client.call(PUT, "$endpoint/robots/${robot.serial}", params) return when (response.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(response.code, getDescriptiveErrorMessage(response.code)) } } suspend fun loadRobots(): Resource<List<Robot>> { val result = client.call(GET, "$endpoint/users/me/robots") return if (result.status === Resource.Status.SUCCESS) { val output = BeehiveJSONParser.parseRobotList(result.data) Resource.success(output) } else { Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun delete(robot: Robot): Resource<Boolean> { val response = client.call(DELETE, "$endpoint/robots/${robot.serial}") return when (response.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(response.code, getDescriptiveErrorMessage(response.code)) } } suspend fun getMapById(serial: String, mapId: String): Resource<CleaningMap> { val result = client.call(GET, "$endpoint/users/me/robots/$serial/maps/$mapId") return when (result.status) { Resource.Status.SUCCESS -> Resource.success(BeehiveJSONParser.parseRobotMap(result.data!!)) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun getExplorationMaps(robot: Robot): Resource<List<PersistentMap>> { val result = client.call(GET, "$endpoint/users/me/robots/${robot.serial}/exploration_maps") return when (result.status) { Resource.Status.SUCCESS -> Resource.success(BeehiveJSONParser.parseRobotExplorationMaps(result.data!!)) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun acceptExplorationMap(robot: Robot, mapId: String, mapName: String): Resource<Boolean> { val input = JSONObject() input.put("name", mapName) val response = client.call(PUT, "$endpoint/users/me/robots/${robot.serial}/exploration_maps/$mapId/accept", input) return when (response.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(response.code, getDescriptiveErrorMessage(response.code)) } } suspend fun rejectExplorationMap(robot: Robot?, mapId: String): Resource<Boolean> { val result = client.call(PUT, "$endpoint/users/me/robots/${robot?.serial}/exploration_maps/$mapId/reject") return when (result.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun getPersistentMaps(robot: Robot): Resource<List<PersistentMap>> { val result = client.call(GET, "$endpoint/users/me/robots/${robot.serial}/persistent_maps") return when (result.status) { Resource.Status.SUCCESS -> { var output: List<PersistentMap> = ArrayList() output = BeehiveJSONParser.parseRobotPersistentMaps(result.data) Resource.success(output) } else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun deletetMap(robot: Robot, mapId: String): Resource<Unit>{ val result = client.call(DELETE, "$endpoint/users/me/robots/${robot.serial}/persistent_maps/$mapId") return when (result.status) { Resource.Status.SUCCESS -> Resource.success(Unit) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun changeUserLocale(locale: String): Resource<Boolean> { val input = JSONObject().apply { put("locale", locale) } val result = client.call(PUT, "$endpoint/users/me", input) return when (result.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun changeUserCountry(country: String): Resource<Boolean> { val input = JSONObject().apply { put("country_code", country) } val result = client.call(PUT, "$endpoint/users/me", input) return when (result.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun updatePersistentMap(robot: Robot?, mapId: String, params: JSONObject): Resource<Boolean> { val result = client.call(PUT, "$endpoint/users/me/robots/${robot?.serial}/persistent_maps/$mapId", params) return when (result.status) { Resource.Status.SUCCESS -> Resource.success(true) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun getRobot(serial: String): Resource<Robot?> { val result = client.call(GET, "$endpoint/robots/$serial", null) return when (result.status) { Resource.Status.SUCCESS -> Resource.success(BeehiveJSONParser.parseRobot(result.data!!)) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } suspend fun getRobotMaps(robot: Robot?): Resource<List<CleaningMap>> { val path = "/users/me/robots/" + robot?.serial + "/maps" val result = client.call(GET, endpoint + path) return when (result.status) { Resource.Status.SUCCESS -> Resource.success(BeehiveJSONParser.parseRobotMaps(result.data!!)) else -> Resource.error(result.code, getDescriptiveErrorMessage(result.code)) } } private fun getDescriptiveErrorMessage(code: ResourceState): String { return errorsProvider.description(code) } companion object { private val TAG = "BeehiveRepository" } }
mit
3064216ff48c4d06ed52cb83d4a5633e
41.73822
122
0.660296
4.438825
false
false
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/commands/maincommands/homecommands/HomeNamePlayerCommand.kt
1
1323
package com.masahirosaito.spigot.homes.commands.maincommands.homecommands import com.masahirosaito.spigot.homes.Configs.onFriendHome import com.masahirosaito.spigot.homes.Configs.onNamedHome import com.masahirosaito.spigot.homes.DelayTeleporter import com.masahirosaito.spigot.homes.Homes.Companion.homes import com.masahirosaito.spigot.homes.Permission.home_command import com.masahirosaito.spigot.homes.Permission.home_command_player_name import com.masahirosaito.spigot.homes.commands.PlayerSubCommand import com.masahirosaito.spigot.homes.commands.subcommands.player.PlayerCommand import com.masahirosaito.spigot.homes.findOfflinePlayer import org.bukkit.entity.Player class HomeNamePlayerCommand(val homeCommand: HomeCommand) : PlayerSubCommand(homeCommand), PlayerCommand { override val permissions: List<String> = listOf( home_command, home_command_player_name ) override fun fee(): Double = homes.fee.HOME_NAME_PLAYER override fun configs(): List<Boolean> = listOf(onNamedHome, onFriendHome) override fun isValidArgs(args: List<String>): Boolean = args.size == 3 && args[1] == "-p" override fun execute(player: Player, args: List<String>) { DelayTeleporter.run(player, homeCommand.getTeleportLocation(findOfflinePlayer(args[2]), args[0]), this) } }
apache-2.0
fd8409e1c73c62f2e3e7087ca5e05eb4
44.62069
111
0.786092
4.033537
false
true
false
false
matrix-org/matrix-android-sdk
matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/TestAssertUtil.kt
1
1919
/* * Copyright 2018 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 org.matrix.androidsdk.common import org.junit.Assert.* /** * Compare two lists and their content */ fun assertListEquals(list1: List<Any>?, list2: List<Any>?) { if (list1 == null) { assertNull(list2) } else { assertNotNull(list2) assertEquals("List sizes must match", list1.size, list2!!.size) for (i in list1.indices) { assertEquals("Elements at index $i are not equal", list1[i], list2[i]) } } } /** * Compare two maps and their content */ fun assertDictEquals(dict1: Map<String, Any>?, dict2: Map<String, Any>?) { if (dict1 == null) { assertNull(dict2) } else { assertNotNull(dict2) assertEquals("Map sizes must match", dict1.size, dict2!!.size) for (i in dict1.keys) { assertEquals("Values for key $i are not equal", dict1[i], dict2[i]) } } } /** * Compare two byte arrays content. * Note that if the arrays have not the same size, it also fails. */ fun assertByteArrayNotEqual(a1: ByteArray, a2: ByteArray) { if (a1.size != a2.size) { fail("Arrays have not the same size.") } for (index in a1.indices) { if (a1[index] != a2[index]) { // Difference found! return } } fail("Arrays are equals.") }
apache-2.0
f781f155166be465f194e0deefd0880b
25.666667
82
0.631058
3.733463
false
false
false
false
CORDEA/MackerelClient
app/src/main/java/jp/cordea/mackerelclient/activity/MonitorDetailActivity.kt
1
3406
package jp.cordea.mackerelclient.activity import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import dagger.android.AndroidInjection import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import jp.cordea.mackerelclient.ListItemDecoration import jp.cordea.mackerelclient.R import jp.cordea.mackerelclient.adapter.DetailCommonAdapter import jp.cordea.mackerelclient.api.response.MonitorDataResponse import jp.cordea.mackerelclient.databinding.ActivityDetailCommonBinding import jp.cordea.mackerelclient.fragment.MonitorSettingDeleteDialogFragment import jp.cordea.mackerelclient.viewmodel.MonitorDetailViewModel import javax.inject.Inject class MonitorDetailActivity : AppCompatActivity(), HasSupportFragmentInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment> private val viewModel by lazy { MonitorDetailViewModel() } private var monitor: MonitorDataResponse? = null override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) val binding = DataBindingUtil .setContentView<ActivityDetailCommonBinding>(this, R.layout.activity_detail_common) supportActionBar?.setDisplayHomeAsUpEnabled(true) val monitor = intent.getSerializableExtra(MONITOR_KEY) as MonitorDataResponse binding.recyclerView.layoutManager = LinearLayoutManager(this) binding.recyclerView.adapter = DetailCommonAdapter(this, viewModel.getDisplayData(monitor)) binding.recyclerView.addItemDecoration(ListItemDecoration(this)) this.monitor = monitor } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.monitor_detail, menu) monitor?.let { if ("connectivity" == it.type) { menu.findItem(R.id.action_delete).isVisible = false } } return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> finish() R.id.action_delete -> { MonitorSettingDeleteDialogFragment .newInstance(monitor!!) .apply { onSuccess = { setResult(Activity.RESULT_OK) finish() } } .show(supportFragmentManager, "") } } return super.onOptionsItemSelected(item) } override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingAndroidInjector companion object { const val REQUEST_CODE = 0 private const val MONITOR_KEY = "MONITOR_KEY" fun createIntent(context: Context, monitor: MonitorDataResponse): Intent = Intent(context, MonitorDetailActivity::class.java).apply { putExtra(MONITOR_KEY, monitor) } } }
apache-2.0
723d7454decf7a0a42f0021d6dbd1cb5
36.844444
99
0.706988
5.520259
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/super/basicmethodSuperTrait.kt
5
238
interface Tr { fun extra() : String = "_" } class N() : Tr { override fun extra() : String = super<Tr>.extra() + super<Tr>.extra() } fun box(): String { val n = N() if (n.extra() == "__") return "OK" return "fail"; }
apache-2.0
08ae763babb4319d48e55f43ad43ac55
16
72
0.512605
2.975
false
false
false
false
JuliusKunze/kotlin-native
performance/src/main/kotlin/org/jetbrains/ring/SwitchBenchmark.kt
2
16389
/* * Copyright 2010-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 org.jetbrains.ring val SPARSE_SWITCH_CASES = intArrayOf(11, 29, 47, 71, 103, 149, 175, 227, 263, 307, 361, 487, 563, 617, 677, 751, 823, 883, 967, 1031) const val V1 = 1 const val V2 = 2 const val V3 = 3 const val V4 = 4 const val V5 = 5 const val V6 = 6 const val V7 = 7 const val V8 = 8 const val V9 = 9 const val V10 = 10 const val V11 = 11 const val V12 = 12 const val V13 = 13 const val V14 = 14 const val V15 = 15 const val V16 = 16 const val V17 = 17 const val V18 = 18 const val V19 = 19 const val V20 = 20 object Numbers { const val V1 = 1 const val V2 = 2 const val V3 = 3 const val V4 = 4 const val V5 = 5 const val V6 = 6 const val V7 = 7 const val V8 = 8 const val V9 = 9 const val V10 = 10 const val V11 = 11 const val V12 = 12 const val V13 = 13 const val V14 = 14 const val V15 = 15 const val V16 = 16 const val V17 = 17 const val V18 = 18 const val V19 = 19 const val V20 = 20 } var VV1 = 1 var VV2 = 2 var VV3 = 3 var VV4 = 4 var VV5 = 5 var VV6 = 6 var VV7 = 7 var VV8 = 8 var VV9 = 9 var VV10 = 10 var VV11 = 11 var VV12 = 12 var VV13 = 13 var VV14 = 14 var VV15 = 15 var VV16 = 16 var VV17 = 17 var VV18 = 18 var VV19 = 19 var VV20 = 20 open class SwitchBenchmark { fun sparseIntSwitch(u : Int) : Int { var t : Int when (u) { 11 -> { t = 1 } 29 -> { t = 2 } 47 -> { t = 3 } 71 -> { t = 4 } 103 -> { t = 5 } 149 -> { t = 6 } 175 -> { t = 7 } 227 -> { t = 1 } 263 -> { t = 9 } 307 -> { t = 1 } 361 -> { t = 2 } 487 -> { t = 3 } 563 -> { t = 4 } 617 -> { t = 4 } 677 -> { t = 4 } 751 -> { t = 435 } 823 -> { t = 31 } 883 -> { t = 1 } 967 -> { t = 1 } 1031 -> { t = 1 } 20 -> { t = 1 } else -> { t = 5 } } return t } fun denseIntSwitch(u : Int) : Int { var t : Int when (u) { 1 -> { t = 1 } -1 -> { t = 2 } 2 -> { t = 3 } 3 -> { t = 4 } 4 -> { t = 5 } 5 -> { t = 6 } 6 -> { t = 7 } 7 -> { t = 1 } 8 -> { t = 9 } 9 -> { t = 1 } 10 -> { t = 2 } 11 -> { t = 3 } 12 -> { t = 4 } 13 -> { t = 4 } 14 -> { t = 4 } 15 -> { t = 435 } 16 -> { t = 31 } 17 -> { t = 1 } 18 -> { t = 1 } 19 -> { t = 1 } 20 -> { t = 1 } else -> { t = 5 } } return t } fun constSwitch(u : Int) : Int { var t : Int when (u) { V1 -> { t = 1 } V2 -> { t = 3 } V3 -> { t = 4 } V4 -> { t = 5 } V5 -> { t = 6 } V6 -> { t = 7 } V7 -> { t = 1 } V8 -> { t = 9 } V9 -> { t = 1 } V10 -> { t = 2 } V11 -> { t = 3 } V12 -> { t = 4 } V13 -> { t = 4 } V14 -> { t = 4 } V15 -> { t = 435 } V16 -> { t = 31 } V17 -> { t = 1 } V18 -> { t = 1 } V19 -> { t = 1 } V20 -> { t = 1 } else -> { t = 5 } } return t } fun objConstSwitch(u : Int) : Int { var t : Int when (u) { Numbers.V1 -> { t = 1 } Numbers.V2 -> { t = 3 } Numbers.V3 -> { t = 4 } Numbers.V4 -> { t = 5 } Numbers.V5 -> { t = 6 } Numbers.V6 -> { t = 7 } Numbers.V7 -> { t = 1 } Numbers.V8 -> { t = 9 } Numbers.V9 -> { t = 1 } Numbers.V10 -> { t = 2 } Numbers.V11 -> { t = 3 } Numbers.V12 -> { t = 4 } Numbers.V13 -> { t = 4 } Numbers.V14 -> { t = 4 } Numbers.V15 -> { t = 435 } Numbers.V16 -> { t = 31 } Numbers.V17 -> { t = 1 } Numbers.V18 -> { t = 1 } Numbers.V19 -> { t = 1 } Numbers.V20 -> { t = 1 } else -> { t = 5 } } return t } fun varSwitch(u : Int) : Int { var t : Int when (u) { VV1 -> { t = 1 } VV2 -> { t = 3 } VV3 -> { t = 4 } VV4 -> { t = 5 } VV5 -> { t = 6 } VV6 -> { t = 7 } VV7 -> { t = 1 } VV8 -> { t = 9 } VV9 -> { t = 1 } VV10 -> { t = 2 } VV11 -> { t = 3 } VV12 -> { t = 4 } VV13 -> { t = 4 } VV14 -> { t = 4 } VV15 -> { t = 435 } VV16 -> { t = 31 } VV17 -> { t = 1 } VV18 -> { t = 1 } VV19 -> { t = 1 } VV20 -> { t = 1 } else -> { t = 5 } } return t } private fun stringSwitch(s: String) : Int { when(s) { "ABCDEFG1" -> return 1 "ABCDEFG2" -> return 2 "ABCDEFG2" -> return 3 "ABCDEFG3" -> return 4 "ABCDEFG4" -> return 5 "ABCDEFG5" -> return 6 "ABCDEFG6" -> return 7 "ABCDEFG7" -> return 8 "ABCDEFG8" -> return 9 "ABCDEFG9" -> return 10 "ABCDEFG10" -> return 11 "ABCDEFG11" -> return 12 "ABCDEFG12" -> return 1 "ABCDEFG13" -> return 2 "ABCDEFG14" -> return 3 "ABCDEFG15" -> return 4 "ABCDEFG16" -> return 5 "ABCDEFG17" -> return 6 "ABCDEFG18" -> return 7 "ABCDEFG19" -> return 8 "ABCDEFG20" -> return 9 else -> return -1 } } lateinit var denseIntData: IntArray lateinit var sparseIntData: IntArray fun setupInts() { denseIntData = IntArray(BENCHMARK_SIZE) { Random.nextInt(25) - 1 } sparseIntData= IntArray(BENCHMARK_SIZE) { SPARSE_SWITCH_CASES[Random.nextInt(20)] } } //Benchmark fun testSparseIntSwitch() { for (i in sparseIntData) { Blackhole.consume(sparseIntSwitch(i)) } } //Benchmark fun testDenseIntSwitch() { for (i in denseIntData) { Blackhole.consume(denseIntSwitch(i)) } } //Benchmark fun testConstSwitch() { for (i in denseIntData) { Blackhole.consume(constSwitch(i)) } } //Benchmark fun testObjConstSwitch() { for (i in denseIntData) { Blackhole.consume(objConstSwitch(i)) } } //Benchmark fun testVarSwitch() { for (i in denseIntData) { Blackhole.consume(varSwitch(i)) } } var data : Array<String> = arrayOf() fun setupStrings() { data = Array(BENCHMARK_SIZE) { "ABCDEFG" + Random.nextInt(22) } } //Benchmark fun testStringsSwitch() { val n = data.size for (s in data) { Blackhole.consume(stringSwitch(s)) } } enum class MyEnum { ITEM1, ITEM2, ITEM3, ITEM4, ITEM5, ITEM6, ITEM7, ITEM8, ITEM9, ITEM10, ITEM11, ITEM12, ITEM13, ITEM14, ITEM15, ITEM16, ITEM17, ITEM18, ITEM19, ITEM20, ITEM21, ITEM22, ITEM23, ITEM24, ITEM25, ITEM26, ITEM27, ITEM28, ITEM29, ITEM30, ITEM31, ITEM32, ITEM33, ITEM34, ITEM35, ITEM36, ITEM37, ITEM38, ITEM39, ITEM40, ITEM41, ITEM42, ITEM43, ITEM44, ITEM45, ITEM46, ITEM47, ITEM48, ITEM49, ITEM50, ITEM51, ITEM52, ITEM53, ITEM54, ITEM55, ITEM56, ITEM57, ITEM58, ITEM59, ITEM60, ITEM61, ITEM62, ITEM63, ITEM64, ITEM65, ITEM66, ITEM67, ITEM68, ITEM69, ITEM70, ITEM71, ITEM72, ITEM73, ITEM74, ITEM75, ITEM76, ITEM77, ITEM78, ITEM79, ITEM80, ITEM81, ITEM82, ITEM83, ITEM84, ITEM85, ITEM86, ITEM87, ITEM88, ITEM89, ITEM90, ITEM91, ITEM92, ITEM93, ITEM94, ITEM95, ITEM96, ITEM97, ITEM98, ITEM99, ITEM100 } private fun enumSwitch(x: MyEnum) : Int { when (x) { MyEnum.ITEM5 -> return 1 MyEnum.ITEM10 -> return 2 MyEnum.ITEM15 -> return 3 MyEnum.ITEM20 -> return 4 MyEnum.ITEM25 -> return 5 MyEnum.ITEM30 -> return 6 MyEnum.ITEM35 -> return 7 MyEnum.ITEM40 -> return 8 MyEnum.ITEM45 -> return 9 MyEnum.ITEM50 -> return 10 MyEnum.ITEM55 -> return 11 MyEnum.ITEM60 -> return 12 MyEnum.ITEM65 -> return 13 MyEnum.ITEM70 -> return 14 MyEnum.ITEM75 -> return 15 MyEnum.ITEM80 -> return 16 MyEnum.ITEM85 -> return 17 MyEnum.ITEM90 -> return 18 MyEnum.ITEM95 -> return 19 MyEnum.ITEM100 -> return 20 else -> return -1 } } private fun denseEnumSwitch(x: MyEnum) : Int { when (x) { MyEnum.ITEM1 -> return 1 MyEnum.ITEM2 -> return 2 MyEnum.ITEM3 -> return 3 MyEnum.ITEM4 -> return 4 MyEnum.ITEM5 -> return 5 MyEnum.ITEM6 -> return 6 MyEnum.ITEM7 -> return 7 MyEnum.ITEM8 -> return 8 MyEnum.ITEM9 -> return 9 MyEnum.ITEM10 -> return 10 MyEnum.ITEM11 -> return 11 MyEnum.ITEM12 -> return 12 MyEnum.ITEM13 -> return 13 MyEnum.ITEM14 -> return 14 MyEnum.ITEM15 -> return 15 MyEnum.ITEM16 -> return 16 MyEnum.ITEM17 -> return 17 MyEnum.ITEM18 -> return 18 MyEnum.ITEM19 -> return 19 MyEnum.ITEM20 -> return 20 else -> return -1 } } lateinit var enumData : Array<MyEnum> lateinit var denseEnumData : Array<MyEnum> fun setupEnums() { enumData = Array(BENCHMARK_SIZE) { MyEnum.values()[it % MyEnum.values().size] } denseEnumData = Array(BENCHMARK_SIZE) { MyEnum.values()[it % 20] } } //Benchmark fun testEnumsSwitch() { val n = enumData.size -1 val data = enumData for (i in 0..n) { Blackhole.consume(enumSwitch(data[i])) } } //Benchmark fun testDenseEnumsSwitch() { val n = denseEnumData.size -1 val data = denseEnumData for (i in 0..n) { Blackhole.consume(denseEnumSwitch(data[i])) } } sealed class MySealedClass { class MySealedClass1: MySealedClass() class MySealedClass2: MySealedClass() class MySealedClass3: MySealedClass() class MySealedClass4: MySealedClass() class MySealedClass5: MySealedClass() class MySealedClass6: MySealedClass() class MySealedClass7: MySealedClass() class MySealedClass8: MySealedClass() class MySealedClass9: MySealedClass() class MySealedClass10: MySealedClass() } lateinit var sealedClassData: Array<MySealedClass> fun setupSealedClassses() { sealedClassData = Array(BENCHMARK_SIZE) { when(Random.nextInt(10)) { 0 -> MySealedClass.MySealedClass1() 1 -> MySealedClass.MySealedClass2() 2 -> MySealedClass.MySealedClass3() 3 -> MySealedClass.MySealedClass4() 4 -> MySealedClass.MySealedClass5() 5 -> MySealedClass.MySealedClass6() 6 -> MySealedClass.MySealedClass7() 7 -> MySealedClass.MySealedClass8() 8 -> MySealedClass.MySealedClass9() 9 -> MySealedClass.MySealedClass10() else -> throw IllegalStateException() } } } private fun sealedWhenSwitch(x: MySealedClass) : Int = when (x) { is MySealedClass.MySealedClass1 -> 1 is MySealedClass.MySealedClass2 -> 2 is MySealedClass.MySealedClass3 -> 3 is MySealedClass.MySealedClass4 -> 4 is MySealedClass.MySealedClass5 -> 5 is MySealedClass.MySealedClass6 -> 6 is MySealedClass.MySealedClass7 -> 7 is MySealedClass.MySealedClass8 -> 8 is MySealedClass.MySealedClass9 -> 9 is MySealedClass.MySealedClass10 -> 10 } //Benchmark fun testSealedWhenSwitch() { val n = sealedClassData.size -1 for (i in 0..n) { Blackhole.consume(sealedWhenSwitch(sealedClassData[i])) } } }
apache-2.0
e7ab3493b4dbc986bb7bedb48be1a965
23.316024
798
0.385747
4.439057
false
false
false
false
smmribeiro/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/PartialLineStatusTrackerTest.kt
11
17586
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs import com.intellij.diff.util.Side import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.undo.DocumentReferenceManager import com.intellij.openapi.vcs.LineStatusTrackerTestUtil.parseInput import com.intellij.openapi.vcs.ex.Range class PartialLineStatusTrackerTest : BaseLineStatusTrackerTestCase() { fun testSimple1() { testPartial("1234_2345_3456") { "12".insertAfter("a") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) } } fun testSimple2() { testPartial("1234_2345_3456") { "12".insertAfter("a") range().assertChangeList(DEFAULT) createChangeList_SetDefault("Test") "12".insertBefore("X_Y_Z") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) "3456".replace("X_Y_Z") range(0).assertChangeList(DEFAULT) range(1).assertChangeList("Test") assertAffectedChangeLists(DEFAULT, "Test") } } fun testRangeMerging1() { testPartial("1234_2345_3456") { "12".insertAfter("a") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) createChangeList_SetDefault("Test") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) "56".insertAfter("b") range(0).assertChangeList(DEFAULT) range(1).assertChangeList("Test") assertAffectedChangeLists(DEFAULT, "Test") "2345".insertAfter("c") range().assertChangeList("Test") assertAffectedChangeLists("Test") } } fun testRangeMerging2() { testPartial("1234_2345_3456") { "12".insertAfter("a") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) createChangeList_SetDefault("Test") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) "56".insertAfter("b") range(0).assertChangeList(DEFAULT) range(1).assertChangeList("Test") assertAffectedChangeLists(DEFAULT, "Test") "2345_".delete() range().assertChangeList("Test") assertAffectedChangeLists("Test") } } fun testMovements1() { testPartial("1234_2345_3456") { "12".insertAfter("a") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) createChangelist("Test") range().moveTo("Test") range().assertChangeList("Test") assertAffectedChangeLists("Test") } } fun testMovements2() { testPartial("1234_2345_3456") { "12".insertAfter("a") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) createChangeList_SetDefault("Test") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) "56".insertAfter("b") range(0).assertChangeList(DEFAULT) range(1).assertChangeList("Test") assertAffectedChangeLists(DEFAULT, "Test") range(0).moveTo("Test") range(0).assertChangeList("Test") range(1).assertChangeList("Test") assertAffectedChangeLists("Test") range(1).moveTo(DEFAULT) range(0).assertChangeList("Test") range(1).assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT, "Test") } } fun testMovements3() { testPartial("1234_2345_3456") { "12".insertAfter("a") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) createChangeList_SetDefault("Test") range().assertChangeList(DEFAULT) assertAffectedChangeLists(DEFAULT) "56".insertAfter("b") range(0).assertChangeList(DEFAULT) range(1).assertChangeList("Test") assertAffectedChangeLists(DEFAULT, "Test") removeChangeList(DEFAULT) range(0).assertChangeList("Test") range(1).assertChangeList("Test") assertAffectedChangeLists("Test") } } fun testWhitespaceBlockMerging() { test("A_B_C_D_E_") { "A".replace("C_D_E") (2 th "C_D_E_").delete() assertTextContentIs("C_D_E_B_") assertRanges(Range(0, 3, 0, 1), Range(4, 4, 2, 5)) } test("A_ _C_D_E_") { "A".replace("C_D_E") (2 th "C_D_E_").delete() assertTextContentIs("C_D_E_ _") assertRanges(Range(0, 0, 0, 2), Range(3, 4, 5, 5)) } testPartial("A_ _C_D_E_") { "A".replace("C_D_E") (2 th "C_D_E_").delete() assertTextContentIs("C_D_E_ _") assertRanges(Range(0, 0, 0, 2), Range(3, 4, 5, 5)) } testPartial("A_ _C_D_E_") { "A".replace("C_D_E") createChangeList_SetDefault("Test") (2 th "C_D_E_").delete() assertTextContentIs("C_D_E_ _") assertRanges(Range(0, 3, 0, 1), Range(4, 4, 2, 5)) } } fun testPartialCommit1() { testPartial("A_B_C_D_E_F_G_H_") { "B".replace("B1") "D_".delete() "F_".insertAfter("M_") "G_".insertAfter("N_") range(1).moveTo("Test") range(3).moveTo("Test") partialTracker.setExcludedFromCommit(false) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_D_E_F_G_H_") assertAffectedChangeLists(DEFAULT, "Test") val helper = handlePartialCommit(Side.LEFT, "Test") helper.applyChanges() assertHelperContentIs("A_B_C_E_F_G_N_H_", helper) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_E_F_G_N_H_") assertAffectedChangeLists(DEFAULT) } } fun testPartialCommit2() { testPartial("A_B_C_D_E_F_G_H_") { "B".replace("B1") "D_".delete() "F_".insertAfter("M_") "G_".insertAfter("N_") range(1).moveTo("Test") range(3).moveTo("Test") partialTracker.setExcludedFromCommit(false) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_D_E_F_G_H_") assertAffectedChangeLists(DEFAULT, "Test") val helper = handlePartialCommit(Side.LEFT, DEFAULT) helper.applyChanges() assertHelperContentIs("A_B1_C_D_E_F_M_G_H_", helper) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B1_C_D_E_F_M_G_H_") assertAffectedChangeLists("Test") } } fun testPartialCommit3() { testPartial("A_B_C_D_E_F_G_H_") { "B".replace("B1") "D_".delete() "F_".insertAfter("M_") "G_".insertAfter("N_") range(1).moveTo("Test") range(3).moveTo("Test") partialTracker.setExcludedFromCommit(false) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_D_E_F_G_H_") assertAffectedChangeLists(DEFAULT, "Test") val helper = handlePartialCommit(Side.RIGHT, "Test") helper.applyChanges() assertHelperContentIs("A_B1_C_D_E_F_M_G_H_", helper) assertTextContentIs("A_B1_C_D_E_F_M_G_H_") assertBaseTextContentIs("A_B_C_D_E_F_G_H_") assertAffectedChangeLists(DEFAULT) } } fun testPartialCommit4() { testPartial("A_B_C_D_E_F_G_H_") { "B".replace("B1") "D_".delete() "F_".insertAfter("M_") "G_".insertAfter("N_") range(1).moveTo("Test") range(3).moveTo("Test") partialTracker.setExcludedFromCommit(false) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_D_E_F_G_H_") assertAffectedChangeLists(DEFAULT, "Test") tracker.doFrozen(Runnable { runCommandVerify { "B1_".replace("X_Y_Z_") val helper = handlePartialCommit(Side.LEFT, DEFAULT) helper.applyChanges() assertHelperContentIs("A_X_Y_Z_C_D_E_F_M_G_H_", helper) assertTextContentIs("A_X_Y_Z_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_X_Y_Z_C_D_E_F_M_G_H_") assertAffectedChangeLists("Test") } }) } } fun testPartialCommit5() { testPartial("A_B_C_D_E_F_G_H_") { "B".replace("B1") "D_".delete() "F_".insertAfter("M_") "G_".insertAfter("N_") range(1).moveTo("Test") range(3).moveTo("Test") partialTracker.setExcludedFromCommit(false) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_D_E_F_G_H_") assertAffectedChangeLists(DEFAULT, "Test") tracker.doFrozen(Runnable { runCommandVerify { "B1_".replace("X_Y_Z_") val helper = handlePartialCommit(Side.LEFT, DEFAULT) "N".replace("N2") "M".replace("M2") vcsDocument.setReadOnly(false) vcsDocument.replaceString(0, 10, "XXXXX_IGNORED") vcsDocument.setReadOnly(true) helper.applyChanges() assertHelperContentIs("A_X_Y_Z_C_D_E_F_M_G_H_", helper) assertTextContentIs("A_X_Y_Z_C_E_F_M2_G_N2_H_") assertBaseTextContentIs("A_X_Y_Z_C_D_E_F_M_G_H_") assertAffectedChangeLists("Test") } }) } } fun testPartialCommitWithExcluded() { testPartial("A_B_C_D_E_F_G_H_") { "B".replace("B1") "D_".delete() "F_".insertAfter("M_") "G_".insertAfter("N_") range(1).moveTo("Test") range(3).moveTo("Test") partialTracker.setExcludedFromCommit(false) partialTracker.setExcludedFromCommit(range(3), true) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_D_E_F_G_H_") assertAffectedChangeLists(DEFAULT, "Test") val helper = handlePartialCommit(Side.LEFT, "Test", true) helper.applyChanges() assertHelperContentIs("A_B_C_E_F_G_H_", helper) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_E_F_G_H_") assertAffectedChangeLists(DEFAULT, "Test") } } fun testPartialCommitIgnoringExcluded() { testPartial("A_B_C_D_E_F_G_H_") { "B".replace("B1") "D_".delete() "F_".insertAfter("M_") "G_".insertAfter("N_") range(1).moveTo("Test") range(3).moveTo("Test") partialTracker.setExcludedFromCommit(false) partialTracker.setExcludedFromCommit(range(3), true) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_D_E_F_G_H_") assertAffectedChangeLists(DEFAULT, "Test") val helper = handlePartialCommit(Side.LEFT, "Test", false) helper.applyChanges() assertHelperContentIs("A_B_C_E_F_G_N_H_", helper) assertTextContentIs("A_B1_C_E_F_M_G_N_H_") assertBaseTextContentIs("A_B_C_E_F_G_N_H_") assertAffectedChangeLists(DEFAULT) } } fun testUndo() { testPartial("A_B_C_D_E") { "B".replace("B1") "D_".delete() range(0).moveTo("Test 1") range(1).moveTo("Test 2") range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 2") assertTextContentIs("A_B1_C_E") assertBaseTextContentIs("A_B_C_D_E") assertAffectedChangeLists("Test 1", "Test 2") "C".replace("C2") assertRanges(Range(1, 3, 1, 4)) assertAffectedChangeLists(DEFAULT) undo() assertTextContentIs("A_B1_C_E") range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 2") assertAffectedChangeLists("Test 1", "Test 2") redo() assertRanges(Range(1, 3, 1, 4)) assertAffectedChangeLists(DEFAULT) undo() range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 2") assertAffectedChangeLists("Test 1", "Test 2") } } fun testUndoAfterExplicitMove() { testPartial("A_B_C_D_E") { "B".replace("B1") "D_".delete() range(0).moveTo("Test 1") range(1).moveTo("Test 2") range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 2") assertTextContentIs("A_B1_C_E") assertBaseTextContentIs("A_B_C_D_E") assertAffectedChangeLists("Test 1", "Test 2") "C".replace("C2") assertRanges(Range(1, 3, 1, 4)) assertAffectedChangeLists(DEFAULT) range(0).moveTo("Test 1") assertAffectedChangeLists("Test 1") undo() assertTextContentIs("A_B1_C_E") range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 1") assertAffectedChangeLists("Test 1") redo() assertRanges(Range(1, 3, 1, 4)) assertAffectedChangeLists("Test 1") undo() range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 1") assertAffectedChangeLists("Test 1") } testPartial("A_B_C_D_E") { "B".replace("B1") "D_".delete() range(0).moveTo("Test 1") range(1).moveTo("Test 2") range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 2") assertTextContentIs("A_B1_C_E") assertBaseTextContentIs("A_B_C_D_E") assertAffectedChangeLists("Test 1", "Test 2") "C".replace("C2") assertRanges(Range(1, 3, 1, 4)) assertAffectedChangeLists(DEFAULT) tracker.virtualFile.moveChanges(DEFAULT, "Test 1") assertAffectedChangeLists("Test 1") undo() assertTextContentIs("A_B1_C_E") range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 1") assertAffectedChangeLists("Test 1") redo() assertRanges(Range(1, 3, 1, 4)) assertAffectedChangeLists("Test 1") undo() range(0).assertChangeList("Test 1") range(1).assertChangeList("Test 1") assertAffectedChangeLists("Test 1") } } fun testUndoTransparentAction1() { testPartial("A_B_C_D_E") { val anotherFile = addLocalFile("Another.txt", parseInput("X_Y_Z")) val anotherDocument = anotherFile.document "C".replace("C1") range(0).moveTo("Test 1") "E".delete() runWriteAction { CommandProcessor.getInstance().executeCommand(getProject(), Runnable { anotherDocument.deleteString(0, 1) }, null, null) } runWriteAction { CommandProcessor.getInstance().runUndoTransparentAction { document.replaceString(0, 1, "A2") } } runWriteAction { CommandProcessor.getInstance().executeCommand(getProject(), Runnable { anotherDocument.insertString(0, "B22") }, null, null) } undo() assertTextContentIs("A_B_C1_D_E") range().assertChangeList("Test 1") } } fun testUndoTransparentAction2() { testPartial("A_B_C_D_E") { val anotherFile = addLocalFile("Another.txt", parseInput("X_Y_Z")) val anotherDocument = anotherFile.document "C".replace("C1") range(0).moveTo("Test 1") "E".delete() runWriteAction { CommandProcessor.getInstance().executeCommand(getProject(), Runnable { anotherDocument.deleteString(0, 1) }, null, null) } runWriteAction { CommandProcessor.getInstance().runUndoTransparentAction { document.replaceString(0, 1, "A2") } } runWriteAction { CommandProcessor.getInstance().executeCommand(getProject(), Runnable { anotherDocument.insertString(0, "B22") }, null, null) } runWriteAction { CommandProcessor.getInstance().executeCommand(getProject(), Runnable { anotherDocument.insertString(0, "B22") }, null, null) } undo() assertTextContentIs("A_B_C1_D_E") range().assertChangeList("Test 1") } } fun testUndoTransparentAction3() { testPartial("A_B_C_D_E") { val anotherFile = addLocalFile("Another.txt", parseInput("X_Y_Z")) val anotherDocument = anotherFile.document "C".replace("C1") range(0).moveTo("Test 1") "E".delete() runWriteAction { CommandProcessor.getInstance().executeCommand(getProject(), Runnable { anotherDocument.deleteString(0, 1) }, null, null) } runWriteAction { CommandProcessor.getInstance().runUndoTransparentAction { document.replaceString(0, 1, "A2") } } runWriteAction { CommandProcessor.getInstance().executeCommand(getProject(), Runnable { undoManager.nonundoableActionPerformed(DocumentReferenceManager.getInstance().create(anotherDocument), false) }, null, null) } undo() assertTextContentIs("A_B_C1_D_E") range().assertChangeList("Test 1") } } fun testZombieModification() { testPartial("A_B_C_D_E_F") { "E".replace("E1") partialTracker.dropBaseRevision() createChangeList_SetDefault("Test") "B".replace("B2") "E1".replace("E2") partialTracker.setBaseRevision(parseInput("A_B_C_D_E1_F")) range(0).assertChangeList("Test") range(1).assertChangeList("Test") } } fun testInvalidatingInvalidTracker1() { testPartial("A_B_C_D_E_F") { createChangeList_SetDefault("Test") partialTracker.dropBaseRevision() "E".replace("E1") setDefaultChangeList(DEFAULT) partialTracker.setBaseRevision(parseInput("A_B_C_D_E_F")) range(0).assertChangeList("Test") } } fun testInvalidatingInvalidTracker2() { testPartial("A_B_C_D_E_F") { createChangeList_SetDefault("Test") partialTracker.dropBaseRevision() "E".replace("E1") setDefaultChangeList(DEFAULT) partialTracker.dropBaseRevision() partialTracker.setBaseRevision(parseInput("A_B_C_D_E_F")) range(0).assertChangeList("Test") } } }
apache-2.0
e3ebf8ae3ed1ee21dc9a3f253fda0125
25.645455
140
0.614921
3.901065
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/classes/FirLightInterfaceOrAnnotationClassSymbol.kt
2
2152
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.asJava.classes import com.intellij.psi.* import org.jetbrains.kotlin.asJava.classes.lazyPub import org.jetbrains.kotlin.idea.asJava.* import org.jetbrains.kotlin.idea.frontend.api.isValid import org.jetbrains.kotlin.idea.frontend.api.symbols.KtClassKind import org.jetbrains.kotlin.idea.frontend.api.symbols.KtClassOrObjectSymbol import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.KtSymbolKind internal abstract class FirLightInterfaceOrAnnotationClassSymbol( private val classOrObjectSymbol: KtClassOrObjectSymbol, manager: PsiManager ) : FirLightClassForClassOrObjectSymbol(classOrObjectSymbol, manager) { init { require( classOrObjectSymbol.classKind == KtClassKind.OBJECT || classOrObjectSymbol.classKind == KtClassKind.INTERFACE || classOrObjectSymbol.classKind == KtClassKind.ANNOTATION_CLASS ) } private val _modifierList: PsiModifierList? by lazyPub { val isTopLevel: Boolean = classOrObjectSymbol.symbolKind == KtSymbolKind.TOP_LEVEL val modifiers = mutableSetOf(classOrObjectSymbol.toPsiVisibilityForClass(isTopLevel), PsiModifier.ABSTRACT) val annotations = classOrObjectSymbol.computeAnnotations( parent = this@FirLightInterfaceOrAnnotationClassSymbol, nullability = NullabilityType.Unknown, annotationUseSiteTarget = null, ) FirLightClassModifierList(this@FirLightInterfaceOrAnnotationClassSymbol, modifiers, annotations) } override fun getModifierList(): PsiModifierList? = _modifierList override fun getImplementsList(): PsiReferenceList? = null override fun getOwnInnerClasses(): List<PsiClass> = emptyList() override fun isInterface(): Boolean = true override fun isEnum(): Boolean = false override fun isValid(): Boolean = super.isValid() && classOrObjectSymbol.isValid() }
apache-2.0
079157bd2d28748952fa83537418e4c8
38.145455
115
0.750929
5.27451
false
false
false
false
smmribeiro/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt
1
14433
// 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:Suppress("HardCodedStringLiteral", "ReplaceGetOrSet") package org.jetbrains.builtInWebServer import com.github.benmanes.caffeine.cache.Caffeine import com.google.common.net.InetAddresses import com.intellij.ide.SpecialConfigFiles.USER_WEB_TOKEN import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationType import com.intellij.notification.SingletonNotificationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.endsWithName import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.io.* import com.intellij.util.io.DigestUtil.randomToken import com.intellij.util.net.NetUtils import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.* import io.netty.handler.codec.http.cookie.DefaultCookie import io.netty.handler.codec.http.cookie.ServerCookieDecoder import io.netty.handler.codec.http.cookie.ServerCookieEncoder import org.jetbrains.ide.BuiltInServerBundle import org.jetbrains.ide.BuiltInServerManagerImpl import org.jetbrains.ide.HttpRequestHandler import org.jetbrains.ide.orInSafeMode import org.jetbrains.io.send import java.awt.datatransfer.StringSelection import java.io.IOException import java.net.InetAddress import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.nio.file.attribute.PosixFileAttributeView import java.nio.file.attribute.PosixFilePermission import java.util.* import java.util.concurrent.TimeUnit import javax.swing.SwingUtilities internal val LOG = logger<BuiltInWebServer>() private val notificationManager by lazy { SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP, NotificationType.INFORMATION) } private val WEB_SERVER_PATH_HANDLER_EP_NAME = ExtensionPointName.create<WebServerPathHandler>("org.jetbrains.webServerPathHandler") class BuiltInWebServer : HttpRequestHandler() { override fun isAccessible(request: HttpRequest): Boolean { return BuiltInServerOptions.getInstance().builtInServerAvailableExternally || request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true) } override fun isSupported(request: FullHttpRequest): Boolean = super.isSupported(request) || request.method() == HttpMethod.POST override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean { var hostName = getHostName(request) ?: return false val projectName: String? val isIpv6 = hostName[0] == '[' && hostName.length > 2 && hostName[hostName.length - 1] == ']' if (isIpv6) { hostName = hostName.substring(1, hostName.length - 1) } if (isIpv6 || InetAddresses.isInetAddress(hostName) || isOwnHostName(hostName) || hostName.endsWith(".ngrok.io")) { if (urlDecoder.path().length < 2) { return false } projectName = null } else { if (hostName.endsWith(".localhost")) { projectName = hostName.substring(0, hostName.lastIndexOf('.')) } else { projectName = hostName } } return doProcess(urlDecoder, request, context, projectName) } } internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false) const val TOKEN_PARAM_NAME = "_ijt" const val TOKEN_HEADER_NAME = "x-ijt" private val STANDARD_COOKIE by lazy { val productName = ApplicationNamesInfo.getInstance().lowercaseProductName val configPath = PathManager.getConfigPath() val file = Path.of(configPath, USER_WEB_TOKEN) var token: String? = null if (file.exists()) { try { token = UUID.fromString(file.readText()).toString() } catch (e: Exception) { LOG.warn(e) } } if (token == null) { token = UUID.randomUUID().toString() file.write(token!!) Files.getFileAttributeView(file, PosixFileAttributeView::class.java) ?.setPermissions(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)) } // explicit setting domain cookie on localhost doesn't work for chrome // http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!) cookie.isHttpOnly = true cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10)) cookie.setPath("/") cookie } // expire after access because we reuse tokens private val tokens = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>() fun acquireToken(): String { var token = tokens.asMap().keys.firstOrNull() if (token == null) { token = randomToken() tokens.put(token, java.lang.Boolean.TRUE) } return token } private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean { val decodedPath = urlDecoder.path() var offset: Int var isEmptyPath: Boolean val isCustomHost = projectNameAsHost != null var projectName: String if (isCustomHost) { projectName = projectNameAsHost!! // host mapped to us offset = 0 isEmptyPath = decodedPath.isEmpty() } else { offset = decodedPath.indexOf('/', 1) projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset) isEmptyPath = offset == -1 } val referer = request.headers().get(HttpHeaderNames.REFERER) val projectNameFromReferer = if (!isCustomHost && referer != null) { try { val uri = URI.create(referer) val refererPath = uri.path if (refererPath != null && refererPath.startsWith('/')) { val secondSlashOffset = refererPath.indexOf('/', 1) if (secondSlashOffset > 1) refererPath.substring(1, secondSlashOffset) else null } else null } catch (t: Throwable) { null } } else null var candidateByDirectoryName: Project? = null var isCandidateFromReferer = false val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean { if (project.isDisposed) { return false } val name = project.name if (isCustomHost) { // domain name is case-insensitive if (projectName.equals(name, ignoreCase = true)) { if (!SystemInfo.isFileSystemCaseSensitive) { // may be passed path is not correct projectName = name } return true } } else { // WEB-17839 Internal web server reports 404 when serving files from project with slashes in name if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfo.isFileSystemCaseSensitive)) { val isEmptyPathCandidate = decodedPath.length == (name.length + 1) if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') { projectName = name offset = name.length + 1 isEmptyPath = isEmptyPathCandidate return true } } } if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) { candidateByDirectoryName = project } if (candidateByDirectoryName == null && projectNameFromReferer != null && (projectNameFromReferer == name || compareNameAndProjectBasePath(projectNameFromReferer, project))) { candidateByDirectoryName = project isCandidateFromReferer = true } return false }) ?: candidateByDirectoryName ?: return false if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) { notificationManager.notify("", BuiltInServerBundle.message("notification.content.built.in.web.server.is.deactivated"), project) return false } if (isCandidateFromReferer) { projectName = projectNameFromReferer!! offset = 0 isEmptyPath = false } if (isEmptyPath) { // we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work redirectToDirectory(request, context.channel(), projectName, null) return true } val path = toIdeaPath(decodedPath, offset) if (path == null) { HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request) return true } for (pathHandler in WEB_SERVER_PATH_HANDLER_EP_NAME.extensionList) { LOG.runAndLogException { if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) { return true } } } return false } fun HttpRequest.isSignedRequest(): Boolean { if (BuiltInServerOptions.getInstance().allowUnsignedRequests) { return true } // we must check referrer - if html cached, browser will send request without query val token = headers().get(TOKEN_HEADER_NAME) ?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() ?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() } // we don't invalidate token - allow making subsequent requests using it (it is required for our javadoc DocumentationComponent) return token != null && tokens.getIfPresent(token) != null } fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean): HttpHeaders? { if (BuiltInServerOptions.getInstance().allowUnsignedRequests) { return EmptyHttpHeaders.INSTANCE } request.headers().get(HttpHeaderNames.COOKIE)?.let { for (cookie in ServerCookieDecoder.STRICT.decode(it)) { if (cookie.name() == STANDARD_COOKIE.name()) { if (cookie.value() == STANDARD_COOKIE.value()) { return EmptyHttpHeaders.INSTANCE } break } } } if (isSignedRequest) { return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict") } val urlDecoder = QueryStringDecoder(request.uri()) if (!urlDecoder.path().endsWith("/favicon.ico")) { val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}" SwingUtilities.invokeAndWait { ProjectUtil.focusProjectWindow(null, true) if (MessageDialogBuilder .yesNo("", BuiltInServerBundle.message("dialog.message.page", StringUtil.trimMiddle(url, 50))) .icon(Messages.getWarningIcon()) .yesText(BuiltInServerBundle.message("dialog.button.copy.authorization.url.to.clipboard")) .guessWindowAndAsk()) { CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken())) } } } HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return null } private fun toIdeaPath(decodedPath: String, offset: Int): String? { // must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize val path = decodedPath.substring(offset) if (!path.startsWith('/')) { return null } return FileUtil.toCanonicalPath(path, '/').substring(1) } fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean { val basePath = project.basePath return basePath != null && endsWithName(basePath, projectName) } fun findIndexFile(basedir: VirtualFile): VirtualFile? { val children = basedir.children if (children == null || children.isEmpty()) { return null } for (indexNamePrefix in arrayOf("index.", "default.")) { var index: VirtualFile? = null val preferredName = indexNamePrefix + "html" for (child in children) { if (!child.isDirectory) { val name = child.name //noinspection IfStatementWithIdenticalBranches if (name == preferredName) { return child } else if (index == null && name.startsWith(indexNamePrefix)) { index = child } } } if (index != null) { return index } } return null } fun findIndexFile(basedir: Path): Path? { val children = basedir.directoryStreamIfExists({ val name = it.fileName.toString() name.startsWith("index.") || name.startsWith("default.") }) { it.toList() } ?: return null for (indexNamePrefix in arrayOf("index.", "default.")) { var index: Path? = null val preferredName = "${indexNamePrefix}html" for (child in children) { if (!child.isDirectory()) { val name = child.fileName.toString() if (name == preferredName) { return child } else if (index == null && name.startsWith(indexNamePrefix)) { index = child } } } if (index != null) { return index } } return null } // is host loopback/any or network interface address (i.e. not custom domain) // must be not used to check is host on local machine internal fun isOwnHostName(host: String): Boolean { if (NetUtils.isLocalhost(host)) { return true } try { val address = InetAddress.getByName(host) if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) { return true } val localHostName = InetAddress.getLocalHost().hostName // WEB-8889 // develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name) return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true)) } catch (ignored: IOException) { return false } }
apache-2.0
1b8fa6427c4ac06836c24ece40999f7e
35.0825
165
0.711356
4.603828
false
false
false
false
Peekazoo/Peekazoo-Android
app/src/main/java/com/tofi/peekazoo/di/modules/HttpModule.kt
1
1963
package com.tofi.peekazoo.di.modules import android.content.Context import com.tofi.peekazoo.BuildConfig import com.tofi.peekazoo.SharedPreferencesManager import com.tofi.peekazoo.di.ApplicationScope import com.tofi.peekazoo.network.InkbunnyNetworkInterceptor import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import java.util.concurrent.TimeUnit import javax.inject.Named const val TIMEOUT_DURATION = 60L /** * Created by Derek on 01/05/2017. * Modules providing http elements for networking layer */ @Module(includes = arrayOf(SharedPreferencesModule::class)) class HttpModule(private val context: Context) { @Provides @ApplicationScope @Named(NetworkModule.INKBUNNY) fun provideInkbunnyOkHttpClient(builder: OkHttpClient.Builder, sharedPrefs: SharedPreferencesManager): OkHttpClient { builder.addInterceptor(InkbunnyNetworkInterceptor(sharedPrefs)) return builder.build() } @Provides @ApplicationScope @Named(NetworkModule.WEASYL) fun provideWeasylOkHttpClient(builder: OkHttpClient.Builder): OkHttpClient { return builder.build() } @Provides @ApplicationScope fun provideLoggingInterceptor(): HttpLoggingInterceptor { val interceptor = HttpLoggingInterceptor() val logLevel = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE return interceptor.setLevel(logLevel) } @Provides @ApplicationScope fun provideBaseOkHttpBuilder(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient.Builder { val builder = OkHttpClient.Builder() builder.connectTimeout(TIMEOUT_DURATION, TimeUnit.SECONDS) builder.readTimeout(TIMEOUT_DURATION, TimeUnit.SECONDS) builder.writeTimeout(TIMEOUT_DURATION, TimeUnit.SECONDS) builder.addInterceptor(loggingInterceptor) return builder } }
apache-2.0
00d31140e86bf7e270ef9dc68f53b978
30.66129
121
0.768721
5.059278
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslExpressionCastFloats.kt
1
986
package de.fabmax.kool.modules.ksl.lang // Float to * cast extension functions - defined in a separate file to avoid JVM signature clashes fun KslScalarExpression<KslTypeFloat1>.toInt1() = KslExpressionCastScalar(this, KslTypeInt1) fun KslScalarExpression<KslTypeFloat1>.toUint1() = KslExpressionCastScalar(this, KslTypeUint1) fun KslVectorExpression<KslTypeFloat2, KslTypeFloat1>.toInt2() = KslExpressionCastVector(this, KslTypeInt2) fun KslVectorExpression<KslTypeFloat2, KslTypeFloat1>.toUint2() = KslExpressionCastVector(this, KslTypeUint2) fun KslVectorExpression<KslTypeFloat3, KslTypeFloat1>.toInt3() = KslExpressionCastVector(this, KslTypeInt3) fun KslVectorExpression<KslTypeFloat3, KslTypeFloat1>.toUint3() = KslExpressionCastVector(this, KslTypeUint3) fun KslVectorExpression<KslTypeFloat4, KslTypeFloat1>.toInt4() = KslExpressionCastVector(this, KslTypeInt4) fun KslVectorExpression<KslTypeFloat2, KslTypeFloat1>.toUint4() = KslExpressionCastVector(this, KslTypeUint4)
apache-2.0
0492500bad893b6688cd5c100944a06d
64.733333
109
0.839757
4.607477
false
false
false
false
yeungeek/AndroidRoad
AVSample/app/src/main/java/com/yeungeek/avsample/activities/opengl/book/programs/ColorShaderProgram.kt
1
1106
package com.yeungeek.avsample.activities.opengl.book.programs import android.content.Context import android.opengl.GLES20.* class ColorShaderProgram( context: Context, vertexShaderFile: String, fragmentShaderFile: String ) : ShaderProgram(context, vertexShaderFile, fragmentShaderFile) { // Uniform locations private var uMatrixLocation = 0 // Attribute locations private var aPositionLocation = 0 private var aColorLocation = 0 constructor(context: Context) : this( context, "airhockey/simple_vertex_shader.glsl", "airhockey/simple_fragment_shader.glsl" ) { this.uMatrixLocation = glGetUniformLocation(program, U_MATRIX) aPositionLocation = glGetAttribLocation(program, A_POSITION) aColorLocation = glGetAttribLocation(program, A_COLOR) } fun setUniforms(matrix: FloatArray?) { // Pass the matrix into the shader program. glUniformMatrix4fv(uMatrixLocation, 1, false, matrix, 0) } fun getPositionAttributeLocation() = aPositionLocation fun getColorAttributeLocation() = aColorLocation }
apache-2.0
8a1f031fe50abe94b1c7799f01e3c257
31.558824
70
0.728752
4.608333
false
false
false
false
siosio/intellij-community
platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsFileEventLogger.kt
1
5383
// 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.internal.statistic.eventLog import com.intellij.internal.statistic.eventLog.validator.IntellijSensitiveDataValidator import com.intellij.internal.statistic.utils.StatisticsRecorderUtil import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Disposer import com.intellij.util.concurrency.AppExecutorUtil import java.util.concurrent.CompletableFuture import java.util.concurrent.RejectedExecutionException import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit open class StatisticsFileEventLogger(private val recorderId: String, private val sessionId: String, private val headless: Boolean, private val build: String, private val bucket: String, private val recorderVersion: String, private val writer: StatisticsEventLogWriter, private val systemEventIdProvider: StatisticsSystemEventIdProvider) : StatisticsEventLogger, Disposable { protected val logExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("StatisticsFileEventLogger: $sessionId", 1) private var lastEvent: FusEvent? = null private var lastEventTime: Long = 0 private var lastEventCreatedTime: Long = 0 private var eventMergeTimeoutMs: Long private val mergeStrategy: StatisticsEventMergeStrategy = FilteredEventMergeStrategy(hashSetOf("start_time")) private var lastEventFlushFuture: ScheduledFuture<CompletableFuture<Void>>? = null init { if (StatisticsRecorderUtil.isTestModeEnabled(recorderId)) { eventMergeTimeoutMs = 500L } else { eventMergeTimeoutMs = 10000L } } override fun logAsync(group: EventLogGroup, eventId: String, data: Map<String, Any>, isState: Boolean): CompletableFuture<Void> { val eventTime = System.currentTimeMillis() group.validateEventId(eventId) return try { CompletableFuture.runAsync(Runnable { val validator = IntellijSensitiveDataValidator.getInstance(recorderId) if (!validator.isGroupAllowed(group)) return@Runnable val event = validator.validate(group.id, group.version.toString(), build, sessionId, bucket, eventTime, recorderVersion, eventId, data, isState) if (event != null) { log(event, System.currentTimeMillis(), eventId, data) } }, logExecutor) } catch (e: RejectedExecutionException) { //executor is shutdown CompletableFuture.completedFuture(null) } } private fun log(event: LogEvent, createdTime: Long, rawEventId: String, rawData: Map<String, Any>) { if (lastEvent != null && event.time - lastEventTime <= eventMergeTimeoutMs && mergeStrategy.shouldMerge(lastEvent!!.validatedEvent, event)) { lastEventTime = event.time lastEvent!!.validatedEvent.event.increment() } else { logLastEvent() lastEvent = if(StatisticsRecorderUtil.isTestModeEnabled(recorderId)) FusEvent(event, rawEventId, rawData) else FusEvent(event, null, null) lastEventTime = event.time lastEventCreatedTime = createdTime } if (StatisticsRecorderUtil.isTestModeEnabled(recorderId)) { lastEventFlushFuture?.cancel(false) // call flush() instead of logLastEvent() directly so that logLastEvent is executed on the logExecutor thread and not on scheduled executor pool thread lastEventFlushFuture = AppExecutorUtil.getAppScheduledExecutorService().schedule(this::flush, eventMergeTimeoutMs, TimeUnit.MILLISECONDS) } } private fun logLastEvent() { lastEvent?.let { val event = it.validatedEvent.event if (event.isEventGroup()) { event.addData("last", lastEventTime) } event.addData("created", lastEventCreatedTime) var systemEventId = systemEventIdProvider.getSystemEventId(recorderId) event.addData("system_event_id", systemEventId) systemEventIdProvider.setSystemEventId(recorderId, ++systemEventId) if (headless) { event.addData("system_headless", true) } writer.log(it.validatedEvent) ApplicationManager.getApplication().getService(EventLogListenersManager::class.java) .notifySubscribers(recorderId, it.validatedEvent, it.rawEventId, it.rawData) } lastEvent = null } override fun getActiveLogFile(): EventLogFile? { return writer.getActiveFile() } override fun getLogFilesProvider(): EventLogFilesProvider { return writer.getLogFilesProvider() } override fun cleanup() { writer.cleanup() } override fun rollOver() { writer.rollOver() } override fun dispose() { flush() logExecutor.shutdown() Disposer.dispose(writer) } fun flush(): CompletableFuture<Void> { return CompletableFuture.runAsync(Runnable { logLastEvent() }, logExecutor) } private data class FusEvent(val validatedEvent: LogEvent, val rawEventId: String?, val rawData: Map<String, Any>?) }
apache-2.0
5b337ec8dc0f2e1d9066db09ba7411c7
39.787879
157
0.698681
5.277451
false
false
false
false
JetBrains/xodus
entity-store/src/main/kotlin/jetbrains/exodus/entitystore/iterate/FilterEntitiesWithCertainLinkIterable.kt
1
4800
/** * 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.entitystore.iterate import jetbrains.exodus.entitystore.* import jetbrains.exodus.entitystore.util.EntityIdSetFactory // this iterable depth is rather great in order to prevent non-effective commutative binary operators mutation private const val DEPTH = 1000 internal class FilterEntitiesWithCertainLinkIterable(txn: PersistentStoreTransaction, private val entitiesWithLink: EntitiesWithCertainLinkIterable, filter: EntityIterableBase) : EntityIterableBase(txn) { private val filter: EntityIterableBase = filter.source val linkId: Int get() = entitiesWithLink.linkId override fun union(right: EntityIterable): EntityIterable { if (right is FilterEntitiesWithCertainLinkIterable) { if ((entitiesWithLink === right.entitiesWithLink) || (linkId == right.linkId && entityTypeId == right.entityTypeId)) { return FilterEntitiesWithCertainLinkIterable( transaction, entitiesWithLink, filter.union(right.filter) as EntityIterableBase) } } return super.union(right) } override fun getEntityTypeId() = entitiesWithLink.entityTypeId override fun isSortedById() = entitiesWithLink.isSortedById override fun canBeReordered() = true override fun depth() = DEPTH override fun getIteratorImpl(txn: PersistentStoreTransaction): EntityIterator { return getIteratorImpl(txn, reverse = false) } override fun getReverseIteratorImpl(txn: PersistentStoreTransaction): EntityIterator { return getIteratorImpl(txn, reverse = true) } private fun getIteratorImpl(txn: PersistentStoreTransaction, reverse: Boolean): EntityIteratorBase { val idSet = filter.toSet(txn) val it = if (reverse) entitiesWithLink.getReverseIteratorImpl(txn) else entitiesWithLink.getIteratorImpl(txn) return object : EntityIteratorBase(this) { private var distinctIds = EntityIdSetFactory.newSet() private var id = nextAvailableId() override fun hasNextImpl() = id != null override fun nextIdImpl(): EntityId? { val result = id distinctIds = distinctIds.add(result) id = nextAvailableId() return result } private fun nextAvailableId(): EntityId? { while (it.hasNext()) { val next = it.nextId() if (idSet.contains(it.targetId) && !distinctIds.contains(next)) { return next } } return null } }.apply { it.cursor?.let { cursor = it } } } override fun getHandleImpl(): EntityIterableHandle { return object : EntityIterableHandleDecorator(store, EntityIterableType.FILTER_LINKS, entitiesWithLink.handle) { private val linkIds = mergeFieldIds(intArrayOf(linkId), filter.handle.linkIds) override fun getLinkIds() = linkIds override fun toString(builder: StringBuilder) { super.toString(builder) applyDecoratedToBuilder(builder) builder.append('-') (filter.handle as EntityIterableHandleBase).toString(builder) } override fun hashCode(hash: EntityIterableHandleHash) { super.hashCode(hash) hash.applyDelimiter() hash.apply(filter.handle) } override fun isMatchedLinkAdded(source: EntityId, target: EntityId, linkId: Int) = decorated.isMatchedLinkAdded(source, target, linkId) || filter.handle.isMatchedLinkAdded(source, target, linkId) override fun isMatchedLinkDeleted(source: EntityId, target: EntityId, id: Int) = decorated.isMatchedLinkDeleted(source, target, id) || filter.handle.isMatchedLinkDeleted(source, target, id) } } }
apache-2.0
b5bc861a272a07701b0c09647650dabb
38.677686
120
0.631042
5.429864
false
false
false
false
siosio/intellij-community
platform/platform-util-io/src/com/intellij/execution/util/ExecUtil.kt
1
11862
// 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.execution.util import com.intellij.execution.CommandLineUtil import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.process.ProcessOutput import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.PathExecLazyValue import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.util.io.IdeUtilIoBundle import org.jetbrains.annotations.Nls import java.io.* import java.nio.charset.Charset object ExecUtil { private val hasGkSudo = PathExecLazyValue.create("gksudo") private val hasKdeSudo = PathExecLazyValue.create("kdesudo") private val hasPkExec = PathExecLazyValue.create("pkexec") private val hasGnomeTerminal = PathExecLazyValue.create("gnome-terminal") private val hasKdeTerminal = PathExecLazyValue.create("konsole") private val hasUrxvt = PathExecLazyValue.create("urxvt") private val hasXTerm = PathExecLazyValue.create("xterm") private val hasSetsid = PathExecLazyValue.create("setsid") @field:NlsSafe private const val nicePath = "/usr/bin/nice" private val hasNice by lazy { File(nicePath).exists() } @JvmStatic val osascriptPath: String @NlsSafe get() = "/usr/bin/osascript" @JvmStatic val openCommandPath: String @NlsSafe get() = "/usr/bin/open" @JvmStatic val windowsShellName: String get() = CommandLineUtil.getWinShellName() @JvmStatic @Throws(IOException::class) fun loadTemplate(loader: ClassLoader, templateName: String, variables: Map<String, String>?): String { val stream = loader.getResourceAsStream(templateName) ?: throw IOException("Template '$templateName' not found by $loader") val template = FileUtil.loadTextAndClose(InputStreamReader(stream, Charsets.UTF_8)) if (variables == null || variables.isEmpty()) { return template } val buffer = StringBuilder(template) for ((name, value) in variables) { val pos = buffer.indexOf(name) if (pos >= 0) { buffer.replace(pos, pos + name.length, value) } } return buffer.toString() } @JvmStatic @Throws(IOException::class, ExecutionException::class) fun createTempExecutableScript(@NlsSafe prefix: String, @NlsSafe suffix: String, @NlsSafe content: String): File { val tempDir = File(PathManager.getTempPath()) val tempFile = FileUtil.createTempFile(tempDir, prefix, suffix, true, true) FileUtil.writeToFile(tempFile, content.toByteArray(Charsets.UTF_8)) if (!tempFile.setExecutable(true, true)) { throw ExecutionException(IdeUtilIoBundle.message("dialog.message.failed.to.make.temp.file.executable", tempFile)) } return tempFile } @JvmStatic @Throws(ExecutionException::class) fun execAndGetOutput(commandLine: GeneralCommandLine): ProcessOutput = CapturingProcessHandler(commandLine).runProcess() @JvmStatic @Throws(ExecutionException::class) fun execAndGetOutput(commandLine: GeneralCommandLine, timeoutInMilliseconds: Int): ProcessOutput = CapturingProcessHandler(commandLine).runProcess(timeoutInMilliseconds) @JvmStatic fun execAndGetOutput(commandLine: GeneralCommandLine, stdin: String): String = CapturingProcessHandler(commandLine).also { processHandler -> processHandler.addProcessListener(object : ProcessAdapter() { override fun startNotified(event: ProcessEvent) { processHandler.processInput.writer(commandLine.charset).use { it.write(stdin) } } }) }.runProcess().stdout @JvmStatic fun execAndReadLine(commandLine: GeneralCommandLine): String? = try { readFirstLine(commandLine.createProcess().inputStream, commandLine.charset) } catch (e: ExecutionException) { Logger.getInstance(ExecUtil::class.java).debug(e) null } @JvmStatic fun readFirstLine(stream: InputStream, cs: Charset?): String? = try { BufferedReader(if (cs == null) InputStreamReader(stream) else InputStreamReader(stream, cs)).use { it.readLine() } } catch (e: IOException) { Logger.getInstance(ExecUtil::class.java).debug(e) null } /** * Run the command with superuser privileges using safe escaping and quoting. * * No shell substitutions, input/output redirects, etc. in the command are applied. * * @param commandLine the command line to execute * @param prompt the prompt string for the users (not used on Windows) * @return the results of running the process */ @JvmStatic @Throws(ExecutionException::class, IOException::class) fun sudo(commandLine: GeneralCommandLine, prompt: @Nls String): Process = sudoCommand(commandLine, prompt).createProcess() @JvmStatic @Throws(ExecutionException::class, IOException::class) fun sudoCommand(commandLine: GeneralCommandLine, prompt: @Nls String): GeneralCommandLine { if (SystemInfo.isUnix && "root" == System.getenv("USER")) { //NON-NLS return commandLine } val command = mutableListOf(commandLine.exePath) command += commandLine.parametersList.list val sudoCommandLine = when { SystemInfoRt.isWindows -> { val launcherExe = PathManager.findBinFileWithException("launcher.exe") GeneralCommandLine(listOf(launcherExe.toString(), commandLine.exePath) + commandLine.parametersList.parameters) } SystemInfoRt.isMac -> { val escapedCommand = StringUtil.join(command, { escapeAppleScriptArgument(it) }, " & \" \" & ") val messageArg = " with prompt \"${StringUtil.escapeQuotes(prompt)}\"" val escapedScript = "tell current application\n" + " activate\n" + " do shell script ${escapedCommand}${messageArg} with administrator privileges without altering line endings\n" + "end tell" GeneralCommandLine(osascriptPath, "-e", escapedScript) } // other UNIX hasGkSudo.value -> { GeneralCommandLine(listOf("gksudo", "--message", prompt, "--") + envCommand(commandLine) + command)//NON-NLS } hasKdeSudo.value -> { GeneralCommandLine(listOf("kdesudo", "--comment", prompt, "--") + envCommand(commandLine) + command)//NON-NLS } hasPkExec.value -> { GeneralCommandLine(listOf("pkexec") + envCommand(commandLine) + command)//NON-NLS } hasTerminalApp() -> { val escapedCommandLine = StringUtil.join(command, { escapeUnixShellArgument(it) }, " ") @NlsSafe val escapedEnvCommand = when (val args = envCommandArgs(commandLine)) { emptyList<String>() -> "" else -> "env " + StringUtil.join(args, { escapeUnixShellArgument(it) }, " ") + " " } val script = createTempExecutableScript( "sudo", ".sh", "#!/bin/sh\n" + "echo " + escapeUnixShellArgument(prompt) + "\n" + "echo\n" + "sudo -- " + escapedEnvCommand + escapedCommandLine + "\n" + "STATUS=$?\n" + "echo\n" + "read -p \"Press Enter to close this window...\" TEMP\n" + "exit \$STATUS\n") GeneralCommandLine(getTerminalCommand(IdeUtilIoBundle.message("terminal.title.install"), script.absolutePath)) } else -> { throw UnsupportedOperationException("Cannot `sudo` on this system - no suitable utils found") } } val parentEnvType = GeneralCommandLine.ParentEnvironmentType.NONE return sudoCommandLine .withWorkDirectory(commandLine.workDirectory) .withEnvironment(commandLine.environment) .withParentEnvironmentType(parentEnvType) .withRedirectErrorStream(commandLine.isRedirectErrorStream) } private fun envCommand(commandLine: GeneralCommandLine): List<String> = when (val args = envCommandArgs(commandLine)) { emptyList<String>() -> emptyList() else -> listOf("env") + args } private fun envCommandArgs(commandLine: GeneralCommandLine): List<String> = // sudo doesn't pass parent process environment for security reasons, // for the same reasons we pass only explicitly configured env variables when (val env = commandLine.environment) { emptyMap<String, String>() -> emptyList() else -> env.map { entry -> "${entry.key}=${entry.value}" } } @JvmStatic @Throws(IOException::class, ExecutionException::class) fun sudoAndGetOutput(commandLine: GeneralCommandLine, prompt: String): ProcessOutput = execAndGetOutput(sudoCommand(commandLine, prompt)) @NlsSafe private fun escapeAppleScriptArgument(arg: String) = "quoted form of \"${arg.replace("\"", "\\\"").replace("\\", "\\\\")}\"" @JvmStatic fun escapeUnixShellArgument(arg: String): String = "'${arg.replace("'", "'\"'\"'")}'" @JvmStatic fun hasTerminalApp(): Boolean = SystemInfo.isWindows || SystemInfo.isMac || hasKdeTerminal.value || hasGnomeTerminal.value || hasUrxvt.value || hasXTerm.value @NlsSafe @JvmStatic fun getTerminalCommand(@Nls(capitalization = Nls.Capitalization.Title) title: String?, command: String): List<String> = when { SystemInfo.isWindows -> { listOf(windowsShellName, "/c", "start", GeneralCommandLine.inescapableQuote(title?.replace('"', '\'') ?: ""), command) } SystemInfo.isMac -> { listOf(openCommandPath, "-a", "Terminal", command) } hasKdeTerminal.value -> { if (title != null) listOf("konsole", "-p", "tabtitle=\"${title.replace('"', '\'')}\"", "-e", command) else listOf("konsole", "-e", command) } hasGnomeTerminal.value -> { if (title != null) listOf("gnome-terminal", "-t", title, "-x", command) else listOf("gnome-terminal", "-x", command) } hasUrxvt.value -> { if (title != null) listOf("urxvt", "-title", title, "-e", command) else listOf("urxvt", "-e", command) } hasXTerm.value -> { if (title != null) listOf("xterm", "-T", title, "-e", command) else listOf("xterm", "-e", command) } else -> { throw UnsupportedOperationException("Unsupported OS/desktop: ${SystemInfo.OS_NAME}/${System.getenv("XDG_CURRENT_DESKTOP")}") } } /** * Wraps the commandline process with the OS specific utility * to mark the process to run with low priority. * * NOTE. Windows implementation does not return the original process exit code! */ @JvmStatic fun setupLowPriorityExecution(commandLine: GeneralCommandLine) { if (canRunLowPriority()) { val executablePath = commandLine.exePath if (SystemInfo.isWindows) { commandLine.exePath = windowsShellName commandLine.parametersList.prependAll("/c", "start", "/b", "/low", "/wait", GeneralCommandLine.inescapableQuote(""), executablePath) } else { commandLine.exePath = nicePath commandLine.parametersList.prependAll("-n", "10", executablePath) } } } private fun canRunLowPriority() = Registry.`is`("ide.allow.low.priority.process") && (SystemInfo.isWindows || hasNice) @JvmStatic fun setupNoTtyExecution(commandLine: GeneralCommandLine) { if (SystemInfo.isLinux && hasSetsid.value) { val executablePath = commandLine.exePath commandLine.exePath = "setsid" commandLine.parametersList.prependAll(executablePath) } } }
apache-2.0
300e88b3707ca340d23ae888214d1242
38.808725
140
0.692801
4.449362
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaSyncImpl.kt
2
1049
package eu.kanade.tachiyomi.data.database.models class MangaSyncImpl : MangaSync { override var id: Long? = null override var manga_id: Long = 0 override var sync_id: Int = 0 override var remote_id: Int = 0 override lateinit var title: String override var last_chapter_read: Int = 0 override var total_chapters: Int = 0 override var score: Float = 0f override var status: Int = 0 override var update: Boolean = false override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || javaClass != other.javaClass) return false val mangaSync = other as MangaSync if (manga_id != mangaSync.manga_id) return false if (sync_id != mangaSync.sync_id) return false return remote_id == mangaSync.remote_id } override fun hashCode(): Int { var result = (manga_id xor manga_id.ushr(32)).toInt() result = 31 * result + sync_id result = 31 * result + remote_id return result } }
gpl-3.0
96be0f60e81880b8c8a1bdff9d983619
23.395349
71
0.627264
4.081712
false
false
false
false
550609334/Twobbble
app/src/main/java/com/twobbble/view/customview/NormalDivider.kt
1
1586
package com.twobbble.view.customview import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.view.View import com.twobbble.R import com.twobbble.application.App import com.twobbble.tools.Utils /** * 主页RecyclerView的分隔线 */ class NormalDivider : RecyclerView.ItemDecoration() { private val mDivider: Drawable init { val typedArray = App.instance.obtainStyledAttributes(attrs) //将数组转化为TypedArray mDivider = typedArray.getDrawable(0) //取出这个Drawable文件 typedArray.recycle() //回收TypedArray } override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) { val childCount = parent.childCount if (childCount != 0) { for (i in 0 until childCount) { if (i != childCount - 1) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + mDivider.intrinsicHeight mDivider.alpha = 100 mDivider.setBounds(0, top, parent.width, bottom) mDivider.draw(c) } } } } companion object { private val attrs = intArrayOf(android.R.attr.listDivider)//系统自带分割线文件,获取后先保存为数组 } }
apache-2.0
8d1132d558719b9b221d4b315153b61b
31.085106
90
0.640584
4.51497
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt
5
1720
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.psi.KtCatchClause import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtTryExpression class LiftAssignmentOutOfTryFix(element: KtTryExpression) : KotlinQuickFixAction<KtTryExpression>(element) { override fun getFamilyName() = text override fun getText() = KotlinBundle.message("lift.assignment.out.of.try.expression") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return BranchedFoldingUtils.tryFoldToAssignment(element) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val expression = diagnostic.psiElement as? KtExpression ?: return null val originalCatch = expression.parent.parent?.parent as? KtCatchClause ?: return null val tryExpression = originalCatch.parent as? KtTryExpression ?: return null if (BranchedFoldingUtils.getFoldableAssignmentNumber(tryExpression) < 1) return null return LiftAssignmentOutOfTryFix(tryExpression) } } }
apache-2.0
a705c615e99f3c59990b7cc29989f77a
45.513514
158
0.773837
5.043988
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckIntention.kt
1
2324
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory abstract class ReplaceSizeCheckIntention(textGetter: () -> String) : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, textGetter ) { override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val target = getTargetExpression(element) ?: return val replacement = getReplacement(target) element.replaced(replacement.newExpression()) } override fun isApplicableTo(element: KtBinaryExpression): Boolean { val targetExpression = getTargetExpression(element) ?: return false val isSizeOrLength = targetExpression.isSizeOrLength() val isCountCall = targetExpression.isTargetCountCall() if (!isSizeOrLength && !isCountCall) return false val replacement = getReplacement(targetExpression, isCountCall) replacement.intentionTextGetter?.let { setTextGetter(it) } return true } protected abstract fun getTargetExpression(element: KtBinaryExpression): KtExpression? protected abstract fun getReplacement(expression: KtExpression, isCountCall: Boolean = expression.isTargetCountCall()): Replacement protected class Replacement( private val targetExpression: KtExpression, private val newFunctionCall: String, private val negate: Boolean = false, val intentionTextGetter: (() -> String)? = null ) { fun newExpression(): KtExpression { val excl = if (negate) "!" else "" val receiver = if (targetExpression is KtDotQualifiedExpression) "${targetExpression.receiverExpression.text}." else "" return KtPsiFactory(targetExpression).createExpression("$excl$receiver$newFunctionCall") } } private fun KtExpression.isTargetCountCall() = isCountCall { it.valueArguments.isEmpty() } }
apache-2.0
ea17deddfa42496c1fb14392afbcb2e9
43.711538
158
0.741394
5.318078
false
false
false
false
loxal/FreeEthereum
free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/suite/model/BlockTck.kt
1
1968
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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.ethereum.jsontestsuite.suite.model import org.codehaus.jackson.annotate.JsonIgnoreProperties @JsonIgnoreProperties("acomment", "comment", "chainname", "chainnetwork") class BlockTck { var blockHeader: BlockHeaderTck? = null var transactions: List<TransactionTck>? = null var uncleHeaders: List<BlockHeaderTck>? = null var rlp: String? = null var blocknumber: String? = null var isReverted: Boolean = false override fun toString(): String { return "Block{" + "blockHeader=" + blockHeader + ", transactions=" + transactions + ", uncleHeaders=" + uncleHeaders + ", rlp='" + rlp + '\'' + '}' } }
mit
dadab28ff850cb16a83cd18e575b700f
38.36
83
0.699187
4.432432
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/data/ispn/history/GenericHistoryDaoImpl.kt
1
7950
package com.github.kerubistan.kerub.data.ispn.history import com.github.kerubistan.kerub.data.HistoryDao import com.github.kerubistan.kerub.data.ispn.batch import com.github.kerubistan.kerub.data.ispn.list import com.github.kerubistan.kerub.data.ispn.queryBuilder import com.github.kerubistan.kerub.model.Range import com.github.kerubistan.kerub.model.dynamic.DynamicEntity import com.github.kerubistan.kerub.model.history.ChangeEvent import com.github.kerubistan.kerub.model.history.DataPropertyChangeSummary import com.github.kerubistan.kerub.model.history.HistoryEntry import com.github.kerubistan.kerub.model.history.HistorySummary import com.github.kerubistan.kerub.model.history.NumericPropertyChangeSummary import com.github.kerubistan.kerub.model.history.PropertyChange import com.github.kerubistan.kerub.model.history.PropertyChangeSummary import com.github.kerubistan.kerub.utils.bd import com.github.kerubistan.kerub.utils.decimalAvgBy import com.github.kerubistan.kerub.utils.equalsAnyOf import com.github.kerubistan.kerub.utils.subLists import io.github.kerubistan.kroki.collections.concat import org.infinispan.Cache import org.infinispan.query.dsl.Query import java.io.Serializable import java.math.BigDecimal import java.util.UUID import kotlin.reflect.KClass abstract class GenericHistoryDaoImpl<in T : DynamicEntity>( private val cache: Cache<UUID, HistoryEntry> ) : HistoryDao<T> { companion object { private const val minimumExtreme = 10 internal val appVersion = GenericHistoryDaoImpl::class.java.`package`.implementationVersion internal fun getPropertyType(property: String, ofClazz: KClass<out Any>) = ofClazz.java.declaredFields.firstOrNull { it.name == property }?.type internal fun isNumber(clazz: Class<*>) = if (clazz.isPrimitive) { clazz.name.equalsAnyOf("double", "float", "byte", "char", "int", "long") } else { Number::class.java.isAssignableFrom(clazz) } internal fun isData(clazz: Class<*>): Boolean = clazz.kotlin.isData internal fun isList(clazz: Class<*>): Boolean = clazz.isAssignableFrom(List::class.java) internal fun changedPropertyNames(changes: List<HistoryEntry>) = changes.filterIsInstance(ChangeEvent::class.java).map { it.changes.map { it.property } }.concat().toSet() + changes.filterIsInstance(HistorySummary::class.java).map { it.changes.map { it.property } }.concat().toSet() internal fun changesOfProperty(propName: String, changes: List<HistoryEntry>) = changes.filter { when (it) { is ChangeEvent -> it.changes.any { it.property == propName } is HistorySummary -> it.changes.any { it.property == propName } else -> TODO("Not handled HistoryEntry") } } private val nevValueAsNumber: (Pair<Long, PropertyChange>) -> BigDecimal = { bd(it.second.newValue) ?: BigDecimal.ZERO } /** * TODO * * Some typical workload as a reminder for myself: * - batch style: occurs regularly a static number of times a day * - ad-hoc style: * * An extreme is: * A period of time when the values are higher than the average * * Maximum number of extremes: * There should be a maximum number of extremes, if there are more extremes than that, * then maybe we should call it the normal behavior of the application. */ internal fun detectExtremes(changes: List<Pair<Long, PropertyChange>>): List<List<PropertyChange>> { val sortedChanges = changes.sortedBy(nevValueAsNumber) val totalAvg = changes.decimalAvgBy(nevValueAsNumber) val median = sortedChanges.minBy { (nevValueAsNumber(it) - totalAvg).abs() } val medianPosition = sortedChanges.indexOf(median) val upperHalf = sortedChanges.subList(medianPosition, sortedChanges.size) val upperAvg = upperHalf.decimalAvgBy(nevValueAsNumber) return changes.subLists(minimumExtreme) { nevValueAsNumber(it) > upperAvg }.map { it.map { it.second } } } } override fun log(oldEntry: T, newEntry: T) { val change = ChangeEvent( entityKey = oldEntry.id, appVersion = appVersion, changes = changes(oldEntry, newEntry) ) cache.putAsync(change.id, change) } internal fun list(id: UUID, clazz: KClass<out HistoryEntry>): List<HistoryEntry> = cache.queryBuilder(clazz).having(HistoryEntry::entityKeyStr.name).eq(id.toString()).list() override fun list(id: UUID): List<HistoryEntry> = list(id, ChangeEvent::class) + list(id, HistorySummary::class) internal fun history(from: Long, to: Long, entityId: UUID) = // events cache.queryBuilder(ChangeEvent::class) .having(ChangeEvent::time.name).between(from, to) .and().having(ChangeEvent::entityKeyStr.name).eq(entityId.toString()).toBuilder<Query>() .orderBy(ChangeEvent::time.name) .list<HistoryEntry>() + // and summarized events cache.queryBuilder(HistorySummary::class) .having(HistorySummary::start.name) .between(from, to) .and() .having(HistorySummary::end.name) .between(from, to) .and() .having(HistorySummary::entityKeyStr.name).eq(entityId.toString()).toBuilder<Query>() .orderBy(HistorySummary::start.name) .list() override fun compress(from: Long, to: Long, entityIds: Collection<UUID>) { entityIds.forEach { entityId -> cache.batch { val changes = history(from, to, entityId) if (changes.isNotEmpty()) { val summary = HistorySummary( appVersion = appVersion, changes = sum(changes), //TODO entityKey = changes.first().entityKey as Serializable, time = Range(from, to) ) cache.putAsync(summary.id, summary) changes.forEach { cache.remove(it.id) } } } } } internal abstract val dynClass: KClass<out DynamicEntity> open fun sum(changes: List<HistoryEntry>): List<PropertyChangeSummary> = changedPropertyNames(changes).map { changedProperty -> val propertyChanges = changesOfProperty(changedProperty, changes) val propertyType = getPropertyType(changedProperty, dynClass) when { propertyType == null -> TODO() isNumber(propertyType) -> { fun genericSelector( summarySelector: (HistorySummary) -> BigDecimal): (HistoryEntry) -> BigDecimal = { when (it) { is HistorySummary -> summarySelector(it) is ChangeEvent -> bd(it.changes.single { it.property == changedProperty }.newValue) ?: BigDecimal.ZERO else -> TODO() } } val maxSelector: (HistoryEntry) -> BigDecimal = genericSelector { bd((it.changes.single { changeSummary -> changeSummary.property == changedProperty } as NumericPropertyChangeSummary).max) ?: BigDecimal.ZERO } val minSelector: (HistoryEntry) -> BigDecimal = genericSelector { bd((it.changes.single { changeSummary -> changeSummary.property == changedProperty } as NumericPropertyChangeSummary).min) ?: BigDecimal.ZERO } NumericPropertyChangeSummary( property = changedProperty, average = propertyChanges.decimalAvgBy { BigDecimal.ZERO /*TODO*/ }, //there is at least one element, therefore there must be a maximum max = requireNotNull(propertyChanges.map(maxSelector).max()), //and same for minimums min = requireNotNull(propertyChanges.map(minSelector).min()), extremes = listOf() ) } isData(propertyType) -> //TODO DataPropertyChangeSummary( property = changedProperty, changes = mapOf() ) isList(propertyType) -> //TODO DataPropertyChangeSummary( property = changedProperty, changes = mapOf() ) else -> //TODO DataPropertyChangeSummary( property = changedProperty, changes = mapOf() ) } } abstract fun changes(oldEntry: T, newEntry: T): List<PropertyChange> }
apache-2.0
ad7e66e4749e07f7484217c6a3d6fefc
32.690678
102
0.696981
3.982966
false
false
false
false
jwren/intellij-community
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/CodeGolfMetrics.kt
4
3121
package com.intellij.cce.metric import com.intellij.cce.core.Session import com.intellij.cce.metric.util.Sample abstract class CodeGolfMetric<T : Number> : Metric { protected var sample = Sample() private fun T.alsoAddToSample(): T = also { sample.add(it.toDouble()) } protected fun computeMoves(session: Session): Int = session.lookups.sumBy { if (it.selectedPosition >= 0) it.selectedPosition else 0 } protected fun computeCompletionCalls(sessions: List<Session>): Int = sessions.sumBy { it.lookups.count { lookup -> lookup.isNew } } override fun evaluate(sessions: List<Session>, comparator: SuggestionsComparator): T = compute(sessions, comparator).alsoAddToSample() abstract fun compute(sessions: List<Session>, comparator: SuggestionsComparator): T } class CodeGolfMovesSumMetric : CodeGolfMetric<Int>() { override val name: String = "Code Golf Moves Count" override val valueType = MetricValueType.INT override val value: Double get() = sample.sum() override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Int { // Add x2 amount of lookups, assuming that before each action we call code completion // We summarize 3 types of actions: // call code completion (1 point) // choice suggestion from completion or symbol (if there is no offer in completion) (1 point) // navigation to the suggestion (if it fits) (N points, based on suggestion index, assuming first index is 0) return sessions.map { computeMoves(it) + it.lookups.count() } .sum() .plus(computeCompletionCalls(sessions)) } } class CodeGolfMovesCountNormalised : CodeGolfMetric<Double>() { override val name: String = "Code Golf Moves Count Normalised" override val valueType = MetricValueType.DOUBLE override val value: Double get() = sample.mean() override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Double { val linesLength = sessions.sumBy { it.expectedText.length } * 2.0 val amountOfMoves = sessions.sumBy { computeMoves(it) + it.lookups.count() } + computeCompletionCalls(sessions) val subtrahend = sessions.count() * 2.0 // Since code completion's call and the choice of option (symbol) contains in each lookup, // It is enough to calculate the difference for the number of lookups and extra moves (for completion case) // To reach 0%, you also need to subtract the minimum number of lookups (eq. number of sessions plus minimum amount of completion calls) // 0% - best scenario, every line was completed from start to end with first suggestion in list // >100% is possible, when navigation in completion takes too many moves return ((amountOfMoves - subtrahend) / (linesLength - subtrahend)) } } class CodeGolfPerfectLine : CodeGolfMetric<Int>() { override val name: String = "Code Golf Perfect Line" override val valueType = MetricValueType.INT override val value: Double get() = sample.sum() override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Int { return sessions.filter { it.success } .count() } }
apache-2.0
a8a0cbefa1b7f8067e8d00c94639d7ce
40.613333
140
0.732458
4.365035
false
false
false
false
androidx/androidx
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/impl/UseCaseCameraState.kt
3
9168
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package androidx.camera.camera2.pipe.integration.impl import android.hardware.camera2.CaptureRequest import androidx.annotation.GuardedBy import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.Metadata import androidx.camera.camera2.pipe.Request import androidx.camera.camera2.pipe.RequestTemplate import androidx.camera.camera2.pipe.StreamId import androidx.camera.camera2.pipe.integration.config.UseCaseCameraScope import androidx.camera.camera2.pipe.integration.config.UseCaseGraphConfig import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch import javax.inject.Inject /** * This object keeps track of the state of the current [UseCaseCamera]. * * Updates to the camera from this class are batched together. That is, if multiple updates * happen while some other system is holding the cameraGraph session, those updates will be * aggregated together and applied when the session becomes available. This also serves as a form * of primitive rate limiting that ensures that updates arriving too quickly are only sent to the * underlying camera graph as fast as the camera is capable of consuming them. */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java @UseCaseCameraScope class UseCaseCameraState @Inject constructor( useCaseGraphConfig: UseCaseGraphConfig, private val threads: UseCaseThreads ) { private val lock = Any() private val cameraGraph = useCaseGraphConfig.graph @GuardedBy("lock") private var updateSignal: CompletableDeferred<Unit>? = null @GuardedBy("lock") private var updating = false @GuardedBy("lock") private val currentParameters = mutableMapOf<CaptureRequest.Key<*>, Any>() @GuardedBy("lock") private val currentInternalParameters = mutableMapOf<Metadata.Key<*>, Any>() @GuardedBy("lock") private val currentStreams = mutableSetOf<StreamId>() @GuardedBy("lock") private val currentListeners = mutableSetOf<Request.Listener>() @GuardedBy("lock") private var currentTemplate: RequestTemplate? = null fun updateAsync( parameters: Map<CaptureRequest.Key<*>, Any>? = null, appendParameters: Boolean = true, internalParameters: Map<Metadata.Key<*>, Any>? = null, appendInternalParameters: Boolean = true, streams: Set<StreamId>? = null, template: RequestTemplate? = null, listeners: Set<Request.Listener>? = null ): Deferred<Unit> { val result: Deferred<Unit> synchronized(lock) { // This block does several things while locked, and is paired with another // synchronized(lock) section in the submitLatest() method below that prevents these // two blocks from ever executing at the same time, even if invoked by multiple // threads. // 1) Update the internal state (locked) // 2) Since a prior update may have happened that didn't need a completion signal, // it is possible that updateSignal is null. Regardless of the need to resubmit or // not, the updateSignal must have a value to be returned. // 3) If an update is already dispatched, return existing update signal. This // updateSignal may be the value from #2 (this is fine). // 4) If we get this far, we need to dispatch an update. Mark this as updating, and // exit the locked section. // 5) If updating, invoke submit without holding the lock. updateState( parameters, appendParameters, internalParameters, appendInternalParameters, streams, template, listeners ) if (updateSignal == null) { updateSignal = CompletableDeferred() } if (updating) { return updateSignal!! } // Fall through to submit if there is no pending update. updating = true result = updateSignal!! } submitLatest() return result } fun update( parameters: Map<CaptureRequest.Key<*>, Any>? = null, appendParameters: Boolean = true, internalParameters: Map<Metadata.Key<*>, Any>? = null, appendInternalParameters: Boolean = true, streams: Set<StreamId>? = null, template: RequestTemplate? = null, listeners: Set<Request.Listener>? = null ) { synchronized(lock) { // See updateAsync for details. updateState( parameters, appendParameters, internalParameters, appendInternalParameters, streams, template, listeners ) if (updating) { return } updating = true } submitLatest() } fun capture(requests: List<Request>) { threads.scope.launch(start = CoroutineStart.UNDISPATCHED) { cameraGraph.acquireSession().use { it.submit(requests) } } } @GuardedBy("lock") private inline fun updateState( parameters: Map<CaptureRequest.Key<*>, Any>? = null, appendParameters: Boolean = true, internalParameters: Map<Metadata.Key<*>, Any>? = null, appendInternalParameters: Boolean = true, streams: Set<StreamId>? = null, template: RequestTemplate? = null, listeners: Set<Request.Listener>? = null ) { // TODO: Consider if this should detect changes and only invoke an update if state has // actually changed. if (parameters != null) { if (!appendParameters) { currentParameters.clear() } currentParameters.putAll(parameters) } if (internalParameters != null) { if (!appendInternalParameters) { currentInternalParameters.clear() } currentInternalParameters.putAll(internalParameters) } if (streams != null) { currentStreams.clear() currentStreams.addAll(streams) } if (template != null) { currentTemplate = template } if (listeners != null) { currentListeners.clear() currentListeners.addAll(listeners) } } @OptIn(ExperimentalCoroutinesApi::class) private fun submitLatest() { // Update the cameraGraph with the most recent set of values. // Since acquireSession is a suspending function, it's possible that subsequent updates // can occur while waiting for the acquireSession call to complete. If this happens, // updates to the internal state are aggregated together, and the Request is built // synchronously with the latest values. The startRepeating/stopRepeating call happens // outside of the synchronized block to avoid holding a lock while updating the camera // state. threads.scope.launch(start = CoroutineStart.UNDISPATCHED) { val result: CompletableDeferred<Unit>? cameraGraph.acquireSession().use { val request: Request? synchronized(lock) { request = if (currentStreams.isEmpty()) { null } else { Request( template = currentTemplate, streams = currentStreams.toList(), parameters = currentParameters.toMap(), extras = currentInternalParameters.toMap(), listeners = currentListeners.toList() ) } result = updateSignal updateSignal = null updating = false } if (request == null) { it.stopRepeating() } else { it.startRepeating(request) } } // Complete the result after the session closes to allow other threads to acquire a // lock. This also avoids cases where complete() synchronously invokes expensive calls. result?.complete(Unit) } } }
apache-2.0
9e8691a8f30ed4023cbfcc2a70d56974
37.687764
99
0.625327
5.29636
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/activities/ManageBlockedNumbersActivity.kt
1
10296
package com.simplemobiletools.commons.activities import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Toast import com.simplemobiletools.commons.R import com.simplemobiletools.commons.adapters.ManageBlockedNumbersAdapter import com.simplemobiletools.commons.dialogs.AddBlockedNumberDialog import com.simplemobiletools.commons.dialogs.ExportBlockedNumbersDialog import com.simplemobiletools.commons.dialogs.FilePickerDialog import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.helpers.BlockedNumbersExporter.ExportResult import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener import com.simplemobiletools.commons.models.BlockedNumber import kotlinx.android.synthetic.main.activity_manage_blocked_numbers.* import java.io.FileOutputStream import java.io.OutputStream class ManageBlockedNumbersActivity : BaseSimpleActivity(), RefreshRecyclerViewListener { private val PICK_IMPORT_SOURCE_INTENT = 11 private val PICK_EXPORT_FILE_INTENT = 21 override fun getAppIconIDs() = intent.getIntegerArrayListExtra(APP_ICON_IDS) ?: ArrayList() override fun getAppLauncherName() = intent.getStringExtra(APP_LAUNCHER_NAME) ?: "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_manage_blocked_numbers) updateBlockedNumbers() setupOptionsMenu() updateTextColors(manage_blocked_numbers_wrapper) updatePlaceholderTexts() val blockTitleRes = if (baseConfig.appId.startsWith("com.simplemobiletools.dialer")) R.string.block_unknown_calls else R.string.block_unknown_messages block_unknown.apply { setText(blockTitleRes) isChecked = baseConfig.blockUnknownNumbers if (isChecked) { maybeSetDefaultCallerIdApp() } } block_unknown_holder.setOnClickListener { block_unknown.toggle() baseConfig.blockUnknownNumbers = block_unknown.isChecked if (block_unknown.isChecked) { maybeSetDefaultCallerIdApp() } } manage_blocked_numbers_placeholder_2.apply { underlineText() setTextColor(getProperPrimaryColor()) setOnClickListener { if (isDefaultDialer()) { addOrEditBlockedNumber() } else { launchSetDefaultDialerIntent() } } } } override fun onResume() { super.onResume() setupToolbar(block_numbers_toolbar, NavigationIcon.Arrow) } private fun setupOptionsMenu() { block_numbers_toolbar.setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.add_blocked_number -> { addOrEditBlockedNumber() true } R.id.import_blocked_numbers -> { tryImportBlockedNumbers() true } R.id.export_blocked_numbers -> { tryExportBlockedNumbers() true } else -> false } } } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { super.onActivityResult(requestCode, resultCode, resultData) if (requestCode == REQUEST_CODE_SET_DEFAULT_DIALER && isDefaultDialer()) { updatePlaceholderTexts() updateBlockedNumbers() } else if (requestCode == PICK_IMPORT_SOURCE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) { tryImportBlockedNumbersFromFile(resultData.data!!) } else if (requestCode == PICK_EXPORT_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) { val outputStream = contentResolver.openOutputStream(resultData.data!!) exportBlockedNumbersTo(outputStream) } else if (requestCode == REQUEST_CODE_SET_DEFAULT_CALLER_ID && resultCode != Activity.RESULT_OK) { toast(R.string.must_make_default_caller_id_app, length = Toast.LENGTH_LONG) baseConfig.blockUnknownNumbers = false block_unknown.isChecked = false } } override fun refreshItems() { updateBlockedNumbers() } private fun updatePlaceholderTexts() { manage_blocked_numbers_placeholder.text = getString(if (isDefaultDialer()) R.string.not_blocking_anyone else R.string.must_make_default_dialer) manage_blocked_numbers_placeholder_2.text = getString(if (isDefaultDialer()) R.string.add_a_blocked_number else R.string.set_as_default) } private fun updateBlockedNumbers() { ensureBackgroundThread { val blockedNumbers = getBlockedNumbers() runOnUiThread { ManageBlockedNumbersAdapter(this, blockedNumbers, this, manage_blocked_numbers_list) { addOrEditBlockedNumber(it as BlockedNumber) }.apply { manage_blocked_numbers_list.adapter = this } manage_blocked_numbers_placeholder.beVisibleIf(blockedNumbers.isEmpty()) manage_blocked_numbers_placeholder_2.beVisibleIf(blockedNumbers.isEmpty()) if (blockedNumbers.any { it.number.isBlockedNumberPattern() }) { maybeSetDefaultCallerIdApp() } } } } private fun addOrEditBlockedNumber(currentNumber: BlockedNumber? = null) { AddBlockedNumberDialog(this, currentNumber) { updateBlockedNumbers() } } private fun tryImportBlockedNumbers() { if (isQPlus()) { Intent(Intent.ACTION_GET_CONTENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "text/plain" try { startActivityForResult(this, PICK_IMPORT_SOURCE_INTENT) } catch (e: ActivityNotFoundException) { toast(R.string.system_service_disabled, Toast.LENGTH_LONG) } catch (e: Exception) { showErrorToast(e) } } } else { handlePermission(PERMISSION_READ_STORAGE) { if (it) { pickFileToImportBlockedNumbers() } } } } private fun tryImportBlockedNumbersFromFile(uri: Uri) { when (uri.scheme) { "file" -> importBlockedNumbers(uri.path!!) "content" -> { val tempFile = getTempFile("blocked", "blocked_numbers.txt") if (tempFile == null) { toast(R.string.unknown_error_occurred) return } try { val inputStream = contentResolver.openInputStream(uri) val out = FileOutputStream(tempFile) inputStream!!.copyTo(out) importBlockedNumbers(tempFile.absolutePath) } catch (e: Exception) { showErrorToast(e) } } else -> toast(R.string.invalid_file_format) } } private fun pickFileToImportBlockedNumbers() { FilePickerDialog(this) { importBlockedNumbers(it) } } private fun importBlockedNumbers(path: String) { ensureBackgroundThread { val result = BlockedNumbersImporter(this).importBlockedNumbers(path) toast( when (result) { BlockedNumbersImporter.ImportResult.IMPORT_OK -> R.string.importing_successful BlockedNumbersImporter.ImportResult.IMPORT_FAIL -> R.string.no_items_found } ) updateBlockedNumbers() } } private fun tryExportBlockedNumbers() { if (isQPlus()) { ExportBlockedNumbersDialog(this, baseConfig.lastBlockedNumbersExportPath, true) { file -> Intent(Intent.ACTION_CREATE_DOCUMENT).apply { type = "text/plain" putExtra(Intent.EXTRA_TITLE, file.name) addCategory(Intent.CATEGORY_OPENABLE) try { startActivityForResult(this, PICK_EXPORT_FILE_INTENT) } catch (e: ActivityNotFoundException) { toast(R.string.system_service_disabled, Toast.LENGTH_LONG) } catch (e: Exception) { showErrorToast(e) } } } } else { handlePermission(PERMISSION_WRITE_STORAGE) { if (it) { ExportBlockedNumbersDialog(this, baseConfig.lastBlockedNumbersExportPath, false) { file -> getFileOutputStream(file.toFileDirItem(this), true) { out -> exportBlockedNumbersTo(out) } } } } } } private fun exportBlockedNumbersTo(outputStream: OutputStream?) { ensureBackgroundThread { val blockedNumbers = getBlockedNumbers() if (blockedNumbers.isEmpty()) { toast(R.string.no_entries_for_exporting) } else { BlockedNumbersExporter().exportBlockedNumbers(blockedNumbers, outputStream) { toast( when (it) { ExportResult.EXPORT_OK -> R.string.exporting_successful ExportResult.EXPORT_FAIL -> R.string.exporting_failed } ) } } } } private fun maybeSetDefaultCallerIdApp() { if (isQPlus() && baseConfig.appId.startsWith("com.simplemobiletools.dialer")) { setDefaultCallerIdApp() } } }
gpl-3.0
6788ab33887e1f9655aa215dcc5022a0
37.706767
158
0.588967
5.444738
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/base/enums/navigation/NavigationScreen.kt
1
1418
package com.sedsoftware.yaptalker.presentation.base.enums.navigation object NavigationScreen { const val NEWS_SCREEN = "NEWS_SCREEN" const val PICTURES_SCREEN = "PICTURES_SCREEN" const val VIDEOS_SCREEN = "VIDEOS_SCREEN" const val EVENTS_SCREEN = "EVENTS_SCREEN" const val AUTO_MOTO_SCREEN = "AUTO_MOTO_SCREEN" const val ANIMALS_SCREEN = "ANIMALS_SCREEN" const val PHOTOBOMB_SCREEN = "PHOTOBOMB_SCREEN" const val INCUBATOR_SCREEN = "INCUBATOR_SCREEN" const val FORUMS_LIST_SCREEN = "FORUMS_LIST_SCREEN" const val CHOSEN_FORUM_SCREEN = "CHOSEN_FORUM_SCREEN" const val CHOSEN_TOPIC_SCREEN = "CHOSEN_TOPIC_SCREEN" const val USER_PROFILE_SCREEN = "USER_PROFILE_SCREEN" const val AUTHORIZATION_SCREEN = "AUTHORIZATION_SCREEN" const val SETTINGS_SCREEN = "SETTINGS_SCREEN" const val MESSAGE_EDITOR_SCREEN = "MESSAGE_EDITOR_SCREEN" const val ACTIVE_TOPICS_SCREEN = "ACTIVE_TOPICS_SCREEN" const val BOOKMARKS_SCREEN = "BOOKMARKS_SCREEN" const val IMAGE_DISPLAY_SCREEN = "IMAGE_DISPLAY_SCREEN" const val VIDEO_DISPLAY_SCREEN = "VIDEO_DISPLAY_SCREEN" const val SEARCH_FORM = "SEARCH_FORM" const val SEARCH_RESULTS = "SEARCH_RESULTS" const val TOPIC_GALLERY = "TOPIC_GALLERY" const val CHANGELOG_SCREEN = "CHANGELOG_SCREEN" const val UPDATES_SCREEN = "UPDATES_SCREEN" const val RESTORED_TOPIC_SCREEN = "RESTORED_TOPIC_SCREEN" }
apache-2.0
0193ed67ff7701e77db7d03e635645d4
47.896552
68
0.728491
3.654639
false
false
false
false
GunoH/intellij-community
plugins/kotlin/frontend-independent/tests/test/org/jetbrains/kotlin/test/utils/IgnoreTests.kt
4
12819
// 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.test.utils import com.intellij.openapi.util.io.FileUtil import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.testFramework.KtUsefulTestCase import org.junit.Assert import org.slf4j.LoggerFactory import java.io.File import java.nio.file.Files import java.nio.file.Path import kotlin.io.path.* object IgnoreTests { private const val INSERT_DIRECTIVE_AUTOMATICALLY = false // TODO use environment variable instead private const val ALWAYS_CONSIDER_TEST_AS_PASSING = false // TODO use environment variable instead fun runTestIfEnabledByFileDirective( testFile: Path, enableTestDirective: String, vararg additionalFilesExtensions: String, directivePosition: DirectivePosition = DirectivePosition.FIRST_LINE_IN_FILE, test: () -> Unit, ) { runTestIfEnabledByDirective( testFile, EnableOrDisableTestDirective.Enable(enableTestDirective), directivePosition, computeAdditionalFilesByExtensions(testFile, additionalFilesExtensions.asList()), test ) } fun runTestWithFixMeSupport( testFile: Path, directivePosition: DirectivePosition = DirectivePosition.FIRST_LINE_IN_FILE, test: () -> Unit ) { runTestIfEnabledByDirective( testFile, EnableOrDisableTestDirective.Disable(DIRECTIVES.FIX_ME), directivePosition, additionalFiles = emptyList(), test = test ) } fun runTestIfNotDisabledByFileDirective( testFile: Path, disableTestDirective: String, vararg additionalFilesExtensions: String, directivePosition: DirectivePosition = DirectivePosition.FIRST_LINE_IN_FILE, test: () -> Unit ) { runTestIfNotDisabledByFileDirective( testFile, disableTestDirective, { mainTestFile -> computeAdditionalFilesByExtensions(mainTestFile, additionalFilesExtensions.asList()) }, directivePosition, test ) } fun runTestIfNotDisabledByFileDirective( testFile: Path, disableTestDirective: String, computeAdditionalFiles: (mainTestFile: Path) -> List<Path>, directivePosition: DirectivePosition = DirectivePosition.FIRST_LINE_IN_FILE, test: () -> Unit ) { runTestIfEnabledByDirective( testFile, EnableOrDisableTestDirective.Disable(disableTestDirective), directivePosition, computeAdditionalFiles(testFile), test ) } private fun runTestIfEnabledByDirective( testFile: Path, directive: EnableOrDisableTestDirective, directivePosition: DirectivePosition, additionalFiles: List<Path>, test: () -> Unit ) { if (ALWAYS_CONSIDER_TEST_AS_PASSING) { test() return } val testIsEnabled = directive.isEnabledInFile(testFile) try { test() } catch (e: Throwable) { if (testIsEnabled) { if (directive is EnableOrDisableTestDirective.Disable) { try { handleTestWithWrongDirective(testPasses = false, testFile, directive, directivePosition, additionalFiles) } catch (e: AssertionError) { LoggerFactory.getLogger("test").info(e.message) } } throw e } return } if (!testIsEnabled) { handleTestWithWrongDirective(testPasses = true, testFile, directive, directivePosition, additionalFiles) } } @OptIn(ExperimentalStdlibApi::class) private fun handleTestWithWrongDirective( testPasses: Boolean, testFile: Path, directive: EnableOrDisableTestDirective, directivePosition: DirectivePosition, additionalFiles: List<Path>, ) { val verb = when (testPasses) { false -> "do not pass" true -> "passes" } if (INSERT_DIRECTIVE_AUTOMATICALLY) { when (directive) { is EnableOrDisableTestDirective.Disable -> { testFile.removeDirectivesFromFileAndAdditionalFiles(directive, additionalFiles) } is EnableOrDisableTestDirective.Enable -> { testFile.insertDirectivesToFileAndAdditionalFile(directive, additionalFiles, directivePosition) } } val modifiedFiles = buildList { add(testFile.fileName.toString()) addAll(additionalFiles) } throw AssertionError( "Looks like the test was ${directive.fixDirectiveMessage}(e)d to the ${modifiedFiles.joinToString()}" ) } throw AssertionError( "Looks like the test $verb, please ${directive.fixDirectiveMessage} the ${testFile.fileName}" ) } private fun computeAdditionalFilesByExtensions(mainTestFile: Path, additionalFilesExtensions: List<String>): List<Path> { return additionalFilesExtensions.mapNotNull { mainTestFile.getSiblingFile(it) } } private fun Path.insertDirectivesToFileAndAdditionalFile( directive: EnableOrDisableTestDirective, additionalFiles: List<Path>, directivePosition: DirectivePosition, ) { insertDirective(directive, directivePosition) additionalFiles.forEach { it.insertDirective(directive, directivePosition) } } private fun Path.removeDirectivesFromFileAndAdditionalFiles( directive: EnableOrDisableTestDirective, additionalFiles: List<Path>, ) { removeDirective(directive) additionalFiles.forEach { it.removeDirective(directive) } } private fun Path.getSiblingFile(extension: String): Path? { val siblingName = fileName.toString() + "." + extension.removePrefix(".") return resolveSibling(siblingName).takeIf(Files::exists) } private sealed class EnableOrDisableTestDirective { abstract val directiveText: String abstract val fixDirectiveMessage: String abstract fun isEnabledIfDirectivePresent(isDirectivePresent: Boolean): Boolean data class Enable(override val directiveText: String) : EnableOrDisableTestDirective() { override val fixDirectiveMessage: String get() = "add $directiveText to" override fun isEnabledIfDirectivePresent(isDirectivePresent: Boolean): Boolean = isDirectivePresent } data class Disable(override val directiveText: String) : EnableOrDisableTestDirective() { override val fixDirectiveMessage: String get() = "remove $directiveText from" override fun isEnabledIfDirectivePresent(isDirectivePresent: Boolean): Boolean = !isDirectivePresent } } private fun EnableOrDisableTestDirective.isEnabledInFile(file: Path): Boolean { val isDirectivePresent = containsDirective(file, this) return isEnabledIfDirectivePresent(isDirectivePresent) } private fun containsDirective(file: Path, directive: EnableOrDisableTestDirective): Boolean { if (file.notExists()) return false return file.useLines { lines -> lines.any { it.isLineWithDirective(directive) } } } private fun String.isLineWithDirective(directive: EnableOrDisableTestDirective): Boolean = substringBefore(':').trim() == directive.directiveText.trim() private fun Path.insertDirective(directive: EnableOrDisableTestDirective, directivePosition: DirectivePosition) { if (notExists()) { createFile() } toFile().apply { val originalText = readText() val textWithDirective = when (directivePosition) { DirectivePosition.FIRST_LINE_IN_FILE -> "${directive.directiveText}\n$originalText" DirectivePosition.LAST_LINE_IN_FILE -> "$originalText\n${directive.directiveText}" } writeText(textWithDirective) } } private fun Path.removeDirective(directive: EnableOrDisableTestDirective) { toFile().apply { val lines = useLines { it.toList() } writeLines(lines.filterNot { it.isLineWithDirective(directive) }) } } object DIRECTIVES { const val FIR_COMPARISON = "// FIR_COMPARISON" const val FIR_COMPARISON_MULTILINE_COMMENT = "/* FIR_COMPARISON */" const val IGNORE_FIR_LOG = "// IGNORE_FIR_LOG" const val IGNORE_FIR = "// IGNORE_FIR" const val IGNORE_K2 = "// IGNORE_K2" const val IGNORE_FIR_MULTILINE_COMMENT = "/* IGNORE_FIR */" const val FIX_ME = "// FIX_ME: " const val FIR_IDENTICAL = "// FIR_IDENTICAL" const val IGNORE_FE10_BINDING_BY_FIR = "// IGNORE_FE10_BINDING_BY_FIR" const val IGNORE_FE10 = "// IGNORE_FE10" } enum class DirectivePosition { FIRST_LINE_IN_FILE, LAST_LINE_IN_FILE } private val isTeamCityBuild: Boolean get() = System.getenv("TEAMCITY_VERSION") != null || KtUsefulTestCase.IS_UNDER_TEAMCITY fun getFirTestFile(originalTestFile: File, vararg additionalFilesExtensions: String): File { if (originalTestFile.readLines().any { it.startsWith(DIRECTIVES.FIR_IDENTICAL) }) { return originalTestFile } val firTestFile = deriveFirTestFile(originalTestFile) if (!firTestFile.exists()) { FileUtil.copy(originalTestFile, firTestFile) } for (extension in additionalFilesExtensions) { val additionalFirFile = firTestFile.withExtension(firTestFile.extension + extension) val additionalOriginalFile = originalTestFile.withExtension(originalTestFile.extension + extension) if (!additionalFirFile.exists() && additionalOriginalFile.exists()) { FileUtil.copy(additionalOriginalFile, additionalFirFile) } } return firTestFile } fun getFirTestFileIfFirPassing(originalTestFile: File, passingDirective: String, vararg additionalFilesExtensions: String): File { if (!InTextDirectivesUtils.isDirectiveDefined(originalTestFile.readText(), passingDirective)) { return originalTestFile } return getFirTestFile(originalTestFile, *additionalFilesExtensions) } fun cleanUpIdenticalFirTestFile( originalTestFile: File, firTestFile: File = deriveFirTestFile(originalTestFile), additionalFileToMarkFirIdentical: File? = null, additionalFileToDeleteIfIdentical: File? = null, additionalFilesToCompare: Collection<Pair<File, File>> = emptyList() ) { if (firTestFile.exists() && firTestFile.readText().trim() == originalTestFile.readText().trim() && additionalFilesToCompare.all { (a, b) -> if (!a.exists() || !b.exists()) false else a.readText().trim() == b.readText().trim() } ) { val message = if (isTeamCityBuild) { "Please remove $firTestFile and add // FIR_IDENTICAL to test source file $originalTestFile" } else { // The FIR test file is identical with the original file. We should remove the FIR file and mark "FIR_IDENTICAL" in the // original file firTestFile.delete() originalTestFile.prependFirIdentical() additionalFileToMarkFirIdentical?.prependFirIdentical() if (additionalFileToDeleteIfIdentical?.exists() == true) additionalFileToDeleteIfIdentical.delete() "Deleted $firTestFile, added // FIR_IDENTICAL to test source file $originalTestFile" } Assert.fail( """ Dumps via FIR & via old FE are the same. $message Please re-run the test now """.trimIndent() ) } } private fun File.prependFirIdentical() { val content = readText() if (content.contains(DIRECTIVES.FIR_IDENTICAL)) return writer().use { it.appendLine(DIRECTIVES.FIR_IDENTICAL) it.append(content) } } private fun deriveFirTestFile(originalTestFile: File) = originalTestFile.parentFile.resolve(originalTestFile.name.removeSuffix(".kt") + ".fir.kt") }
apache-2.0
ae77ba8ff9248d8117565a811b3bee28
37.728097
158
0.640144
5.563802
false
true
false
false
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/WebSymbolsScopeWithCache.kt
2
6242
// 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.webSymbols import com.intellij.model.Pointer import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.util.UserDataHolder import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.Stack import com.intellij.webSymbols.completion.WebSymbolCodeCompletionItem import com.intellij.webSymbols.query.impl.SearchMap import com.intellij.webSymbols.query.* import com.intellij.webSymbols.utils.psiModificationCount import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap abstract class WebSymbolsScopeWithCache<T : UserDataHolder, K>(protected val framework: FrameworkId?, protected val project: Project, protected val dataHolder: T, protected val key: K) : WebSymbolsScope { abstract override fun createPointer(): Pointer<out WebSymbolsScopeWithCache<T, K>> private val requiresResolve: Boolean get() = true override fun getModificationCount(): Long = project.psiModificationCount final override fun equals(other: Any?): Boolean = other === this || (other != null && other is WebSymbolsScopeWithCache<*, *> && other::class.java == this::class.java && other.framework == framework && other.key == key && other.project == project && other.dataHolder == dataHolder) final override fun hashCode(): Int = Objects.hash(framework, project, dataHolder, key) private fun getNamesProviderToMapCache(): NamesProviderToMapCache { val manager = CachedValuesManager.getManager(project) return if (key == Unit) { manager.getCachedValue(dataHolder, manager.getKeyForClass(this::class.java), { CachedValueProvider.Result(NamesProviderToMapCache(), PsiModificationTracker.NEVER_CHANGED) }, false) } else { manager.getCachedValue(dataHolder, manager.getKeyForClass(this::class.java), { CachedValueProvider.Result(ConcurrentHashMap<K, NamesProviderToMapCache>(), ModificationTracker.NEVER_CHANGED) }, false).getOrPut(key) { NamesProviderToMapCache() } } } protected abstract fun initialize(consumer: (WebSymbol) -> Unit, cacheDependencies: MutableSet<Any>) private fun createCachedSearchMap(namesProvider: WebSymbolNamesProvider): CachedValue<WebSymbolsSearchMap> = CachedValuesManager.getManager(project).createCachedValue { val dependencies = mutableSetOf<Any>() val map = WebSymbolsSearchMap(namesProvider, framework) initialize(map::add, dependencies) if (dependencies.isEmpty()) { throw IllegalArgumentException( "CacheDependencies cannot be empty. Add ModificationTracker.NEVER_CHANGED if cache should never be dropped.") } dependencies.add(namesProvider) CachedValueProvider.Result.create(map, dependencies.toList()) } protected open fun provides(namespace: SymbolNamespace, kind: SymbolKind): Boolean = true override fun getSymbols(namespace: SymbolNamespace?, kind: SymbolKind, name: String?, params: WebSymbolsNameMatchQueryParams, scope: Stack<WebSymbolsScope>): List<WebSymbolsScope> = if (namespace != null && (params.queryExecutor.allowResolve || !requiresResolve) && (framework == null || params.framework == framework) && provides(namespace, kind)) { getMap(params.queryExecutor).getSymbols(namespace, kind, name, params, Stack(scope)).toList() } else emptyList() override fun getCodeCompletions(namespace: SymbolNamespace?, kind: SymbolKind, name: String?, params: WebSymbolsCodeCompletionQueryParams, scope: Stack<WebSymbolsScope>): List<WebSymbolCodeCompletionItem> = if (namespace != null && (params.queryExecutor.allowResolve || !requiresResolve) && (framework == null || params.framework == framework) && provides(namespace, kind)) { getMap(params.queryExecutor).getCodeCompletions(namespace, kind, name, params, Stack(scope)).toList() } else emptyList() private fun getMap(queryExecutor: WebSymbolsQueryExecutor): WebSymbolsSearchMap = getNamesProviderToMapCache().getOrCreateMap(queryExecutor.namesProvider, this::createCachedSearchMap) private class NamesProviderToMapCache { private val cache: ConcurrentMap<WebSymbolNamesProvider, CachedValue<WebSymbolsSearchMap>> = ContainerUtil.createConcurrentSoftKeySoftValueMap() private var cacheMisses = 0 fun getOrCreateMap(namesProvider: WebSymbolNamesProvider, createCachedSearchMap: (namesProvider: WebSymbolNamesProvider) -> CachedValue<WebSymbolsSearchMap>): WebSymbolsSearchMap { if (cacheMisses > 20) { // Get rid of old soft keys cacheMisses = 0 cache.clear() } return cache.getOrPut(namesProvider) { cacheMisses++ createCachedSearchMap(namesProvider) }.value } } private class WebSymbolsSearchMap(namesProvider: WebSymbolNamesProvider, private val framework: FrameworkId?) : SearchMap<WebSymbol>(namesProvider) { override fun Sequence<WebSymbol>.mapAndFilter(params: WebSymbolsQueryParams): Sequence<WebSymbol> = this fun add(symbol: WebSymbol) { assert(symbol.origin.framework == framework) { "WebSymbolsScope only accepts symbols with framework: $framework, but symbol with framework ${symbol.origin.framework} was added." } add(symbol.namespace, symbol.kind, symbol.name, symbol.pattern, symbol) } } }
apache-2.0
24bfdb26a4cd1d5b9b81b73c44976858
43.913669
148
0.693207
5.344178
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/bolone/BoFrontFuns.kt
1
3870
package bolone import alraune.* import alraune.entity.* import bolone.rp.BiddingParamsFields import bolone.rp.BoloneRP_AssignWriter import bolone.rp.OrderFields import bolone.rp.OrderFileFields import bolone.test.Test_jsonizeForCallingFront import pieces100.* import vgrechka.* object BoFrontFuns { class InitOrderPageActionBanner( val orderHandle: JsonizableOrderHandle, val reloadURL: String, val actionBannerContainerDomid: String, val contentToRevealAfterInitDomid: String, val orderState: Order.State, val userKind: AlUserKind) : FrontFunction() { var adminTaskID: String? = null var adminTaskHref: String? = null var rejectionReason: String? = null var wasRejectionReason: String? = null var whatChangedHref: String? = null var biddingParamsShit: BiddingParamsShit? = null var bidding: Order.Bidding? = null var writerAssignmentShit: WriterAssignmentShit? = null } class WriterAssignmentShit( val nudgePaymentReminderTimeRange: JSLongRange, val fields: BoloneRP_AssignWriter.Fields) class BiddingParamsShit( val workDeadlineShownToWritersDuringBiddingRange: JSLongRange, val closeBiddingReminderTimeRange: JSLongRange, val fields: BiddingParamsFields) class JSLongRange(val min: JSLong, val max: JSLong) class InitOrderFilesPage( val editable: Boolean, val orderHandle: JsonizableOrderHandle, val bucket: String, val tabsTopRightContainerDomid: String, val reloadURL: String, val reloadToFirstPageURL: String, val storikanURL: String, val fileItems: List<FileItem>, val userKind: AlUserKind?) : FrontFunction() { class FileItem( val id: Long, val fields: OrderFileFields, var editTriggerDomid: String?, val rightIconsContainerDomid: String, val file: Order.File, val copiedTo: List<Order.File.Reference>) } class InitCreateOrderPage( val contentContainerDomid: String, val piece1: Piece1) : FrontFunction() class InitOrderParamsPage( val editable: Boolean, val orderHandle: JsonizableOrderHandle, val tabsTopRightContainerDomid: String, val reloadURL: String, val orderParamsFields: OrderFields, val piece1: Piece1) : FrontFunction() class Piece1( val documentTypes: List<SelectItem>, val rootDocumentCategory: JsonizableDocumentCategory, val deadlineMin: JSLong, val deadlineMax: JSLong) { companion object { fun make() = run { val fcr = orderDeadlineRange().toFrontCalendarRange() Piece1( documentTypes = Order.DocumentType.values().map {SelectItem(value = it.name, title = it.title)}, rootDocumentCategory = JsonizableDocumentCategory(AlUADocumentCategories.root), deadlineMin = fcr.min, deadlineMax = fcr.max) } } } class AddJSONMonacoBelowFooter( val title: String, val json: String) : FrontFunction() abstract class FrontFunction : Dancer<Unit> { override fun dance() { val jsFunctionName = this::class.simpleName!!.decapitalize() val jsArgs = jsonizeForCallingFront(this) btfEval(jsWhenDomReady("bolone.$jsFunctionName($jsArgs)")) } } @TestRefs(Test_jsonizeForCallingFront::class) fun jsonizeForCallingFront(x: Any, pretty: Boolean = false): String { val writer = Wilma.filteredWriter return when { pretty -> writer.withDefaultPrettyPrinter().writeValueAsString(x)!! else -> writer.writeValueAsString(x)!!} } }
apache-2.0
a85d6a7a104b001f3281c72e43f9e651
32.652174
116
0.655039
4.702309
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/callableReferences.0.kt
3
497
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter // OPTIONS: usages data class A(val <caret>a: Int, val b: Int) { fun f() {} } fun f1(): A = A(1, 2) class X { fun f2() = A(0, 0) } fun foo(x: X) { val fun1 = A::f val fun2 = ::f1 val fun3 = x::f2 val (a1, b1) = fun2() val (a2, b2) = fun3() val constructor = ::A val (a3, b3) = constructor(1, 2) val (a4, b4) = A::class.java.newInstance() } // FIR_IGNORE // FIR_COMPARISON_WITH_DISABLED_COMPONENTS
apache-2.0
2fb38e4b72ec4dd7f0ff6472580c0104
16.172414
52
0.555332
2.497487
false
false
false
false
LouisCAD/Splitties
modules/resources/src/androidMain/kotlin/splitties/resources/StyledAttributes.kt
1
2717
/* * Copyright 2019-2021 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NOTHING_TO_INLINE") package splitties.resources import android.content.Context import android.content.res.Resources import android.util.TypedValue import androidx.annotation.AnyRes import androidx.annotation.AttrRes import splitties.experimental.InternalSplittiesApi import splitties.mainthread.isMainThread @AnyRes fun Context.resolveThemeAttribute( @AttrRes attrRes: Int, resolveRefs: Boolean = true ): Int = if (isMainThread) { if (theme.resolveAttribute(attrRes, uiThreadConfinedCachedTypedValue, resolveRefs).not()) { throw Resources.NotFoundException( "Couldn't resolve attribute resource #0x" + Integer.toHexString(attrRes) + " from the theme of this Context." ) } uiThreadConfinedCachedTypedValue.resourceId } else synchronized(cachedTypeValue) { if (theme.resolveAttribute(attrRes, cachedTypeValue, resolveRefs).not()) { throw Resources.NotFoundException( "Couldn't resolve attribute resource #0x" + Integer.toHexString(attrRes) + " from the theme of this Context." ) } cachedTypeValue.resourceId } @InternalSplittiesApi inline fun <R> Context.withResolvedThemeAttribute( @AttrRes attrRes: Int, resolveRefs: Boolean = true, crossinline block: TypedValue.() -> R ): R = if (isMainThread) { if (theme.resolveAttribute(attrRes, uiThreadConfinedCachedTypedValue, resolveRefs).not()) { throw Resources.NotFoundException( "Couldn't resolve attribute resource #0x" + Integer.toHexString(attrRes) + " from the theme of this Context." ) } block(uiThreadConfinedCachedTypedValue) } else synchronized(cachedTypeValue) { if (theme.resolveAttribute(attrRes, cachedTypeValue, resolveRefs).not()) { throw Resources.NotFoundException( "Couldn't resolve attribute resource #0x" + Integer.toHexString(attrRes) + " from the theme of this Context." ) } block(cachedTypeValue) } @PublishedApi @JvmField internal val uiThreadConfinedCachedTypedValue = TypedValue() @PublishedApi @JvmField internal val cachedTypeValue = TypedValue() internal fun TypedValue.unexpectedThemeAttributeTypeErrorMessage(expectedKind: String): String { val article = when (expectedKind.firstOrNull() ?: ' ') { in "aeio" -> "an" else -> "a" } return "Expected $article $expectedKind theme attribute but got type 0x${type.toString(16)} " + "(see what it corresponds to in android.util.TypedValue constants)" }
apache-2.0
422a238e5a654f5f38adca4dcb27e9dc
36.736111
114
0.704085
4.758319
false
false
false
false
NlRVANA/Unity
app/src/main/java/com/zwq65/unity/ui/activity/MainActivity.kt
1
5895
/* * Copyright [2017] [NIRVANA PRIVATE LIMITED] * * 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.zwq65.unity.ui.activity import android.content.Intent import android.view.View import androidx.appcompat.app.ActionBarDrawerToggle import androidx.core.view.GravityCompat import com.jakewharton.rxbinding2.view.RxView import com.zwq65.unity.ui._base.BaseDaggerActivity import com.zwq65.unity.ui._base.BaseFragment import com.zwq65.unity.ui.contract.MainContract import com.zwq65.unity.ui.fragment.AlbumFragment import com.zwq65.unity.ui.fragment.ArticleFragment import com.zwq65.unity.ui.fragment.RestVideoFragment import com.zwq65.unity.ui.fragment.TestFragment import com.zwq65.unity.utils.loadCircle import com.zwq65.unity.utils.setCustomDensity import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.drawer_left.* import java.util.concurrent.TimeUnit /** * ================================================ * 首页[BaseDaggerActivity] * * Created by NIRVANA on 2017/06/29. * Contact with <[email protected]> * ================================================ */ class MainActivity : BaseDaggerActivity<MainContract.View, MainContract.Presenter<MainContract.View>>(), MainContract.View, View.OnClickListener { private var disposable: Disposable? = null override val layoutId: Int get() = com.zwq65.unity.R.layout.activity_main private var firstClick: Long = 0 override fun initBaseTooBar(): Boolean { return true } override fun dealIntent(intent: Intent) { } override fun initView() { //屏幕适配方案 setCustomDensity(this, application, 375.0f) //将drawerLayout、toolBar绑定 val toggle = ActionBarDrawerToggle( this, drawer_layout, toolbar, com.zwq65.unity.R.string.navigation_drawer_open, com.zwq65.unity.R.string.navigation_drawer_close) drawer_layout?.addDrawerListener(toggle) toggle.syncState() addToolbarDoubleClick() iv_avatar?.setOnClickListener(this) iv_avatar?.loadCircle(com.zwq65.unity.R.mipmap.ic_avatar) tv_account_name?.setOnClickListener(this) ll_welfare?.setOnClickListener(this) ll_news?.setOnClickListener(this) ll_video?.setOnClickListener(this) ll_setting?.setOnClickListener(this) ll_out?.setOnClickListener(this) //默认跳转 gotoFragment(AlbumFragment()) } override fun initData() { } override fun onBackPressed() { if (drawer_layout?.isDrawerOpen(GravityCompat.START)!!) { drawer_layout?.closeDrawer(GravityCompat.START) } else { //双击退出app if (System.currentTimeMillis() - firstClick > DELAY_TIME_FINISH) { firstClick = System.currentTimeMillis() showMessage(com.zwq65.unity.R.string.str_finish_if_press_again) } else { super.onBackPressed() } } } override fun onClick(v: View?) { drawer_layout?.closeDrawer(GravityCompat.START) when (v?.id) { com.zwq65.unity.R.id.iv_avatar, com.zwq65.unity.R.id.tv_account_name -> //个人中心 openActivity(AccountActivity::class.java) com.zwq65.unity.R.id.ll_welfare -> //福利图集 gotoFragment(AlbumFragment()) com.zwq65.unity.R.id.ll_news -> //技术文章 gotoFragment(ArticleFragment()) com.zwq65.unity.R.id.ll_video -> //休息视频 gotoFragment(RestVideoFragment()) com.zwq65.unity.R.id.ll_setting -> gotoFragment(TestFragment()) com.zwq65.unity.R.id.ll_out -> onBackPressed() else -> { } } } /** * 添加toolBar双击监听事件 */ private fun addToolbarDoubleClick() { //buffer: 定期收集Observable的数据放进一个数据包裹,然后发射这些数据包裹,而不是一次发射一个值 //判断500ms内,如果接受到2次的点击事件,则视为用户双击操作 if (toolbar != null) { disposable = RxView.clicks(toolbar!!).buffer(500, TimeUnit.MILLISECONDS, 2).subscribe { objects -> val clickNum = 2 if (objects.size == clickNum) { val fragmentManager = supportFragmentManager val fragmentList = fragmentManager.fragments if (fragmentList.size > 0) { fragmentList .filter { it.isVisible } .filterIsInstance<BaseFragment<*, *>>() .forEach { it.onToolbarClick() } } } } } } private fun gotoFragment(fragment: BaseFragment<*, *>) { switchFragment(com.zwq65.unity.R.id.fl_main, fragment, fragment.javaClass.simpleName) } override fun onDestroy() { super.onDestroy() disposable?.dispose() } companion object { /** * 退出app延时时间 */ const val DELAY_TIME_FINISH = 2000 } }
apache-2.0
589618e6e80126ab5120d94a517cc747
32.958084
146
0.615412
4.305998
false
false
false
false
testIT-LivingDoc/livingdoc2
livingdoc-engine/src/jmh/kotlin/org/livingdoc/engine/execution/examples/decisiontables/AdditionDecisionTableBenchmarks.kt
2
2568
package org.livingdoc.engine.execution.examples.decisiontables import org.assertj.core.api.Assertions import org.livingdoc.api.fixtures.decisiontables.Check import org.livingdoc.api.fixtures.decisiontables.DecisionTableFixture import org.livingdoc.api.fixtures.decisiontables.Input import org.livingdoc.repositories.model.decisiontable.DecisionTable import org.livingdoc.repositories.model.decisiontable.Field import org.livingdoc.repositories.model.decisiontable.Header import org.livingdoc.repositories.model.decisiontable.Row import org.livingdoc.results.examples.decisiontables.DecisionTableResult import org.openjdk.jmh.annotations.Benchmark import org.openjdk.jmh.annotations.Level import org.openjdk.jmh.annotations.Param import org.openjdk.jmh.annotations.Scope import org.openjdk.jmh.annotations.Setup import org.openjdk.jmh.annotations.State import kotlin.random.Random @State(Scope.Thread) open class AdditionDecisionTableBenchmarks { lateinit var table: DecisionTable @Param("1", "10", "100", "1000", "10000", "100000", "1000000") var tableSize: Int = 0 @Setup(Level.Iteration) fun generateRandomAdditionTable() { val headers = listOf(Header("a"), Header("b"), Header("a + b = ?")) val rows = (0 until tableSize).map { val a = Random.nextLong(Long.MAX_VALUE) val b = Random.nextLong(Long.MAX_VALUE - a) val result = a + b Row( mapOf( headers[0] to Field(a.toString()), headers[1] to Field(b.toString()), headers[2] to Field(result.toString()) ) ) } table = DecisionTable(headers, rows) } @Benchmark fun sequentialAddition(): DecisionTableResult { return DecisionTableFixtureWrapper(SequentialAddition::class.java).execute(table) } @Benchmark fun parallelAddition(): DecisionTableResult { return DecisionTableFixtureWrapper(ParallelAddition::class.java).execute(table) } } @DecisionTableFixture class SequentialAddition { @Input("a") var a: Long = 0 @Input("b") var b: Long = 0 @Check("a + b = ?") fun `sum is correct`(expected: Long) { Assertions.assertThat(a + b).isEqualTo(expected) } } @DecisionTableFixture(parallel = true) class ParallelAddition { @Input("a") var a: Long = 0 @Input("b") var b: Long = 0 @Check("a + b = ?") fun `sum is correct`(expected: Long) { Assertions.assertThat(a + b).isEqualTo(expected) } }
apache-2.0
b70a55c84e1c9a036dfb4d026d3e044c
29.211765
89
0.678738
4.189233
false
false
false
false
marverenic/Paper
app/src/main/java/com/marverenic/reader/ui/home/all/AllArticlesFragment.kt
1
3866
package com.marverenic.reader.ui.home.all import android.databinding.DataBindingUtil import android.os.Bundle import android.view.* import com.marverenic.reader.R import com.marverenic.reader.ReaderApplication import com.marverenic.reader.data.RssStore import com.marverenic.reader.databinding.FragmentAllArticlesBinding import com.marverenic.reader.ui.home.HomeFragment import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import javax.inject.Inject private const val EXTRA_UNREAD_ONLY = "unread_only" class AllArticlesFragment : HomeFragment() { @Inject lateinit var rssStore: RssStore lateinit var binding: FragmentAllArticlesBinding override val title: String get() = getString(R.string.all_articles_header) private var unreadOnly: Boolean = false private var streamSubscription: Disposable? = null companion object { fun newInstance() = AllArticlesFragment() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.let { unreadOnly = it.getBoolean(EXTRA_UNREAD_ONLY, false) } ReaderApplication.component(this).inject(this) setHasOptionsMenu(true) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(EXTRA_UNREAD_ONLY, unreadOnly) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_all_articles, container, false) val viewModel = AllArticlesViewModel(context, streamTitle = title, readCallback = { rssStore.markAsRead(it) }, fetchCallback = { rssStore.loadMoreArticles(it) }) binding.viewModel = viewModel loadArticles(viewModel) return binding.root } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.article_list, menu) menu.findItem(R.id.menu_item_show_all).isVisible = unreadOnly menu.findItem(R.id.menu_item_filter_unread).isVisible = !unreadOnly } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_item_show_all -> filterUnreadArticles(false) R.id.menu_item_filter_unread -> filterUnreadArticles(true) else -> return super.onOptionsItemSelected(item) } return true } private fun loadArticles(viewModel: AllArticlesViewModel) { streamSubscription?.dispose() streamSubscription = rssStore.getAllArticles(unreadOnly) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle()) .subscribe({ stream -> viewModel.stream = stream viewModel.refreshing = false setupRefreshListener(viewModel) }) } private fun setupRefreshListener(viewModel: AllArticlesViewModel) { viewModel.getRefreshObservable() .distinctUntilChanged() .subscribe({ refreshing -> if (refreshing) { rssStore.refreshAllArticles() } }) } private fun filterUnreadArticles(hideReadArticles: Boolean) { if (unreadOnly != hideReadArticles) { unreadOnly = hideReadArticles loadArticles(binding.viewModel ?: throw IllegalStateException("View model is not set")) activity.invalidateOptionsMenu() } } }
apache-2.0
5afdd9ace65d77baa61c5dab8e957827
33.837838
115
0.668132
5.12053
false
false
false
false
prof18/RSS-Parser
rssparser/src/main/java/com/prof/rssparser/Image.kt
1
846
package com.prof.rssparser import java.io.Serializable data class Image( val title: String?, val url: String?, val link: String?, val description: String? ) : Serializable { fun isNotEmpty(): Boolean { return !url.isNullOrBlank() || !link.isNullOrBlank() } internal data class Builder( private var title: String? = null, private var url: String? = null, private var link: String? = null, private var description: String? = null ) { fun title(title: String?) = apply { this.title = title } fun url(url: String?) = apply { this.url = url } fun link(link: String?) = apply { this.link = link } fun description(description: String?) = apply { this.description = description } fun build() = Image(title, url, link, description) } }
apache-2.0
5abca3ec657917ad896cf811b4bf6424
29.25
88
0.612293
4.086957
false
false
false
false
busybusy/AnalyticsKit-Android
flurry-provider/src/main/kotlin/flurry_provider/FlurryProvider.kt
2
3810
/* * Copyright 2016 - 2022 busybusy, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.busybusy.flurry_provider import com.busybusy.analyticskit_android.AnalyticsKitProvider.PriorityFilter import com.busybusy.analyticskit_android.AnalyticsKitProvider import com.busybusy.analyticskit_android.AnalyticsEvent import com.flurry.android.FlurryAgent /** * Implements Flurry as a provider to use with [com.busybusy.analyticskit_android.AnalyticsKit] * * * **Important**: It is a violation of Flurry’s TOS to record personally identifiable information such as a user’s UDID, * email address, and so on using Flurry. If you have a user login that you wish to associate with your session and * event data, you should use the SetUserID function. If you do choose to record a user id of any type within a parameter, * you must anonymize the data using a hashing function such as MD5 or SHA256 prior to calling the method. * * * Refer to the Flurry documentation here: * [Flurry Documentation](https://developer.yahoo.com/flurry/docs/analytics/gettingstarted/events/android/) * * @author John Hunt on 3/21/16. */ class FlurryProvider( private val priorityFilter: PriorityFilter = PriorityFilter { true }, ) : AnalyticsKitProvider { /** * Returns the filter used to restrict events by priority. * * @return the [PriorityFilter] instance the provider is using to determine if an * event of a given priority should be logged */ override fun getPriorityFilter(): PriorityFilter = priorityFilter /** * Sends the event using provider-specific code. * * @param event an instantiated event */ @Throws(IllegalStateException::class) override fun sendEvent(event: AnalyticsEvent) { val eventParams: Map<String, String>? = stringifyParameters(event.attributes) if (event.isTimed()) { // start the Flurry SDK event timer for the event when (eventParams) { null -> FlurryAgent.logEvent(event.name(), true) else -> FlurryAgent.logEvent(event.name(), eventParams, true) } } else { when (eventParams) { null -> FlurryAgent.logEvent(event.name()) else -> FlurryAgent.logEvent(event.name(), eventParams) } } } /** * End the timed event. * * @param timedEvent the event which has finished */ override fun endTimedEvent(timedEvent: AnalyticsEvent) { FlurryAgent.endTimedEvent(timedEvent.name()) } /** * Converts a `Map<String, Any>` to `Map<String, String>` * @param attributes the map of attributes attached to the event * @return the String map of parameters. Returns `null` if no parameters are attached to the event. */ @Throws(IllegalStateException::class) fun stringifyParameters(attributes: Map<String, Any>?): Map<String, String>? { check((attributes?.size ?: 0) <= ATTRIBUTE_LIMIT) { "Flurry events are limited to $ATTRIBUTE_LIMIT attributes" } return attributes?.map { (key, value) -> key to value.toString() } ?.takeIf { it.isNotEmpty() } ?.toMap() } } internal const val ATTRIBUTE_LIMIT = 10
apache-2.0
30d935d3cfe53a18afc7fdaee0df9d29
37.836735
122
0.678665
4.435897
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/data/BaseRepository.kt
1
2673
package ch.rmy.android.framework.data import ch.rmy.android.framework.extensions.detachFromRealm import io.realm.Realm import io.realm.RealmList import io.realm.RealmModel import io.realm.RealmQuery import io.realm.kotlin.toFlow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.ProducerScope import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext abstract class BaseRepository(private val realmFactory: RealmFactory) { protected suspend fun <T : RealmModel> query(query: RealmContext.() -> RealmQuery<T>): List<T> = withContext(Dispatchers.IO) { realmFactory.createRealm().use { realm -> query(realm.createContext()) .findAll() .detachFromRealm() } } protected suspend fun <T : RealmModel> queryItem(query: RealmContext.() -> RealmQuery<T>): T = query(query).first() protected fun <T : RealmModel> observeQuery(query: RealmContext.() -> RealmQuery<T>): Flow<List<T>> = channelFlow { withRealmContext(realmFactory) { query() .findAllAsync() .toFlow() .collect(channel::send) } } protected fun <T : RealmModel> observeList(query: RealmContext.() -> RealmList<T>): Flow<List<T>> = channelFlow { withRealmContext(realmFactory) { query() .toFlow() .collect(channel::send) } } private suspend fun ProducerScope<*>.withRealmContext(realmFactory: RealmFactory, block: suspend RealmContext.() -> Unit) { var realm: Realm withContext(Dispatchers.Main) { // TODO: Check if this could be done on a different thread (which has a looper) realm = realmFactory.createRealm() realm.createContext().block() } awaitClose(realm::close) } protected fun <T : RealmModel> observeItem(query: RealmContext.() -> RealmQuery<T>): Flow<T> = observeQuery(query) .filter { it.isNotEmpty() } .map { it.first() } protected suspend fun commitTransaction(transaction: RealmTransactionContext.() -> Unit) { withContext(Dispatchers.IO) { realmFactory.createRealm().use { realm -> realm.executeTransaction { transaction(realm.createTransactionContext()) } } } } }
mit
f0df6220ca4f7827e18e460a8b39f72e
35.121622
127
0.618406
4.895604
false
false
false
false
vicpinm/KPresenterAdapter
sample/src/main/java/com/vicpin/sample/view/fragment/MultiBindingFragment.kt
1
3305
package com.vicpin.sample.view.fragment import android.os.Bundle import android.os.Handler import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import com.vicpin.kpresenteradapter.extensions.inflate import com.vicpin.sample.R import com.vicpin.sample.data.MixedRepository import com.vicpin.sample.extensions.finishIdlingResource import com.vicpin.sample.extensions.showToast import com.vicpin.sample.extensions.startIdlingResource import com.vicpin.sample.model.Country import com.vicpin.sample.model.IRepository import com.vicpin.sample.model.NamedItem import com.vicpin.sample.view.adapter.MultiBindingAdapter import com.vicpin.sample.view.interfaces.ItemDeletedListener import com.vicpin.sample.view.interfaces.ItemRecycledListener import kotlinx.android.synthetic.main.fragment_main.* /** * Created by Victor on 25/06/2016. */ class MultiBindingFragment : Fragment(), ItemRecycledListener, ItemDeletedListener<Country> { private var lastPresentersRecycled: Int = 0 private var currentPage: Int = 0 private lateinit var adapter: MultiBindingAdapter private var isSingleAdapter = false private lateinit var repository: IRepository<NamedItem> override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = container?.inflate(R.layout.fragment_main) override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) this.repository = MixedRepository(context) initView() } private fun initView(){ setupAdapter() appendListeners() setupRecyclerView() loadFirstData() } private fun setupAdapter() { adapter = MultiBindingAdapter() adapter.notifyScrollStatus(recycler) adapter.enableLoadMore { onLoadMore() } } private fun appendListeners() { adapter.apply { itemClickListener = { item, view -> showToast(getString(R.string.item_toast_message,item.name)) } customListener = this@MultiBindingFragment } } private fun setupRecyclerView() { recycler.layoutManager = LinearLayoutManager(activity) recycler.adapter = adapter } private fun loadFirstData() { val data = repository.getItemsPage(0) adapter.setData(data) } override fun onItemRecycled(presenterId: Int) { lastPresenterDestroyed.text = "Last presenters recycled: $lastPresentersRecycled - $presenterId" lastPresentersRecycled = presenterId } /** * Pagination listener. Simulates a 1500ms load delay. */ private fun onLoadMore() { startIdlingResource() Handler().postDelayed({ currentPage++ val newData = repository.getItemsPage(currentPage) if (newData.isNotEmpty()) { adapter.addData(newData) } else { adapter.disableLoadMore() } finishIdlingResource() }, 1500) } override fun onItemDeleted(item: Country) { adapter.updateHeaders() } fun toggleAdapter() { isSingleAdapter = !isSingleAdapter initView() } }
apache-2.0
7b31c05800d0a4c862ccba21988b7d36
30.47619
152
0.706505
4.896296
false
false
false
false
drmashu/koshop
src/main/kotlin/io/github/drmashu/koshop/Koshop.kt
1
5625
package io.github.drmashu.koshop import io.github.drmashu.buri.Buri import io.github.drmashu.buri.BuriRunner import io.github.drmashu.buri.TemplateHolder import io.github.drmashu.dikon.* import io.github.drmashu.koshop.action.ItemAction import io.github.drmashu.koshop.action.ItemImgAction import io.github.drmashu.koshop.action.SearchAction import io.github.drmashu.koshop.action.manage.* import org.apache.logging.log4j.LogManager import org.seasar.doma.jdbc.Config import org.seasar.doma.jdbc.UtilLoggingJdbcLogger import org.seasar.doma.jdbc.dialect.Dialect import org.seasar.doma.jdbc.dialect.H2Dialect import org.seasar.doma.jdbc.tx.LocalTransactionDataSource import org.seasar.doma.jdbc.tx.LocalTransactionManager import org.seasar.doma.jdbc.tx.TransactionManager import java.util.logging.Level import javax.sql.DataSource val mainLogger = LogManager.getLogger("KoshopMain") /** * Created by drmashu on 2015/10/07. */ fun main(args: Array<String>){ mainLogger.entry() BuriRunner(Koshop()).start(8080) mainLogger.exit() } public class Koshop() : Buri() { val datasource = LocalTransactionDataSource("jdbc:h2:file:./db/koshop;CIPHER=AES", "sa", "password password") val diarect = H2Dialect() val jdbcLogger = UtilLoggingJdbcLogger(Level.FINE) val transactionManager: LocalTransactionManager = LocalTransactionManager( datasource.getLocalTransaction(jdbcLogger)) init { val tran = datasource.getLocalTransaction(jdbcLogger) tran.begin() val conn = datasource.connection conn.createStatement().execute(""" CREATE TABLE IF NOT EXISTS account ( id INT NOT NULL PRIMARY KEY, mail NVARCHAR2(256) NOT NULL UNIQUE, name NVARCHAR2(100) NOT NULL, password NVARCHAR2(20), gauth BOOL, role INT ); """) conn.createStatement().execute(""" CREATE TABLE IF NOT EXISTS totp ( id INT NOT NULL PRIMARY KEY, key NVARCHAR2(1024) NOT NULL ); """) conn.createStatement().execute(""" CREATE TABLE IF NOT EXISTS customer ( id INT NOT NULL PRIMARY KEY, postal_code NVARCHAR2(10), address NVARCHAR2(100), phone NVARCHAR2(20) ); """) conn.createStatement().execute(""" CREATE TABLE IF NOT EXISTS item ( id NVARCHAR2(20) NOT NULL PRIMARY KEY, name NVARCHAR2(100) NOT NULL, price INT NOT NULL, description NVARCHAR2(1024) ); """) conn.createStatement().execute(""" CREATE TABLE IF NOT EXISTS items ( uid NVARCHAR2(256) NOT NULL, item_id NVARCHAR2(20) NOT NULL, count INT NOT NULL, PRIMARY KEY (uid, item_id) ); """) conn.createStatement().execute(""" CREATE TABLE IF NOT EXISTS item_image ( item_id NVARCHAR2(20) NOT NULL, `index` TINYINT NOT NULL, image IMAGE, contentType VARCHAR2(256), PRIMARY KEY (item_id, `index`) ); """) tran.commit() conn.close() } override val config: Map<String, Factory<*>> get() { return mapOf( "doma_config" to Holder(object: Config { override fun getDataSource(): DataSource? = datasource override fun getDialect(): Dialect? = diarect override fun getTransactionManager(): TransactionManager? = transactionManager }), "itemDao" to Injection(getKClassForName("io.github.drmashu.koshop.dao.ItemDaoImpl")), "itemsDao" to Injection(getKClassForName("io.github.drmashu.koshop.dao.ItemsDaoImpl")), "itemImageDao" to Injection(getKClassForName("io.github.drmashu.koshop.dao.ItemImageDaoImpl")), "accountDao" to Injection(getKClassForName("io.github.drmashu.koshop.dao.AccountDaoImpl")), "totpDao" to Injection(getKClassForName("io.github.drmashu.koshop.dao.TotpDaoImpl")), "koshop_config" to Holder(KoshopConfig( title = "KoshopSample", description = """ Koshopのサンプルです。 """ )), "authenticate_location" to Holder("/login"), "/" to TemplateHolder("/index", arrayOf("koshop_config")), "/search/(?<keyword>.*)" to Injection(SearchAction::class), "/manage/" to Injection(ManageLoginAction::class), "/manage/login" to Injection(ManageLoginAction::class), "/manage/accounts" to Injection(ManageAccountListAction::class), "/manage/account/(?<id>[0-9]+)" to Injection(ManageAccountAction::class), "/manage/items" to Injection(ManageItemListAction::class), "/manage/item/(?<id>[A-Za-z0-9]{20})" to Injection(ManageItemAction::class), "/itemImg/(?<id>[A-Za-z0-9]{20})/(?<index>[0-9]+)" to Injection(ItemImgAction::class), "/items" to Injection(ItemListAction::class), "/item/(?<id>[A-Za-z0-9]{20})" to Injection(ItemAction::class) ) } } class KoshopConfig(val title: String, val description: String)
apache-2.0
e1f3435126846857ed86382c83f63640
42.820313
115
0.587449
4.516103
false
true
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/usecase/UseCaseRunner.kt
1
1778
package com.orgzly.android.usecase import com.orgzly.BuildConfig import com.orgzly.android.App import com.orgzly.android.data.DataRepository import com.orgzly.android.reminders.RemindersScheduler import com.orgzly.android.sync.AutoSync import com.orgzly.android.SharingShortcutsManager import com.orgzly.android.util.LogUtils import com.orgzly.android.widgets.ListWidgetProvider import javax.inject.Inject object UseCaseRunner { private val TAG = UseCaseRunner::class.java.name // FIXME: Make UserActionRunner a class class Factory { @Inject lateinit var autoSync: AutoSync @Inject lateinit var dataRepository: DataRepository init { App.appComponent.inject(this) } } @JvmStatic fun run(action: UseCase): UseCaseResult { val startedAt = System.currentTimeMillis() val factory = Factory() val result = action.run(factory.dataRepository) when (result.triggersSync) { UseCase.SYNC_DATA_MODIFIED -> factory.autoSync.trigger(AutoSync.Type.DATA_MODIFIED) UseCase.SYNC_NOTE_CREATED -> factory.autoSync.trigger(AutoSync.Type.NOTE_CREATED) } if (result.modifiesLocalData) { RemindersScheduler.notifyDataSetChanged(App.getAppContext()) ListWidgetProvider.notifyDataSetChanged(App.getAppContext()) SharingShortcutsManager().replaceDynamicShortcuts(App.getAppContext()) } if (result.modifiesListWidget) { ListWidgetProvider.update(App.getAppContext()) } if (BuildConfig.LOG_DEBUG) { val ms = System.currentTimeMillis() - startedAt LogUtils.d(TAG, "Finished $action in ${ms}ms") } return result } }
gpl-3.0
b83b68c98009e9f7969b17e6fee3412a
28.65
95
0.68279
4.754011
false
false
false
false
samthor/intellij-community
plugins/settings-repository/src/copyAppSettingsToRepository.kt
13
3286
/* * 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 org.jetbrains.settingsRepository import com.intellij.configurationStore.StateStorageManagerImpl import com.intellij.ide.actions.ExportSettingsAction import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import java.io.File fun copyLocalConfig() { val storageManager = ApplicationManager.getApplication()!!.stateStore.getStateStorageManager() as StateStorageManagerImpl val streamProvider = storageManager.streamProvider!! as IcsManager.IcsStreamProvider val fileToComponents = ExportSettingsAction.getExportableComponentsMap(true, false) for (file in fileToComponents.keySet()) { val absolutePath = FileUtilRt.toSystemIndependentName(file.getAbsolutePath()) var fileSpec = storageManager.collapseMacros(absolutePath) if (fileSpec.equals(absolutePath)) { // we have not experienced such problem yet, but we are just aware val canonicalPath = FileUtilRt.toSystemIndependentName(file.getCanonicalPath()) if (!canonicalPath.equals(absolutePath)) { fileSpec = storageManager.collapseMacros(canonicalPath) } } val roamingType = getRoamingType(fileToComponents.get(file)) if (file.isFile()) { val fileBytes = FileUtil.loadFileBytes(file) streamProvider.doSave(fileSpec, fileBytes, fileBytes.size(), roamingType) } else { saveDirectory(file, fileSpec, roamingType, streamProvider) } } } private fun saveDirectory(parent: File, parentFileSpec: String, roamingType: RoamingType, streamProvider: IcsManager.IcsStreamProvider) { val files = parent.listFiles() if (files != null) { for (file in files) { val childFileSpec = parentFileSpec + '/' + file.getName() if (file.isFile()) { val fileBytes = FileUtil.loadFileBytes(file) streamProvider.doSave(childFileSpec, fileBytes, fileBytes.size(), roamingType) } else { saveDirectory(file, childFileSpec, roamingType, streamProvider) } } } } private fun getRoamingType(components: Collection<ExportableComponent>): RoamingType { for (component in components) { if (component is ExportSettingsAction.ExportableComponentItem) { return component.getRoamingType() } else if (component is PersistentStateComponent<*>) { val stateAnnotation = component.javaClass.getAnnotation(javaClass<State>()) if (stateAnnotation != null) { val storages = stateAnnotation.storages if (!storages.isEmpty()) { return storages[0].roamingType } } } } return RoamingType.DEFAULT }
apache-2.0
d659cb3f20bab2d6be46116b1ba3b4b1
37.670588
137
0.737066
4.956259
false
false
false
false
kamgurgul/cpu-info
app/src/main/java/com/kgurgul/cpuinfo/di/modules/AppModule.kt
1
4014
/* * Copyright 2017 KG Soft * * 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.kgurgul.cpuinfo.di.modules import android.annotation.SuppressLint import android.app.ActivityManager import android.app.admin.DevicePolicyManager import android.content.ContentResolver import android.content.Context import android.content.SharedPreferences import android.content.pm.PackageManager import android.content.res.Resources import android.hardware.SensorManager import android.net.wifi.WifiManager import android.os.storage.StorageManager import android.view.WindowManager import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile import androidx.preference.PreferenceManager import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton /** * Module which can provide all singletons * * @author kgurgul */ @Module @InstallIn(SingletonComponent::class) class AppModule { @Provides @Singleton fun provideResources(@ApplicationContext appContext: Context): Resources = appContext.resources @Provides @Singleton fun provideActivityManager(@ApplicationContext appContext: Context): ActivityManager = appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager @Provides @Singleton fun provideDevicePolicyManager(@ApplicationContext appContext: Context): DevicePolicyManager = appContext.getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager @Provides @Singleton fun providePackageManager(@ApplicationContext appContext: Context): PackageManager = appContext.packageManager @Provides @Singleton fun provideContentResolver(@ApplicationContext appContext: Context): ContentResolver = appContext.contentResolver @Provides @Singleton fun provideWindowManager(@ApplicationContext appContext: Context): WindowManager = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager @Provides @Singleton fun provideSensorManager(@ApplicationContext appContext: Context): SensorManager = appContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager @SuppressLint("WifiManagerPotentialLeak") @Provides @Singleton fun provideWifiManager(@ApplicationContext appContext: Context): WifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager @Provides @Singleton fun provideSharedPreferences(@ApplicationContext appContext: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(appContext) @Provides @Singleton fun provideStorageManager(@ApplicationContext appContext: Context): StorageManager = appContext.getSystemService(Context.STORAGE_SERVICE) as StorageManager @Provides @Singleton fun providePreferencesDataStore(@ApplicationContext appContext: Context): DataStore<Preferences> = PreferenceDataStoreFactory.create( produceFile = { appContext.preferencesDataStoreFile(USER_PREFERENCES_NAME) } ) companion object { const val USER_PREFERENCES_NAME = "user_preferences" } }
apache-2.0
d1abed931b5d997d00773d8628277057
33.913043
102
0.7713
5.506173
false
false
false
false
Stargamers/FastHub
app/src/main/java/com/fastaccess/ui/modules/trending/fragment/TrendingFragment.kt
6
2886
package com.fastaccess.ui.modules.trending.fragment import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.view.View import butterknife.BindView import com.evernote.android.state.State import com.fastaccess.R import com.fastaccess.data.dao.TrendingModel import com.fastaccess.ui.adapter.TrendingAdapter import com.fastaccess.ui.base.BaseFragment import com.fastaccess.ui.widgets.StateLayout import com.fastaccess.ui.widgets.recyclerview.DynamicRecyclerView import com.fastaccess.ui.widgets.recyclerview.scroll.RecyclerViewFastScroller /** * Created by Kosh on 30 May 2017, 11:37 PM */ class TrendingFragment : BaseFragment<TrendingFragmentMvp.View, TrendingFragmentPresenter>(), TrendingFragmentMvp.View { @BindView(R.id.recycler) lateinit var recycler: DynamicRecyclerView @BindView(R.id.refresh) lateinit var refresh: SwipeRefreshLayout @BindView(R.id.stateLayout) lateinit var stateLayout: StateLayout @BindView(R.id.fastScroller) lateinit var fastScroller: RecyclerViewFastScroller private val adapter by lazy { TrendingAdapter(presenter.getTendingList()) } @State var lang: String = "" @State var since: String = "" override fun providePresenter(): TrendingFragmentPresenter = TrendingFragmentPresenter() override fun fragmentLayout(): Int = R.layout.small_grid_refresh_list override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { stateLayout.setEmptyText(R.string.no_trending) recycler.setEmptyView(stateLayout, refresh) refresh.setOnRefreshListener { onCallApi() } stateLayout.setOnReloadListener { onCallApi() } adapter.listener = presenter recycler.adapter = adapter fastScroller.attachRecyclerView(recycler) } override fun onNotifyAdapter(items: TrendingModel) { adapter.addItem(items) } override fun onSetQuery(lang: String, since: String) { this.lang = lang this.since = since adapter.clear() presenter.onCallApi(lang, since) } override fun showProgress(resId: Int) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.hideProgress() stateLayout.showReload(adapter.itemCount) } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun showMessage(titleRes: String, msgRes: String) { hideProgress() super.showMessage(titleRes, msgRes) } override fun showErrorMessage(msgRes: String) { hideProgress() super.showErrorMessage(msgRes) } private fun onCallApi() { presenter.onCallApi(lang, since) } override fun clearAdapter() { adapter.clear() } }
gpl-3.0
7a196e2435c26acafb7e785d97f182fb
31.077778
120
0.72176
4.731148
false
false
false
false
pchrysa/Memento-Calendar
android_mobile/src/main/java/com/alexstyl/specialdates/upcoming/widget/list/WidgetRouterActivity.kt
1
2811
package com.alexstyl.specialdates.upcoming.widget.list import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import com.alexstyl.specialdates.MementoApplication import com.alexstyl.specialdates.contact.Contact import com.alexstyl.specialdates.contact.ContactsProvider import com.alexstyl.specialdates.date.Date import com.alexstyl.specialdates.date.getDateExtraOrThrow import com.alexstyl.specialdates.date.putExtraDate import com.alexstyl.specialdates.events.namedays.activity.NamedayActivity import com.alexstyl.specialdates.person.PersonActivity import com.alexstyl.specialdates.upcoming.UpcomingEventsActivity import javax.inject.Inject private val ACTION_VIEW_NAMEDAY = "action:view_nameday" private val ACTION_VIEW_CONTACT = "action:view_contact" private val EXTRA_CNTACT_ID = "extra:contact_id" private val EXTRA_CONTACT_SOURCE = "extra:contact_source" class WidgetRouterActivity : Activity() { @Inject lateinit var contactsProvider: ContactsProvider override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val applicationModule = (application as MementoApplication).applicationModule applicationModule.inject(this) val startIntent = routeIntent(intent, this) startActivity(startIntent) finish() } companion object { fun buildIntent(context: Context): Intent = Intent(context, WidgetRouterActivity::class.java) fun buildContactIntent(context: Context, contact: Contact): Intent = Intent(context, WidgetRouterActivity::class.java) .apply { action = ACTION_VIEW_CONTACT putExtra(EXTRA_CNTACT_ID, contact.contactID) putExtra(EXTRA_CONTACT_SOURCE, contact.source) } fun buildNamedayIntent(date: Date, context: Context): Intent = Intent(context, WidgetRouterActivity::class.java) .apply { action = ACTION_VIEW_NAMEDAY putExtraDate(date) } } fun routeIntent(intent: Intent, context: Context): Intent = when (intent.action) { ACTION_VIEW_CONTACT -> PersonActivity.buildIntentFor(context, intent.contact()) ACTION_VIEW_NAMEDAY -> NamedayActivity.getStartIntent(context, intent.getDateExtraOrThrow()) else -> { UpcomingEventsActivity.getStartIntent(this) } } private fun Intent.contact(): Contact { val contactId = getLongExtra(EXTRA_CNTACT_ID, -1) val source = getIntExtra(EXTRA_CONTACT_SOURCE, -1) return contactsProvider.getContact(contactId, source) } }
mit
608b929e81d658bfb33ded1bf680b394
35.506494
101
0.688723
4.764407
false
false
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/misc/AndroidHelpers.kt
1
844
package fr.geobert.efficio.misc import android.appwidget.AppWidgetManager import android.content.* import fr.geobert.efficio.widget.TaskListWidget inline fun consume(f: () -> Unit): Boolean { f() return true } fun updateWidgets(ctx: Context) { val appWidgetManager = AppWidgetManager.getInstance(ctx) val intent = Intent(ctx, TaskListWidget::class.java) intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE val thisWidget = ComponentName(ctx, TaskListWidget::class.java) val ids = appWidgetManager.getAppWidgetIds(thisWidget) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids) ctx.sendBroadcast(intent) } fun refreshTaskList(ctx: Context, storeId: Long) { val intent = Intent(OnRefreshReceiver.REFRESH_ACTION) intent.putExtra("newStoreId", storeId) ctx.sendBroadcast(intent) }
gpl-2.0
37eb07135ac12d4f5d8fbe8515193b7b
28.103448
67
0.757109
4.178218
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/ui/EditEventActivity.kt
1
48054
// // Calendar Notifications Plus // Copyright (C) 2018 Sergey Parshin ([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, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.ui import android.app.AlertDialog import android.app.DatePickerDialog import android.app.TimePickerDialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.graphics.drawable.ColorDrawable import android.os.Build import android.os.Bundle import android.provider.CalendarContract import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.format.DateUtils import android.view.Menu import android.view.View import android.view.ViewGroup import android.widget.* import com.github.quarck.calnotify.Consts import com.github.quarck.calnotify.R import com.github.quarck.calnotify.Settings import com.github.quarck.calnotify.calendar.* import com.github.quarck.calnotify.calendareditor.* import com.github.quarck.calnotify.logs.DevLog import com.github.quarck.calnotify.textutils.EventFormatter import com.github.quarck.calnotify.textutils.dateToStr import com.github.quarck.calnotify.utils.* import java.util.* // FIXME: on the snooze activity - show all the reminders, not just next // FIXME: Bin - invalid 'moved to' after edit // FIXME: handle repeating requests // FIXME: handle timezones // FIXME: Also handle colors fun EventReminderRecord.toLocalizedString(ctx: Context, isAllDay: Boolean): String { val ret = StringBuilder() if (!isAllDay) { val duration = EventFormatter(ctx).formatTimeDuration(this.millisecondsBefore, 60L) ret.append( ctx.resources.getString(R.string.add_event_fmt_before).format(duration) ) } else { val fullDaysBefore = allDayDaysBefore val (hr, min) = allDayHourOfDayAndMinute val cal = DateTimeUtils.createCalendarTime(System.currentTimeMillis(), hr, min) val time = DateUtils.formatDateTime(ctx, cal.timeInMillis, DateUtils.FORMAT_SHOW_TIME) when (fullDaysBefore) { 0 -> ret.append( ctx.resources.getString(R.string.add_event_zero_days_before).format(time) ) 1 -> ret.append( ctx.resources.getString(R.string.add_event_one_day_before).format(time) ) else -> ret.append( ctx.resources.getString(R.string.add_event_n_days_before).format(fullDaysBefore, time) ) } } when (this.method) { CalendarContract.Reminders.METHOD_EMAIL -> { ret.append(" ") ret.append(ctx.resources.getString(R.string.add_event_as_email_suffix)) } CalendarContract.Reminders.METHOD_SMS -> { ret.append(" ") ret.append(ctx.resources.getString(R.string.add_event_as_sms_suffix)) } CalendarContract.Reminders.METHOD_ALARM -> { ret.append(" ") ret.append(ctx.resources.getString(R.string.add_event_as_alarm_suffix)) } } return ret.toString() } data class EditEventActivityState( var eventId: Long, var title: String, var location: String, var note: String, var from: Calendar, var to: Calendar, var isAllDay: Boolean, var reminders: List<EventReminderRecord>, var allDayReminders: List<EventReminderRecord>, var selectedCalendar: Long, var isMuted: Boolean, var isTask: Boolean, var isAlarm: Boolean ) { fun toBundle(bundle: Bundle) { bundle.putLong(KEY_EVENT_ID, eventId) bundle.putString(KEY_TITLE, title) bundle.putString(KEY_LOCATION, location) bundle.putString(KEY_NOTE, note) bundle.putLong(KEY_FROM, from.timeInMillis) bundle.putLong(KEY_TO, to.timeInMillis) bundle.putBoolean(KEY_IS_ALL_DAY, isAllDay) bundle.putString(KEY_REMINDERS, reminders.serialize()) bundle.putString(KEY_ALL_DAY_REMINDERS, allDayReminders.serialize()) bundle.putLong(KEY_SELECTED_CALENDAR, selectedCalendar) bundle.putBoolean(KEY_IS_ALARM, isAlarm) bundle.putBoolean(KEY_IS_TASK, isTask) bundle.putBoolean(KEY_IS_MUTED, isMuted) } companion object { fun fromBundle(bundle: Bundle): EditEventActivityState { val id = bundle.getLong(KEY_EVENT_ID, -1L) val title = bundle.getString(KEY_TITLE, "") val loc = bundle.getString(KEY_LOCATION, "") val note = bundle.getString(KEY_NOTE, "") val from = bundle.getLong(KEY_FROM) val to = bundle.getLong(KEY_TO) val isAllDay = bundle.getBoolean(KEY_IS_ALL_DAY, false) val reminders = bundle.getString(KEY_REMINDERS, "").deserializeCalendarEventReminders() val allDayReminders = bundle.getString(KEY_ALL_DAY_REMINDERS, "").deserializeCalendarEventReminders() val selectedCalendar = bundle.getLong(KEY_SELECTED_CALENDAR) val muted = bundle.getBoolean(KEY_IS_MUTED) val task = bundle.getBoolean(KEY_IS_TASK) val alarm = bundle.getBoolean(KEY_IS_ALARM) return EditEventActivityState( id, title, loc, note, DateTimeUtils.createCalendarTime(from), DateTimeUtils.createCalendarTime(to), isAllDay, reminders, allDayReminders, selectedCalendar, muted, task, alarm ) } const val KEY_EVENT_ID = "eventId" const val KEY_TITLE = "title" const val KEY_LOCATION = "loc" const val KEY_NOTE = "note" const val KEY_FROM = "from" const val KEY_TO = "to" const val KEY_IS_ALL_DAY = "aday" const val KEY_REMINDERS = "reminders" const val KEY_ALL_DAY_REMINDERS = "adayreminders" const val KEY_SELECTED_CALENDAR = "cal" const val KEY_IS_MUTED = "isMuted" const val KEY_IS_TASK = "isTask" const val KEY_IS_ALARM = "isAlarm" } } open class EditEventActivity : AppCompatActivity() { data class ReminderWrapper(val view: TextView, var reminder: EventReminderRecord, val isForAllDay: Boolean) private var receivedSharedText = "" private lateinit var eventTitleText: EditText private lateinit var buttonSave: Button private lateinit var buttonCancel: ImageView private lateinit var accountName: TextView private lateinit var switchAllDay: Switch private lateinit var dateFrom: Button private lateinit var timeFrom: Button private lateinit var dateTo: Button private lateinit var timeTo: Button private lateinit var eventLocation: EditText private lateinit var notificationsLayout: LinearLayout private lateinit var notificationPrototype: TextView private lateinit var addNotification: TextView private lateinit var note: EditText private lateinit var muteTagButton: TextView private lateinit var taskTagButton: TextView private lateinit var alarmTagButton: TextView private lateinit var eventTitleLayout: RelativeLayout private lateinit var tagsLayout: LinearLayout private var isMuted = false private var isTask = false private var isAlarm = false private lateinit var calendars: List<CalendarRecord> private lateinit var calendar: CalendarRecord private lateinit var settings: Settings private lateinit var from: Calendar private lateinit var to: Calendar private var isAllDay: Boolean = false private lateinit var persistentState: CalendarChangePersistentState var calendarProvider: CalendarProviderInterface = CalendarProvider val reminders = mutableListOf<ReminderWrapper>() var originalEvent: EventRecord? = null val anyChanges: Boolean get() { val details = originalEvent?.details if (details == null) { return eventTitleText.text.isNotEmpty() || eventLocation.text.isNotEmpty() || note.text.isNotEmpty() } if (eventTitleText.text.toString() != details.title || note.text.toString() != details.desc || eventLocation.text.toString() != details.location ) { return true } // if (eventTimeZone.text.toString() != details.timezone) // return true if (isAllDay != details.isAllDay) return true var currentStartTime = from.timeInMillis var currentEndTime = to.timeInMillis if (isAllDay) { currentStartTime = DateTimeUtils.createUTCCalendarDate(from.year, from.month, from.dayOfMonth).timeInMillis currentEndTime = DateTimeUtils.createUTCCalendarDate(to.year, to.month, to.dayOfMonth).timeInMillis } if (currentStartTime != details.startTime || currentEndTime != details.endTime) return true val currentReminders = reminders.filter { it.isForAllDay == isAllDay }.map { it.reminder } if (currentReminders.size != details.reminders.size) return true if (!details.reminders.containsAll(currentReminders)) return true // if (colorView.text.value != details.color) // return true /* val repeatingRule: String = "", // empty if not repeating val repeatingRDate: String = "", // empty if not repeating val repeatingExRule: String = "", // empty if not repeating val repeatingExRDate: String = "", // empty if not repeating */ return false; } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_event) val toolbar = find<Toolbar?>(R.id.toolbar) toolbar?.visibility = View.GONE persistentState = CalendarChangePersistentState(this) val intent = intent val action = intent.action val type = intent.type if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { receivedSharedText = intent.getStringExtra(Intent.EXTRA_TEXT) } } val eventId = intent.getLongExtra(EVENT_ID, -1) if (eventId != -1L) { originalEvent = CalendarProvider.getEvent(this, eventId) if (originalEvent == null) { Toast.makeText(this, R.string.event_not_found, Toast.LENGTH_LONG).show() finish() return } } else { if (receivedSharedText.isEmpty()) findOrThrow<LinearLayout>(R.id.layout_focus_catcher).visibility = View.GONE } eventTitleLayout = find<RelativeLayout?>(R.id.snooze_view_event_details_layout) ?: throw Exception("Cant find snooze_view_event_details_layout") // get all the objects first eventTitleText = find<EditText?>(R.id.add_event_title) ?: throw Exception("Can't find add_event_title") buttonSave = find<Button?>(R.id.add_event_save) ?: throw Exception("Can't find add_event_save") buttonCancel = find<ImageView?>(R.id.add_event_view_cancel) ?: throw Exception("Can't find add_event_view_cancel") accountName = find<TextView?>(R.id.account_name) ?: throw Exception("Can't find account_name") switchAllDay = find<Switch?>(R.id.switch_all_day) ?: throw Exception("Can't find switch_all_day") dateFrom = find<Button?>(R.id.add_event_date_from) ?: throw Exception("Can't find add_event_date_from") timeFrom = find<Button?>(R.id.add_event_time_from) ?: throw Exception("Can't find add_event_time_from") dateTo = find<Button?>(R.id.add_event_date_to) ?: throw Exception("Can't find add_event_date_to") timeTo = find<Button?>(R.id.add_event_time_to) ?: throw Exception("Can't find add_event_time_to") eventLocation = find<EditText?>(R.id.event_location) ?: throw Exception("Can't find event_location") notificationsLayout = find<LinearLayout?>(R.id.notifications) ?: throw Exception("Can't find notifications") notificationPrototype = find<TextView?>(R.id.notificationPrototype) ?: throw Exception("Can't find notificationPrototype") addNotification = find<TextView?>(R.id.add_notification) ?: throw Exception("Can't find add_notification") note = find<EditText?>(R.id.event_note) ?: throw Exception("Can't find event_note") notificationPrototype.visibility = View.GONE // settings settings = Settings(this) taskTagButton = find<TextView?>(R.id.add_event_task_tag) ?: throw Exception("Can't find add_event_task_tag") muteTagButton = find<TextView?>(R.id.add_event_mute_tag) ?: throw Exception("Can't find add_event_mute_tag") alarmTagButton = find<TextView?>(R.id.add_event_alarm_tag) ?: throw Exception("Can't find add_event_alarm_tag") tagsLayout = find<LinearLayout?>(R.id.add_event_layout_buttons) ?: throw Exception("Can't find add_event_layout_buttons") updateTags(true) if (originalEvent == null) { taskTagButton.setOnClickListener { isTask = !isTask updateTags(false) } muteTagButton.setOnClickListener { isMuted = !isMuted updateTags(false) } alarmTagButton.setOnClickListener { isAlarm = !isAlarm updateTags(false) } } // Default calendar calendars = calendarProvider .getCalendars(this) .filter { !it.isReadOnly && it.isVisible && settings.getCalendarIsHandled(it.calendarId) } if (calendars.isEmpty()) { DevLog.error(LOG_TAG, "You have no enabled calendars") accountName.text = "" // remove debug mess AlertDialog.Builder(this) .setMessage(R.string.no_active_calendars) .setPositiveButton(android.R.string.ok) { _, _ -> finish() } .show() return } val lastCalendar = persistentState.lastCalendar if (lastCalendar != -1L) { calendar = calendars.filter { it.calendarId == lastCalendar }.firstOrNull() ?: calendars[0] } else { calendar = calendars.filter { it.isPrimary }.firstOrNull() ?: calendars[0] } // Set onClickListener-s buttonSave.setOnClickListener(this::onButtonSaveClick) buttonCancel.setOnClickListener(this::onButtonCancelClick) accountName.setOnClickListener(this::onAccountClick) switchAllDay.setOnClickListener(this::onSwitchAllDayClick) dateFrom.setOnClickListener(this::onDateFromClick) timeFrom.setOnClickListener(this::onTimeFromClick) dateTo.setOnClickListener(this::onDateToClick) timeTo.setOnClickListener(this::onTimeToClick) addNotification.setOnClickListener(this::onAddNotificationClick) // Set-up fields val eventToEdit = originalEvent if (savedInstanceState != null) { val state = EditEventActivityState.fromBundle(savedInstanceState) originalEvent = if (state.eventId != -1L) calendarProvider.getEvent(this, state.eventId) else null calendar = calendars.find { it.calendarId == state.selectedCalendar } ?: calendars[0] accountName.text = calendar.name val color = originalEvent?.color ?: calendar.color eventTitleLayout.background = ColorDrawable(color.adjustCalendarColor()) eventTitleText.background = ColorDrawable(color.adjustCalendarColor()) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = color.scaleColor(0.7f) } from = state.from to = state.to eventTitleText.setText(state.title) note.setText(state.note) eventLocation.setText(state.location) switchAllDay.isChecked = state.isAllDay isAllDay = state.isAllDay isMuted = state.isMuted isAlarm = state.isAlarm isTask = state.isTask for (reminder in state.reminders) { addReminder(reminder, false) } for (reminder in state.allDayReminders) { addReminder(reminder, true) } updateDateTimeUI(); updateReminders() updateTags(true) } else if (eventToEdit != null) { //val details = eventToEdit.details val cal = calendars.find { it.calendarId == eventToEdit.calendarId } if (cal == null) { Toast.makeText(this, R.string.calendar_not_found, Toast.LENGTH_LONG).show() finish() return } calendar = cal isAllDay = eventToEdit.isAllDay switchAllDay.isChecked = isAllDay switchAllDay.isEnabled = false accountName.text = calendar.name eventTitleLayout.background = ColorDrawable(eventToEdit.color.adjustCalendarColor()) eventTitleText.background = ColorDrawable(eventToEdit.color.adjustCalendarColor()) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = eventToEdit.color.scaleColor(0.7f) } eventTitleText.setText(eventToEdit.title) note.setText(eventToEdit.desc) eventLocation.setText(eventToEdit.location) // eventTimeSonze.setText(eventToEdit.timezone) from = DateTimeUtils.createCalendarTime(eventToEdit.startTime) to = DateTimeUtils.createCalendarTime(eventToEdit.endTime) if (eventToEdit.isAllDay) { val fromUtc = DateTimeUtils.createUTCCalendarTime(eventToEdit.startTime) val toUtc = DateTimeUtils.createUTCCalendarTime(eventToEdit.endTime) from.year = fromUtc.year from.month = fromUtc.month from.dayOfMonth = fromUtc.dayOfMonth to.year = toUtc.year to.month = toUtc.month to.dayOfMonth = toUtc.dayOfMonth } eventTitleText.clearFocus() updateDateTimeUI() for (reminder in eventToEdit.reminders) { addReminder(reminder, isAllDay) } updateReminders() } else { // Initialize default values accountName.text = calendar.name eventTitleLayout.background = ColorDrawable(calendar.color.adjustCalendarColor()) eventTitleText.background = ColorDrawable(calendar.color.adjustCalendarColor()) if (receivedSharedText.isNotEmpty()) { eventTitleText.setText(receivedSharedText) } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = calendar.color.scaleColor(0.7f) } // Set default date and time var currentTime = System.currentTimeMillis() currentTime -= (currentTime % 1000) // Drop millis from = DateTimeUtils.createCalendarTime(currentTime) from.addHours(Consts.NEW_EVENT_DEFAULT_ADD_HOURS) from.minute = 0 from.second = 0 to = DateTimeUtils.createCalendarTime(from.timeInMillis) to.addMinutes(settings.defaultNewEventDurationMinutes) DevLog.debug(LOG_TAG, "${from.timeInMillis}, ${to.timeInMillis}, $from, $to") updateDateTimeUI() addReminder(EventReminderRecord(Consts.NEW_EVENT_DEFAULT_NEW_EVENT_REMINDER), false) addReminder(EventReminderRecord(Consts.NEW_EVENT_DEFAULT_ALL_DAY_REMINDER), true) updateReminders() } } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val regularReminders = reminders.filter { it.isForAllDay == false }.map { it.reminder }.toList(); val allDayReminders = reminders.filter { it.isForAllDay == true }.map { it.reminder }.toList() val state = EditEventActivityState( originalEvent?.eventId ?: -1L, eventTitleText.text.toString(), eventLocation.text.toString(), note.text.toString(), from, to, isAllDay, regularReminders, allDayReminders, calendar.calendarId, isMuted, isTask, isAlarm ) state.toBundle(outState) } fun updateDateTimeUI() { if (isAllDay) { timeTo.visibility = View.GONE timeFrom.visibility = View.GONE } else { timeTo.visibility = View.VISIBLE timeFrom.visibility = View.VISIBLE } val dateFormat = DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_YEAR or DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_ABBREV_MONTH or DateUtils.FORMAT_ABBREV_WEEKDAY val timeFormat = DateUtils.FORMAT_SHOW_TIME if (!isAllDay) { dateFrom.text = DateUtils.formatDateTime(this, from.timeInMillis, dateFormat) timeFrom.text = DateUtils.formatDateTime(this, from.timeInMillis, timeFormat) dateTo.text = DateUtils.formatDateTime(this, to.timeInMillis, dateFormat) timeTo.text = DateUtils.formatDateTime(this, to.timeInMillis, timeFormat) } else { val fromClean = DateTimeUtils.createCalendarTime(from.timeInMillis) fromClean.hourOfDay = 0 fromClean.minute = 0 val toClean = DateTimeUtils.createCalendarTime(to.timeInMillis) toClean.hourOfDay = 0 toClean.minute = 0 dateFrom.text = DateUtils.formatDateTime(this, fromClean.timeInMillis, dateFormat) dateTo.text = DateUtils.formatDateTime(this, Math.max(toClean.timeInMillis-1000L, fromClean.timeInMillis), dateFormat) } } fun updateTags(updateLayouts: Boolean) { val enableTags = originalEvent == null if (updateLayouts) { tagsLayout.visibility = if (enableTags) View.VISIBLE else View.GONE } if (enableTags) { if (updateLayouts) { taskTagButton.visibility = View.VISIBLE muteTagButton.visibility = View.VISIBLE alarmTagButton.visibility = View.VISIBLE } val selectedColor = ContextCompat.getColor(this, R.color.event_selected_tag_color) val unselectedColor = ContextCompat.getColor(this, R.color.event_unselected_tag_color) taskTagButton.setTextColor(if (isTask) selectedColor else unselectedColor) muteTagButton.setTextColor(if (isMuted) selectedColor else unselectedColor) alarmTagButton.setTextColor(if (isAlarm) selectedColor else unselectedColor) } } fun updateReminders() { for (reminder in reminders) { if (reminder.isForAllDay == isAllDay) { reminder.view.visibility = View.VISIBLE } else { reminder.view.visibility = View.GONE } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.add_event, menu) return true } override fun onBackPressed() { if (anyChanges) { AlertDialog.Builder(this) .setMessage(R.string.discard_new_event) .setCancelable(false) .setPositiveButton(android.R.string.yes) { _, _ -> [email protected]() } .setNegativeButton(R.string.cancel) { _, _ -> } .create() .show() } else { finish() } } @Suppress("UNUSED_PARAMETER") fun onButtonCancelClick(v: View) { onBackPressed() } @Suppress("UNUSED_PARAMETER") fun onAccountClick(v: View) { if (originalEvent != null) return // not editable anymore val builder = AlertDialog.Builder(this) val adapter = ArrayAdapter<String>(this, R.layout.simple_list_item_medium) val listCalendars = calendars.filter { !it.isReadOnly }.map { "${it.displayName} <${it.accountName}>" }.toList() adapter.addAll(listCalendars) builder.setCancelable(true) builder.setAdapter(adapter) { _, which -> if (which in 0..calendars.size-1) { calendar = calendars.get(which) persistentState.lastCalendar = calendar.calendarId accountName.text = calendar.name // eventTitleText.background = ColorDrawable( // calendar.color.adjustCalendarColor(settings.darkerCalendarColors)) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.statusBarColor = calendar.color.scaleColor(0.7f) } eventTitleLayout.background = ColorDrawable(calendar.color.adjustCalendarColor()) eventTitleText.background = ColorDrawable(calendar.color.adjustCalendarColor()) } } builder.show() } @Suppress("UNUSED_PARAMETER") fun onButtonSaveClick(v: View) { var startTime = from.timeInMillis var endTime = to.timeInMillis if (isAllDay) { startTime = DateTimeUtils.createUTCCalendarDate(from.year, from.month, from.dayOfMonth).timeInMillis endTime = DateTimeUtils.createUTCCalendarDate(to.year, to.month, to.dayOfMonth).timeInMillis } val remindersToAdd = reminders.filter { it.isForAllDay == isAllDay }.map { it.reminder }.toList() var appendTags = "" if (originalEvent == null) { if (isMuted) appendTags += " #mute" if (isTask) appendTags += " #task" if (isAlarm) appendTags += " #alarm" } val details = CalendarEventDetails( title = eventTitleText.text.toString() + appendTags, desc = note.text.toString(), location = eventLocation.text.toString(), timezone = originalEvent?.timezone ?: calendar.timeZone, startTime = startTime, endTime = endTime, isAllDay = isAllDay, repeatingRule = originalEvent?.repeatingRule ?: "", repeatingRDate = originalEvent?.repeatingRDate ?: "", repeatingExRule = originalEvent?.repeatingExRule ?: "", repeatingExRDate = originalEvent?.repeatingExRDate ?: "", color = originalEvent?.color ?: 0, reminders = remindersToAdd ) val eventToEdit = originalEvent if (eventToEdit == null) { val eventId = CalendarChangeManager(CalendarProvider).createEvent(this, calendar.calendarId, calendar.owner, details) if (eventId != -1L) { DevLog.debug(LOG_TAG, "Event created: id=${eventId}") val nextReminder = calendarProvider.getNextEventReminderTime(this, eventId, startTime) if (nextReminder != 0L) { Toast.makeText( this, resources.getString(R.string.event_was_created_reminder_at).format(dateToStr(this, nextReminder)), Toast.LENGTH_LONG ).show() } else { Toast.makeText(this, R.string.event_was_created, Toast.LENGTH_LONG).show() } finish() } else { DevLog.error(LOG_TAG, "Failed to create event") AlertDialog.Builder(this) .setMessage(R.string.new_event_failed_to_create_event) .setPositiveButton(android.R.string.ok) { _, _ -> } .show() } } else { val success = CalendarChangeManager(CalendarProvider).updateEvent(this, eventToEdit, details) if (success) { val nextReminder = calendarProvider.getNextEventReminderTime(this, eventToEdit.eventId, details.startTime) if (nextReminder != 0L) { Toast.makeText( this, resources.getString(R.string.event_was_updated_next_reminder).format(dateToStr(this, nextReminder)), Toast.LENGTH_LONG ).show() } else { Toast.makeText(this, getString(R.string.event_was_updated), Toast.LENGTH_LONG).show() } finish() } else { Toast.makeText(this, R.string.failed_to_update_event_details, Toast.LENGTH_LONG).show() } } } @Suppress("UNUSED_PARAMETER") fun onSwitchAllDayClick(v: View) { isAllDay = switchAllDay.isChecked if (isAllDay) { to = DateTimeUtils.createCalendarTime(from.timeInMillis) to.addDays(1) } else { to = DateTimeUtils.createCalendarTime(from.timeInMillis) to.addMinutes(settings.defaultNewEventDurationMinutes) } updateDateTimeUI() updateReminders() } @Suppress("UNUSED_PARAMETER") fun onDateFromClick(v: View) { val durationMinutes = (to.timeInMillis - from.timeInMillis) / Consts.MINUTE_IN_MILLISECONDS val dialog = DatePickerDialog( this, { _, year, month, day -> from.year = year from.month = month from.dayOfMonth = day to = DateTimeUtils.createCalendarTime(from.timeInMillis) to.addMinutes(durationMinutes.toInt()) updateDateTimeUI() }, from.year, from.month, from.dayOfMonth ) val firstDayOfWeek = Settings(this).firstDayOfWeek if (firstDayOfWeek != -1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { dialog.datePicker.firstDayOfWeek = firstDayOfWeek } dialog.show() //builder.setIcon(R.drawable.ic_launcher) } @Suppress("UNUSED_PARAMETER") fun onTimeFromClick(v: View) { val durationMinutes = (to.timeInMillis - from.timeInMillis) / Consts.MINUTE_IN_MILLISECONDS val dialog = TimePickerDialog( this, { _, hour, min -> from.hourOfDay = hour from.minute = min to = DateTimeUtils.createCalendarTime(from.timeInMillis) to.addMinutes(durationMinutes.toInt()) updateDateTimeUI() }, from.hourOfDay, from.minute, android.text.format.DateFormat.is24HourFormat(this) ) dialog.show() } @Suppress("UNUSED_PARAMETER") fun onDateToClick(v: View) { val durationMinutes = (to.timeInMillis - from.timeInMillis) / Consts.MINUTE_IN_MILLISECONDS val dialog = DatePickerDialog( this, { _, year, month, day -> to.year = year to.month = month to.dayOfMonth = day if (to.before(from)) { Toast.makeText(this, getString(R.string.end_time_before_start_time), Toast.LENGTH_LONG).show() to = DateTimeUtils.createCalendarTime(from.timeInMillis) to.addMinutes(durationMinutes.toInt()) } updateDateTimeUI() }, to.year, to.month, to.dayOfMonth ) val firstDayOfWeek = Settings(this).firstDayOfWeek if (firstDayOfWeek != -1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { dialog.datePicker.firstDayOfWeek = firstDayOfWeek } dialog.show() } @Suppress("UNUSED_PARAMETER") fun onTimeToClick(v: View) { val durationMinutes = (to.timeInMillis - from.timeInMillis) / Consts.MINUTE_IN_MILLISECONDS val dialog = TimePickerDialog( this, { _, hour, min -> to.hourOfDay = hour to.minute = min if (to.before(from)) { Toast.makeText(this, getString(R.string.end_time_before_start_time), Toast.LENGTH_LONG).show() to = DateTimeUtils.createCalendarTime(from.timeInMillis) to.addMinutes(durationMinutes.toInt()) } updateDateTimeUI() }, to.hourOfDay, to.minute, android.text.format.DateFormat.is24HourFormat(this) ) dialog.show() } @Suppress("UNUSED_PARAMETER") fun onNotificationClick(v: View) { val wrapper = reminders.find { it.view == v } if (wrapper != null) { if (wrapper.isForAllDay) showAddReminderListAllDayDialog(wrapper.reminder, wrapper.view) else showAddReminderListDialog(wrapper.reminder, wrapper.view) } } fun showAddReminderCustomDialog(currentReminder: EventReminderRecord, existingReminderView: View?) { val dialogView = this.layoutInflater.inflate(R.layout.dialog_add_event_notification, null); val timeIntervalPicker = TimeIntervalPickerController(dialogView, null, Consts.NEW_EVENT_MAX_REMINDER_MILLISECONDS_BEFORE, false) timeIntervalPicker.intervalMilliseconds = currentReminder.millisecondsBefore val isEmailCb = dialogView.find<CheckBox?>(R.id.checkbox_as_email) val builder = AlertDialog.Builder(this) builder.setView(dialogView) builder.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int -> var intervalMilliseconds = timeIntervalPicker.intervalMilliseconds val isEmail = isEmailCb?.isChecked ?: false if (intervalMilliseconds > Consts.NEW_EVENT_MAX_REMINDER_MILLISECONDS_BEFORE) { intervalMilliseconds = Consts.NEW_EVENT_MAX_REMINDER_MILLISECONDS_BEFORE Toast.makeText(this, R.string.new_event_max_reminder_is_28_days, Toast.LENGTH_LONG).show() } val reminder = EventReminderRecord( intervalMilliseconds, if (isEmail) CalendarContract.Reminders.METHOD_EMAIL else CalendarContract.Reminders.METHOD_DEFAULT ) if (existingReminderView != null) modifyReminder(existingReminderView, reminder) else addReminder(reminder, isForAllDay = false) } if (existingReminderView != null) { builder.setNegativeButton(R.string.remove_reminder) { _: DialogInterface?, _: Int -> removeReminder(existingReminderView) } } else { builder.setNegativeButton(android.R.string.cancel) { _: DialogInterface?, _: Int -> } } builder.create().show() } fun showAddReminderListDialog(currentReminder: EventReminderRecord, existingReminderView: View?) { if (currentReminder.method != CalendarContract.Reminders.METHOD_DEFAULT) return showAddReminderCustomDialog(currentReminder, existingReminderView) val intervalNames: Array<String> = this.resources.getStringArray(R.array.default_reminder_intervals) val intervalValues = this.resources.getIntArray(R.array.default_reminder_intervals_milliseconds_values) if (intervalValues.find { it.toLong() == currentReminder.millisecondsBefore } == null) { // reminder is not one of standard ones - we have to show custom idalog return showAddReminderCustomDialog(currentReminder, existingReminderView) } val builder = AlertDialog.Builder(this) val adapter = ArrayAdapter<String>(this, R.layout.simple_list_item_medium) adapter.addAll(intervalNames.toMutableList()) builder.setCancelable(true) builder.setAdapter(adapter) { _, which -> if (which in 0..intervalValues.size-1) { val intervalMillis = intervalValues[which].toLong() if (intervalMillis != -1L) { if (existingReminderView != null) modifyReminder(existingReminderView, EventReminderRecord(intervalMillis)) else addReminder(EventReminderRecord(intervalMillis), isForAllDay = false) } else { showAddReminderCustomDialog(currentReminder, existingReminderView) } } } if (existingReminderView != null) { builder.setNegativeButton(R.string.remove_reminder) { _: DialogInterface?, _: Int -> removeReminder(existingReminderView) } } else { builder.setNegativeButton(android.R.string.cancel) { _: DialogInterface?, _: Int -> } } builder.show() } fun showAddReminderCustomAllDayDialog(currentReminder: EventReminderRecord, existingReminderView: View?) { val dialogView = this.layoutInflater.inflate(R.layout.dialog_add_event_allday_notification, null); val numberPicker = dialogView.findOrThrow<NumberPicker>(R.id.number_picker_days_before) val timePicker = dialogView.findOrThrow<TimePicker>(R.id.time_picker_notification_time_of_day) val isEmailCb = dialogView.findOrThrow<CheckBox>(R.id.checkbox_as_email) numberPicker.minValue = 0 numberPicker.maxValue = Consts.NEW_EVENT_MAX_ALL_DAY_REMINDER_DAYS_BEFORE numberPicker.value = currentReminder.allDayDaysBefore timePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(this)) val (hr, min) = currentReminder.allDayHourOfDayAndMinute timePicker.hourCompat = hr timePicker.minuteCompat = min val builder = AlertDialog.Builder(this) builder.setView(dialogView) builder.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int -> numberPicker.clearFocus() timePicker.clearFocus() val daysBefore = numberPicker.value val pickerHr = timePicker.hourCompat val pickerMin = timePicker.minuteCompat val daysInMilliseconds = daysBefore * Consts.DAY_IN_MILLISECONDS val hrMinInMilliseconds = pickerHr * Consts.HOUR_IN_MILLISECONDS + pickerMin * Consts.MINUTE_IN_MILLISECONDS val reminderTimeMilliseconds = daysInMilliseconds - hrMinInMilliseconds val isEmail = isEmailCb.isChecked val reminder = EventReminderRecord( reminderTimeMilliseconds, if (isEmail) CalendarContract.Reminders.METHOD_EMAIL else CalendarContract.Reminders.METHOD_DEFAULT ) if (existingReminderView != null) modifyReminder(existingReminderView, reminder) else addReminder(reminder, isForAllDay = true) } if (existingReminderView != null) { builder.setNegativeButton(R.string.remove_reminder) { _: DialogInterface?, _: Int -> removeReminder(existingReminderView) } } else { builder.setNegativeButton(android.R.string.cancel) { _: DialogInterface?, _: Int -> } } builder.create().show() } fun showAddReminderListAllDayDialog(currentReminder: EventReminderRecord, existingReminderView: View?) { if (currentReminder.method != CalendarContract.Reminders.METHOD_DEFAULT) return showAddReminderCustomAllDayDialog(currentReminder, existingReminderView) val reminderNames: Array<String> = this.resources.getStringArray(R.array.default_reminder_intervals_all_day) val reminderValues = this.resources.getIntArray(R.array.default_reminder_intervals_all_day_seconds_values) val enterManuallyValue = -2147483648 if (reminderValues.find { it.toLong() == currentReminder.millisecondsBefore / 1000L } == null) { // reminder is not one of standard ones - we have to show custom idalog return showAddReminderCustomAllDayDialog(currentReminder, existingReminderView) } val builder = AlertDialog.Builder(this) val adapter = ArrayAdapter<String>(this, R.layout.simple_list_item_medium) adapter.addAll(reminderNames.toMutableList()) builder.setCancelable(true) builder.setAdapter(adapter) { _, which -> if (which in 0..reminderValues.size-1) { val reminderSeconds = reminderValues[which] if (reminderSeconds != enterManuallyValue) { val reminderTimeMillis = reminderSeconds.toLong() * 1000L if (existingReminderView != null) modifyReminder(existingReminderView, EventReminderRecord(reminderTimeMillis)) else addReminder(EventReminderRecord(reminderTimeMillis), isForAllDay = true) } else { showAddReminderCustomAllDayDialog(currentReminder, existingReminderView) } } } if (existingReminderView != null) { builder.setNegativeButton(R.string.remove_reminder) { _: DialogInterface?, _: Int -> removeReminder(existingReminderView) } } else { builder.setNegativeButton(android.R.string.cancel) { _: DialogInterface?, _: Int -> } } builder.show() } @Suppress("UNUSED_PARAMETER") fun onAddNotificationClick(v: View) { if (!isAllDay) { showAddReminderListDialog(EventReminderRecord(Consts.NEW_EVENT_DEFAULT_NEW_EVENT_REMINDER), null) } else { showAddReminderListAllDayDialog(EventReminderRecord(Consts.NEW_EVENT_DEFAULT_ALL_DAY_REMINDER), null) } } private fun removeReminder(existingReminderView: View) { val wrapper = reminders.find { it.view == existingReminderView } if (wrapper != null) { reminders.remove(wrapper) notificationsLayout.removeView(wrapper.view) } } private fun modifyReminder(existingReminderView: View, newReminder: EventReminderRecord) { if (reminders.find { it.reminder == newReminder && it.view != existingReminderView} != null) { // we have another reminder with the same params in the list -- remove this one (cruel!!) removeReminder(existingReminderView) return } val wrapper = reminders.find { it.view == existingReminderView } if (wrapper != null) { wrapper.reminder = newReminder wrapper.view.text = newReminder.toLocalizedString(this, isAllDay) } } private fun addReminder(reminder: EventReminderRecord, isForAllDay: Boolean) { if (reminders.find { it.reminder == reminder} != null) { DevLog.warn(LOG_TAG, "Not adding reminder: already in the list") return } val textView = TextView(this) textView.text = reminder.toLocalizedString(this, isForAllDay) textView.setOnClickListener (this::onNotificationClick) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { textView.setTextAppearance(android.R.style.TextAppearance_Medium) } else { @Suppress("DEPRECATION") textView.setTextAppearance(this, android.R.style.TextAppearance_Medium) } textView.setTextColor(notificationPrototype.textColors) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView.setPaddingRelative( notificationPrototype.paddingStart, notificationPrototype.paddingTop, notificationPrototype.paddingEnd, notificationPrototype.paddingBottom) } else { textView.setPadding( notificationPrototype.paddingLeft, notificationPrototype.paddingTop, notificationPrototype.paddingRight, notificationPrototype.paddingBottom) } textView.isClickable = true textView.background = notificationPrototype.background val lp = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) notificationsLayout.addView(textView, lp) reminders.add(ReminderWrapper(textView, reminder, isForAllDay)) } companion object { private const val LOG_TAG = "EditEventActivity" const val EVENT_ID = "event_id" } }
gpl-3.0
ce1ed6c0d087d173f6617eda53e43043
34.995506
152
0.595809
5.198961
false
false
false
false
MaibornWolff/codecharta
analysis/import/MetricGardenerImporter/src/test/kotlin/de/maibornwolff/codecharta/importer/metricgardenerimporter/MetricGardenerImporterTest.kt
1
2343
package de.maibornwolff.codecharta.importer.metricgardenerimporter import de.maibornwolff.codecharta.importer.metricgardenerimporter.MetricGardenerImporter.Companion.main import de.maibornwolff.codecharta.serialization.ProjectDeserializer import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import picocli.CommandLine import java.io.File class MetricGardenerImporterTest { @Test fun `should create json uncompressed file`() { main( arrayOf( "--is-json-file", "src/test/resources/metricgardener-analysis.json", "-nc", "-o=src/test/resources/import-result" ) ) val file = File("src/test/resources/import-result.cc.json") file.deleteOnExit() val inputStream = file.inputStream() val project = ProjectDeserializer.deserializeProject(inputStream) inputStream.close() assertTrue(file.exists()) assertEquals(project.attributeDescriptors, getAttributeDescriptors()) } @Test fun `should create json gzip file`() { main( arrayOf( "--is-json-file", "src/test/resources/metricgardener-analysis.json", "-o=src/test/resources/import-result" ) ) val file = File("src/test/resources/import-result.cc.json.gz") file.deleteOnExit() assertTrue(file.exists()) } @Test fun `should create file when MG needs to run first`() { main( arrayOf( "src/test/resources/MetricGardenerRawFile.kt", "-nc", "-o=src/test/resources/import-result-mg" ) ) val file = File("src/test/resources/import-result-mg.cc.json") file.deleteOnExit() assertTrue(file.exists()) } @Test fun `should create no file when the input file was not specified`() { main( arrayOf( "-o=src/test/resources/import-result-empty.json" ) ) val file = File("src/test/resources/import-result-empty.cc.json.gz") file.deleteOnExit() CommandLine(MetricGardenerImporter()).execute() assertFalse(file.exists()) } }
bsd-3-clause
b6206fe4ba703cb2b9cc77fc77ff0aa3
32
103
0.632096
4.454373
false
true
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/tables/SnowflakeTable.kt
1
743
package net.perfectdreams.loritta.morenitta.tables import org.jetbrains.exposed.dao.Entity import org.jetbrains.exposed.dao.EntityClass import org.jetbrains.exposed.dao.LongEntity import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IdTable import org.jetbrains.exposed.sql.Column open class SnowflakeTable(name: String = "", columnName: String = "id") : IdTable<Long>(name) { override val id: Column<EntityID<Long>> = long(columnName).entityId() override val primaryKey = PrimaryKey(id) } abstract class SnowflakeEntity(id: EntityID<Long>) : Entity<Long>(id) abstract class SlowflakeEntityClass<out E: LongEntity>(table: IdTable<Long>, entityType: Class<E>? = null) : EntityClass<Long, E>(table, entityType)
agpl-3.0
a7e3d6ef5f6d71166f231958ad2e4fb2
42.705882
148
0.787349
3.678218
false
false
false
false
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/web/PageToadletRegistry.kt
1
2337
package net.pterodactylus.sone.web import freenet.clients.http.* import net.pterodactylus.sone.main.* import net.pterodactylus.sone.web.page.* import net.pterodactylus.util.web.* import java.util.concurrent.atomic.* import javax.inject.* private const val soneMenu = "Navigation.Menu.Sone" private const val soneMenuName = "$soneMenu.Name" class PageToadletRegistry @Inject constructor( private val pageMaker: PageMaker, private val toadletContainer: ToadletContainer, private val sonePlugin: SonePlugin, private val pageToadletFactory: PageToadletFactory ) { private val pages = mutableListOf<Page<FreenetRequest>>() private val debugPages = mutableListOf<Page<FreenetRequest>>() private val registeredToadlets = mutableListOf<PageToadlet>() private val registered = AtomicBoolean(false) private val debugActivated = AtomicBoolean(false) fun addPage(page: Page<FreenetRequest>) { if (registered.get()) throw IllegalStateException() pages += page } fun addDebugPage(page: Page<FreenetRequest>) { if (registered.get()) throw IllegalStateException() debugPages += page } fun registerToadlets() { registered.set(true) pageMaker.addNavigationCategory("/Sone/index.html", soneMenuName, "$soneMenu.Tooltip", sonePlugin) addPages() } private fun addPages(pages: List<Page<FreenetRequest>> = this.pages) = pages .map { pageToadletFactory.createPageToadlet(it) } .onEach(registeredToadlets::plusAssign) .forEach { pageToadlet -> if (pageToadlet.menuName == null) { registerToadletWithoutMenuname(pageToadlet) } else { registerToadletWithMenuname(pageToadlet) } } private fun registerToadletWithoutMenuname(pageToadlet: PageToadlet) = toadletContainer.register(pageToadlet, null, pageToadlet.path(), true, false) private fun registerToadletWithMenuname(pageToadlet: PageToadlet) = toadletContainer.register(pageToadlet, soneMenuName, pageToadlet.path(), true, "$soneMenu.Item.${pageToadlet.menuName}.Name", "$soneMenu.Item.${pageToadlet.menuName}.Tooltip", false, pageToadlet) fun unregisterToadlets() { pageMaker.removeNavigationCategory(soneMenuName) registeredToadlets.forEach(toadletContainer::unregister) } fun activateDebugMode() { if (!debugActivated.get()) { addPages(debugPages) debugActivated.set(true) } } }
gpl-3.0
21808b6d95c86a692c77c214c635b344
31.458333
198
0.76166
3.895
false
false
false
false
jiangkang/KTools
app/src/main/java/com/jiangkang/ktools/SystemActivity.kt
1
12586
package com.jiangkang.ktools import android.Manifest import android.app.Activity import android.app.AlertDialog import android.content.ComponentName import android.content.Intent import android.content.pm.PackageManager import android.database.Cursor import android.os.Bundle import android.provider.ContactsContract import android.text.TextUtils import android.util.Log import android.view.View import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import com.jiangkang.ktools.databinding.ActivitySystemBinding import com.jiangkang.ktools.service.AIDLDemoActivity import com.jiangkang.ktools.share.ShareActivity import com.jiangkang.tools.extend.wallpaperManager import com.jiangkang.tools.struct.JsonGenerator import com.jiangkang.tools.system.ContactHelper import com.jiangkang.tools.utils.ClipboardUtils import com.jiangkang.tools.utils.ShellUtils import com.jiangkang.tools.utils.SpUtils import com.jiangkang.tools.utils.ToastUtils import kotlinx.coroutines.* import org.json.JSONException import org.json.JSONObject import kotlin.concurrent.thread /** * Created by jiangkang on 2017/9/5. * description:与系统相关的Demo * 1.打开通讯录,选择联系人,获得联系人姓名和手机号 * 2.获取联系人列表 * 3.设置文本到剪贴板,从剪贴板中取出文本 */ class SystemActivity : AppCompatActivity() { private lateinit var binding:ActivitySystemBinding private var jsonObject: JSONObject? = null private val mainScope = MainScope() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySystemBinding.inflate(layoutInflater) setContentView(binding.root) title = "System" handleClick() } override fun onDestroy() { super.onDestroy() mainScope.cancel() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { when (requestCode) { REQUEST_OPEN_CONTACTS -> { gotoContactPage() } REQUEST_GET_CONTACTS -> { getContactList() } } } } private fun handleClick() { binding.btnOpenContacts.setOnClickListener { if (checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { gotoContactPage() } else { requestPermissions(arrayOf(Manifest.permission.READ_CONTACTS), REQUEST_OPEN_CONTACTS) } } binding.btnGetAllContacts.setOnClickListener { if (checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { getContactList() } else { requestPermissions(arrayOf(Manifest.permission.READ_CONTACTS), REQUEST_GET_CONTACTS) } } binding.btnSetClipboard.setOnClickListener { onBtnSetClipboardClicked() } binding.btnGetClipboard.setOnClickListener { ToastUtils.showShortToast(ClipboardUtils.stringFromClipboard) } binding.btnExitApp.setOnClickListener { onClickBtnExitApp() } binding.btnQuickSettings.setOnClickListener { mainScope.launch { val result = async(Dispatchers.IO) { ShellUtils.execCmd("adb shell setprop debug.layout true", false) ShellUtils.execCmd("adb shell am start com.android.settings/.DevelopmentSettings", false) } ToastUtils.showShortToast("result : ${result.await()}") } } binding.btnAidl.setOnClickListener { AIDLDemoActivity.launch(this, null) } binding.btnShare.setOnClickListener { startActivity(Intent(this, ShareActivity::class.java)) } binding.btnChangeWallpaper.setOnClickListener { this.wallpaperManager.setResource(R.raw.wallpaper) ToastUtils.showShortToast("壁纸更换成功!") } binding.btnHideAppIcon.setOnClickListener { onHideAppIconClicked() } binding.btnChangeIcon.setOnClickListener { changeLauncherIcon() } binding.btnHideVirtualNavbar.setOnClickListener { hideVirtualNavbar(this@SystemActivity) } binding.btnLoadDex.setOnClickListener { ToastUtils.showShortToast("代码遗失") } binding.btnCreateNote.setOnClickListener { } } private fun gotoContactPage() { val intent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI) .apply { flags += Intent.FLAG_ACTIVITY_NEW_TASK flags += Intent.FLAG_GRANT_READ_URI_PERMISSION } startActivityForResult(intent, REQUEST_PICK_CONTACT) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_PICK_CONTACT) { if (resultCode == Activity.RESULT_OK) { if (data == null) { Log.d(TAG, "onActivityResult: 什么东西都没有选") } else { Log.d(TAG, "onActivityResult: 有返回") val cursor = contentResolver.query( data.data!!, null, null, null, null ) val contact = handleCursor(cursor) try { AlertDialog.Builder(this) .setTitle("选择的联系人信息") .setMessage(contact.toString(4)) .setNegativeButton("关闭") { dialog, _ -> dialog.dismiss() } .create() .show() } catch (e: JSONException) { e.printStackTrace() } } } } super.onActivityResult(requestCode, resultCode, data) } private fun handleCursor(data: Cursor?): JSONObject { var result = JSONObject() if (data != null && data.moveToFirst()) { do { val name = data.getString( data.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) ) val id = data.getInt( data.getColumnIndex(ContactsContract.Contacts._ID) ) //指定获取NUMBER这一列数据 val phoneProjection = arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER) val cursor = contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneProjection, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null ) if (cursor != null && cursor.moveToFirst()) { do { val number = cursor.getString( cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) ) result = JsonGenerator() .put("name", name) .put("tel", number) .gen() } while (cursor.moveToNext()) } } while (data.moveToNext()) } return result } private fun getContactList() { val helper = ContactHelper(this) thread { jsonObject = helper.queryContactList() runOnUiThread { try { AlertDialog.Builder(this@SystemActivity) .setTitle("通讯录") .setMessage(jsonObject!!.toString(4)) .setPositiveButton("关闭") { dialog, _ -> dialog.dismiss() } .setNegativeButton("复制") { dialog, _ -> try { ClipboardUtils.putStringToClipboard(jsonObject!!.toString(4)) ToastUtils.showShortToast("复制成功") } catch (e: JSONException) { e.printStackTrace() } dialog.dismiss() } .show() } catch (e: JSONException) { e.printStackTrace() } } } } private fun onBtnSetClipboardClicked() { if (!TextUtils.isEmpty(findViewById<EditText>(R.id.et_content).text)) { val content = findViewById<EditText>(R.id.et_content).text.toString() ClipboardUtils.putStringToClipboard(content) ToastUtils.showShortToast("设置成功") } else { ToastUtils.showShortToast("内容不能为空") } } private fun hideVirtualNavbar(activity: Activity) { val decroView = activity.window.decorView val uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION decroView.systemUiVisibility = uiOptions } private fun changeLauncherIcon() { val packageManager = packageManager val componentName0 = ComponentName(baseContext, "com.jiangkang.ktools.MainActivity") val componentName1 = ComponentName(baseContext, "com.jiangkang.ktools.MainActivity1") if ("1" == SpUtils.getInstance(this, "Launcher").getString("icon_type", "0")) { packageManager.setComponentEnabledSetting( componentName1, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP ) packageManager.setComponentEnabledSetting( componentName0, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP ) SpUtils.getInstance(this, "Launcher") .putString("icon_type", "0") } else { packageManager.setComponentEnabledSetting( componentName0, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP ) packageManager.setComponentEnabledSetting( componentName1, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP ) SpUtils.getInstance(this, "Launcher") .putString("icon_type", "1") } ToastUtils.showShortToast("Icon替换成功,稍等一段时间方可看到效果") } private fun onClickBtnExitApp() { exitApp() } private fun exitApp() { val intent = Intent(this, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) hideVirtualNavbar(this) } private fun onHideAppIconClicked() { val manager = packageManager val componentName = ComponentName(this, MainActivity::class.java) val status = manager.getComponentEnabledSetting(componentName) if (status == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT || status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { manager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP) } else { manager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, PackageManager.DONT_KILL_APP) } } override fun onBackPressed() { super.onBackPressed() finishAfterTransition() } companion object { private val REQUEST_OPEN_CONTACTS = 1000 private val REQUEST_GET_CONTACTS = 1001 private val REQUEST_PICK_CONTACT = 1002 private val TAG = SystemActivity::class.java.simpleName } }
mit
d84186253c3801f3d414aa4edd4d850a
34.094017
140
0.576636
5.350999
false
false
false
false
Shynixn/PetBlocks
petblocks-bukkit-plugin/petblocks-bukkit-nms-118R2/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_18_R2/NMSPetBat.kt
1
5064
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_18_R2 import com.github.shynixn.petblocks.api.PetBlocksApi import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy import com.github.shynixn.petblocks.api.business.service.ConcurrencyService import com.github.shynixn.petblocks.api.persistence.entity.AIFlying import net.minecraft.core.BlockPosition import net.minecraft.world.entity.Entity import net.minecraft.world.entity.EntityTypes import net.minecraft.world.entity.ai.attributes.GenericAttributes import net.minecraft.world.entity.ai.goal.PathfinderGoal import net.minecraft.world.entity.ai.goal.PathfinderGoalSelector import net.minecraft.world.entity.animal.EntityParrot import net.minecraft.world.level.block.state.IBlockData import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.craftbukkit.v1_18_R2.CraftServer import org.bukkit.craftbukkit.v1_18_R2.CraftWorld import org.bukkit.event.entity.CreatureSpawnEvent /** * NMS implementation of the Parrot pet backend. */ class NMSPetBat(petDesign: NMSPetArmorstand, location: Location) : EntityParrot(EntityTypes.al, (location.world as CraftWorld).handle) { // NMSPetBee might be instantiated from another source. private var petDesign: NMSPetArmorstand? = null // Pathfinders need to be self cached for Paper. private var initialClear = true private var pathfinderCounter = 0 private var cachedPathfinders = HashSet<PathfinderGoal>() // BukkitEntity has to be self cached since 1.14. private var entityBukkit: Any? = null init { this.petDesign = petDesign this.d(true) // Set Silent. clearAIGoals() // NMS can sometimes instantiate this object without petDesign. if (this.petDesign != null) { val flyingAI = this.petDesign!!.proxy.meta.aiGoals.firstOrNull { a -> a is AIFlying } as AIFlying? if (flyingAI != null) { this.a(GenericAttributes.d)!!.a(0.30000001192092896 * 0.75) // Set Value. this.a(GenericAttributes.e)!!.a( 0.30000001192092896 * flyingAI.movementSpeed) // Set Value. this.P = flyingAI.climbingHeight.toFloat() } } val mcWorld = (location.world as CraftWorld).handle this.e(location.x, location.y - 200, location.z) mcWorld.addFreshEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM) val targetLocation = location.clone() PetBlocksApi.resolve(ConcurrencyService::class.java).runTaskSync(20L) { // Only fix location if it is not already fixed. if (this.bukkitEntity.location.distance(targetLocation) > 20) { this.e(targetLocation.x, targetLocation.y + 1.0, targetLocation.z) } } } /** * Applies pathfinders to the entity. */ fun applyPathfinders(pathfinders: List<Any>) { clearAIGoals() pathfinderCounter = 0 val proxies = HashMap<PathfinderProxy, CombinedPathfinder.Cache>() val hyperPathfinder = CombinedPathfinder(proxies) for (pathfinder in pathfinders) { if (pathfinder is PathfinderProxy) { val wrappedPathfinder = Pathfinder(pathfinder) this.cachedPathfinders.add(wrappedPathfinder) proxies[pathfinder] = CombinedPathfinder.Cache() } else { this.bQ.a(pathfinderCounter++, pathfinder as PathfinderGoal) this.cachedPathfinders.add(pathfinder) } } this.bQ.a(pathfinderCounter++, hyperPathfinder) this.cachedPathfinders.add(hyperPathfinder) } /** * Gets called on move to play sounds. */ override fun b(blockposition: BlockPosition, iblockdata: IBlockData) { if (petDesign == null) { return } if (!this.aQ()) { // IsInWater. petDesign!!.proxy.playMovementEffects() } } /** * Disable health. */ override fun c(f: Float) { } /** * Gets the bukkit entity. */ override fun getBukkitEntity(): CraftPet { if (this.entityBukkit == null) { entityBukkit = CraftPet(Bukkit.getServer() as CraftServer, this) val field = Entity::class.java.getDeclaredField("bukkitEntity") field.isAccessible = true field.set(this, entityBukkit) } return this.entityBukkit as CraftPet } override fun e(): Entity? { return null } /** * Clears all entity aiGoals. */ private fun clearAIGoals() { if (initialClear) { val dField = PathfinderGoalSelector::class.java.getDeclaredField("d") dField.isAccessible = true (dField.get(this.bQ) as MutableSet<*>).clear() (dField.get(this.bR) as MutableSet<*>).clear() initialClear = false } for (pathfinder in cachedPathfinders) { this.bQ.a(pathfinder) } this.cachedPathfinders.clear() } }
apache-2.0
f50c24d09af829475ed6e3cf60ab978b
33.924138
136
0.653633
4.328205
false
false
false
false
Magneticraft-Team/Magneticraft
ignore/test/block/BlockTableSieve.kt
2
1841
package block import com.cout970.magneticraft.tileentity.TileTableSieve import com.cout970.magneticraft.util.vector.toAABBWith import com.teamwizardry.librarianlib.common.base.block.BlockModContainer import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.world.IBlockAccess import net.minecraft.world.World /** * Created by cout970 on 13/06/2016. */ object BlockTableSieve : BlockModContainer("table_sieve", Material.WOOD) { val TABLE_SIEVE_BOX = Vec3d.ZERO toAABBWith Vec3d(1.0, 9.0 / 16.0, 1.0) override fun getBoundingBox(state: IBlockState?, source: IBlockAccess?, pos: BlockPos?) = TABLE_SIEVE_BOX override fun isFullBlock(state: IBlockState?) = false override fun isOpaqueCube(state: IBlockState?) = false override fun isFullCube(state: IBlockState?) = false override fun isVisuallyOpaque() = false override fun onBlockActivated(world: World, pos: BlockPos, state: IBlockState, player: EntityPlayer, hand: EnumHand, heldItem: ItemStack?, side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { if (heldItem != null) { val tile = world.getTileEntity(pos) as TileTableSieve if (tile.getRecipe(heldItem) != null) { val inserted = tile.inventory.insertItem(0, heldItem, false) player.setHeldItem(hand, inserted) return true } } return false } override fun createTileEntity(world: World, state: IBlockState): TileEntity? = TileTableSieve() }
gpl-2.0
507219d6c56ea839e71bbc6b7f52aa9b
39.043478
211
0.73547
4.064018
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/delegates/ClientModuleDelegate.kt
1
5273
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.support.delegates import groovy.lang.Closure import org.gradle.api.Action import org.gradle.api.artifacts.ClientModule import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.DependencyArtifact import org.gradle.api.artifacts.ExcludeRule import org.gradle.api.artifacts.ExternalDependency import org.gradle.api.artifacts.ExternalModuleDependency import org.gradle.api.artifacts.ModuleDependency import org.gradle.api.artifacts.ModuleVersionSelector import org.gradle.api.artifacts.ModuleDependencyCapabilitiesHandler import org.gradle.api.artifacts.ModuleIdentifier import org.gradle.api.artifacts.ModuleVersionIdentifier import org.gradle.api.artifacts.MutableVersionConstraint import org.gradle.api.artifacts.VersionConstraint import org.gradle.api.attributes.AttributeContainer import org.gradle.api.capabilities.Capability /** * Facilitates the implementation of the [ClientModule] interface by delegation via subclassing. * * See [GradleDelegate] for why this is currently necessary. */ abstract class ClientModuleDelegate : ClientModule { internal abstract val delegate: ClientModule override fun getGroup(): String = /** Because this also implements [ModuleVersionSelector.getGroup] it must not return `null` */ (delegate as Dependency).group ?: "" override fun addDependency(dependency: ModuleDependency) = delegate.addDependency(dependency) override fun getName(): String = delegate.name override fun getExcludeRules(): MutableSet<ExcludeRule> = delegate.excludeRules override fun addArtifact(artifact: DependencyArtifact): ModuleDependency = delegate.addArtifact(artifact) override fun artifact(configureClosure: Closure<Any>): DependencyArtifact = delegate.artifact(configureClosure) override fun artifact(configureAction: Action<in DependencyArtifact>): DependencyArtifact = delegate.artifact(configureAction) override fun getAttributes(): AttributeContainer = delegate.attributes override fun capabilities(configureAction: Action<in ModuleDependencyCapabilitiesHandler>): ModuleDependency = delegate.capabilities(configureAction) override fun version(configureAction: Action<in MutableVersionConstraint>) = delegate.version(configureAction) override fun getId(): String = delegate.id override fun getTargetConfiguration(): String? = delegate.targetConfiguration override fun copy(): ClientModule = delegate.copy() override fun attributes(configureAction: Action<in AttributeContainer>): ModuleDependency = delegate.attributes(configureAction) override fun matchesStrictly(identifier: ModuleVersionIdentifier): Boolean = delegate.matchesStrictly(identifier) override fun isChanging(): Boolean = delegate.isChanging override fun getVersion(): String? = delegate.version override fun isTransitive(): Boolean = delegate.isTransitive override fun setTransitive(transitive: Boolean): ModuleDependency = delegate.setTransitive(transitive) override fun setForce(force: Boolean): ExternalDependency = delegate.setForce(force) override fun contentEquals(dependency: Dependency): Boolean = delegate.contentEquals(dependency) override fun getRequestedCapabilities(): MutableList<Capability> = delegate.requestedCapabilities override fun getVersionConstraint(): VersionConstraint = delegate.versionConstraint override fun getModule(): ModuleIdentifier = delegate.module override fun getArtifacts(): MutableSet<DependencyArtifact> = delegate.artifacts override fun setTargetConfiguration(name: String?) { delegate.targetConfiguration = name } override fun setChanging(changing: Boolean): ExternalModuleDependency = delegate.setChanging(changing) override fun isForce(): Boolean = delegate.isForce override fun getDependencies(): MutableSet<ModuleDependency> = delegate.dependencies override fun because(reason: String?) = delegate.because(reason) override fun exclude(excludeProperties: Map<String, String>): ModuleDependency = delegate.exclude(excludeProperties) override fun getReason(): String? = delegate.reason override fun inheritStrictVersions() = delegate.inheritStrictVersions() override fun doNotInheritStrictVersions() = delegate.doNotInheritStrictVersions() override fun isInheriting() = delegate.isInheriting }
apache-2.0
6f31a9bf53ac55aeef8fc42df600adc8
33.019355
114
0.751754
5.246766
false
true
false
false
wireapp/wire-android
storage/src/main/kotlin/com/waz/zclient/storage/db/accountdata/ActiveAccountsDao.kt
1
1229
package com.waz.zclient.storage.db.accountdata import androidx.room.Dao import androidx.room.Insert import androidx.room.Query //TODO: Add dao instrumentation tests @Dao interface ActiveAccountsDao { @Query("SELECT access_token from ActiveAccounts WHERE _id = :userId") suspend fun accessToken(userId: String): AccessTokenEntity? @Query("UPDATE ActiveAccounts SET access_token = :accessToken WHERE _id = :userId") suspend fun updateAccessToken(userId: String, accessToken: AccessTokenEntity) @Query("SELECT cookie from ActiveAccounts WHERE _id = :userId") suspend fun refreshToken(userId: String): String? @Query("UPDATE ActiveAccounts SET cookie = :refreshToken WHERE _id = :userId") suspend fun updateRefreshToken(userId: String, refreshToken: String) @Query("SELECT * from ActiveAccounts") suspend fun activeAccounts(): List<ActiveAccountsEntity> @Query("SELECT * from ActiveAccounts WHERE _id = :id LIMIT 1") suspend fun activeAccountById(id: String): ActiveAccountsEntity? @Insert suspend fun insertActiveAccount(activeAccountsEntity: ActiveAccountsEntity) @Query("DELETE from ActiveAccounts WHERE _id = :id") suspend fun removeAccount(id: String) }
gpl-3.0
a27690b13b2f061ff2fad1205bc4e1eb
35.147059
87
0.752644
4.585821
false
false
false
false
mozilla-mobile/focus-android
app/src/androidTest/java/org/mozilla/focus/activity/SitePermissionsTest.kt
1
8911
/* 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.activity import android.Manifest import android.content.Context import android.hardware.camera2.CameraManager import androidx.test.rule.GrantPermissionRule import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Assume import org.junit.Before import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.mozilla.focus.activity.robots.homeScreen import org.mozilla.focus.activity.robots.searchScreen import org.mozilla.focus.helpers.FeatureSettingsHelper import org.mozilla.focus.helpers.MainActivityFirstrunTestRule import org.mozilla.focus.helpers.MockLocationUpdatesRule import org.mozilla.focus.helpers.MockWebServerHelper import org.mozilla.focus.helpers.TestAssetHelper.getGenericAsset import org.mozilla.focus.helpers.TestAssetHelper.getMediaTestAsset import org.mozilla.focus.helpers.TestHelper.exitToTop import org.mozilla.focus.helpers.TestHelper.getTargetContext import org.mozilla.focus.helpers.TestHelper.grantAppPermission import org.mozilla.focus.helpers.TestHelper.waitingTime import org.mozilla.focus.testAnnotations.SmokeTest class SitePermissionsTest { private lateinit var webServer: MockWebServer private val featureSettingsHelper = FeatureSettingsHelper() /* Test page created and handled by the Mozilla mobile test-eng team */ private val permissionsPage = "https://mozilla-mobile.github.io/testapp/permissions" private val testPageSubstring = "https://mozilla-mobile.github.io:443" private val cameraManager = getTargetContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager @get: Rule val mActivityTestRule = MainActivityFirstrunTestRule(showFirstRun = false) @get:Rule val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant( Manifest.permission.ACCESS_COARSE_LOCATION, ) @get: Rule val mockLocationUpdatesRule = MockLocationUpdatesRule() @Before fun setUp() { featureSettingsHelper.setCfrForTrackingProtectionEnabled(false) featureSettingsHelper.setSearchWidgetDialogEnabled(false) webServer = MockWebServer().apply { dispatcher = MockWebServerHelper.AndroidAssetDispatcher() start() } } @After fun tearDown() { webServer.shutdown() featureSettingsHelper.resetAllFeatureFlags() } @Test fun sitePermissionsSettingsItemsTest() { homeScreen { }.openMainMenu { }.openSettings { }.openPrivacySettingsMenu { }.clickSitePermissionsSettings { verifySitePermissionsItems() } } @SmokeTest @Test fun autoplayPermissionsSettingsItemsTest() { homeScreen { }.openMainMenu { }.openSettings { }.openPrivacySettingsMenu { }.clickSitePermissionsSettings { openAutoPlaySettings() verifyAutoplaySection() } } // Tests the default autoplay setting: Block audio only on a video with autoplay attribute and not muted @SmokeTest @Test fun blockAudioAutoplayPermissionTest() { val videoPage = getMediaTestAsset(webServer, "videoPage") searchScreen { }.loadPage(videoPage.url) { progressBar.waitUntilGone(waitingTime) // an un-muted video won't be able to autoplay with this setting, so we have to press play clickPlayButton() waitForPlaybackToStart() } } // Tests the default autoplay setting: Block audio only on a video with autoplay and muted attributes @SmokeTest @Test fun blockAudioAutoplayPermissionOnMutedVideoTest() { val mutedVideoPage = getMediaTestAsset(webServer, "mutedVideoPage") searchScreen { }.loadPage(mutedVideoPage.url) { // a muted video will autoplay with this setting waitForPlaybackToStart() } } // Tests the autoplay setting: Allow audio and video on a video with autoplay attribute and not muted @SmokeTest @Test fun allowAudioVideoAutoplayPermissionTest() { val videoPage = getMediaTestAsset(webServer, "videoPage") homeScreen { }.openMainMenu { }.openSettings { }.openPrivacySettingsMenu { }.clickSitePermissionsSettings { openAutoPlaySettings() selectAllowAudioVideoAutoplay() exitToTop() } searchScreen { }.loadPage(videoPage.url) { waitForPlaybackToStart() } } // Tests the autoplay setting: Allow audio and video on a video with autoplay and muted attributes @SmokeTest @Test fun allowAudioVideoAutoplayPermissionOnMutedVideoTest() { val genericPage = getGenericAsset(webServer) val mutedVideoPage = getMediaTestAsset(webServer, "mutedVideoPage") homeScreen { }.openMainMenu { }.openSettings { }.openPrivacySettingsMenu { }.clickSitePermissionsSettings { openAutoPlaySettings() selectAllowAudioVideoAutoplay() exitToTop() } searchScreen { }.loadPage(genericPage.url) { }.clearBrowsingData {} searchScreen { }.loadPage(mutedVideoPage.url) { waitForPlaybackToStart() } } // Tests the autoplay setting: Block audio and video @SmokeTest @Test fun blockAudioVideoAutoplayPermissionTest() { val videoPage = getMediaTestAsset(webServer, "videoPage") homeScreen { }.openMainMenu { }.openSettings { }.openPrivacySettingsMenu { }.clickSitePermissionsSettings { openAutoPlaySettings() selectBlockAudioVideoAutoplay() exitToTop() } searchScreen { }.loadPage(videoPage.url) { clickPlayButton() waitForPlaybackToStart() } } @SmokeTest @Test fun cameraPermissionsSettingsItemsTest() { homeScreen { }.openMainMenu { }.openSettings { }.openPrivacySettingsMenu { }.clickSitePermissionsSettings { openCameraPermissionsSettings() verifyPermissionsStateSettings() verifyAskToAllowChecked() verifyBlockedByAndroidState() } } @SmokeTest @Test fun locationPermissionsSettingsItemsTest() { homeScreen { }.openMainMenu { }.openSettings { }.openPrivacySettingsMenu { }.clickSitePermissionsSettings { openLocationPermissionsSettings() verifyPermissionsStateSettings() verifyAskToAllowChecked() verifyBlockedByAndroidState() } } @Test fun testLocationSharingNotAllowed() { searchScreen { }.loadPage(permissionsPage) { clickGetLocationButton() verifyLocationPermissionPrompt(testPageSubstring) denySitePermissionRequest() verifyPageContent("User denied geolocation prompt") } } @SmokeTest @Test fun testLocationSharingAllowed() { mockLocationUpdatesRule.setMockLocation() searchScreen { }.loadPage(permissionsPage) { clickGetLocationButton() verifyLocationPermissionPrompt(testPageSubstring) allowSitePermissionRequest() verifyPageContent("${mockLocationUpdatesRule.latitude}") verifyPageContent("${mockLocationUpdatesRule.longitude}") } } @Ignore( "Camera not available on some AVDs: " + "https://github.com/mozilla-mobile/mobile-test-eng/issues/622", ) @SmokeTest @Test fun allowCameraPermissionsTest() { Assume.assumeTrue(cameraManager.cameraIdList.isNotEmpty()) searchScreen { }.loadPage(permissionsPage) { clickGetCameraButton() grantAppPermission() verifyCameraPermissionPrompt(testPageSubstring) allowSitePermissionRequest() verifyPageContent("Camera allowed") } } @Ignore( "Camera not available on some AVDs: " + "https://github.com/mozilla-mobile/mobile-test-eng/issues/622", ) @SmokeTest @Test fun denyCameraPermissionsTest() { Assume.assumeTrue(cameraManager.cameraIdList.isNotEmpty()) searchScreen { }.loadPage(permissionsPage) { clickGetCameraButton() grantAppPermission() verifyCameraPermissionPrompt(testPageSubstring) denySitePermissionRequest() verifyPageContent("Camera not allowed") } } }
mpl-2.0
af982931a729535896da68960cb92095
30.939068
108
0.666367
5.597362
false
true
false
false
Caellian/Math
src/main/kotlin/hr/caellian/math/matrix/MatrixD.kt
1
21127
package hr.caellian.math.matrix import hr.caellian.math.internal.DataUtil.transpose import hr.caellian.math.vector.VectorD import hr.caellian.math.vector.VectorN import java.nio.Buffer import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.DoubleBuffer import kotlin.math.cos import kotlin.math.roundToInt import kotlin.math.sin /** * Matrix class for double N-dimensional matrices. * * @author Caellian */ class MatrixD(override var wrapped: Array<Array<Double>> = emptyArray(), vertical: Boolean = false) : MatrixN<Double>() { init { require(rowCount > 1 && columnCount > 1) { "Invalid matrix size!" } require(validate()) { if (vertical) "Matrix columns must be of equal length!" else "Matrix rows must be of equal length!" } if (vertical) { wrapped = transpose().wrapped } } /** * Creates a new blank square matrix. * * @param size width & height of new matrix. */ constructor(size: Int, default: Double = 0.0) : this(Array(size) { _ -> Array(size) { default } }) /** * Creates a new matrix containing given data. * * @param rows number of rows matrix should store. * @param columns number of columns matrix should store. */ constructor(rows: Int, columns: Int, default: Double = 0.0) : this(Array(rows) { _ -> Array(columns) { default } }) /** * Creates a new matrix using collection values. * * @param values values to create a new matrix from. * @return created matrix. */ constructor(values: Collection<Collection<Double>>) : this(values.map { it.toTypedArray() }.toTypedArray()) /** * Creates a new matrix using buffer values. * * @param buffer buffer to create a new matrix from. * @param rowCount number of rows new matrix will have. * @param columnCount number of columns new matrix will have. * @return created matrix. */ constructor(buffer: DoubleBuffer, rowCount: Int, columnCount: Int) : this( Array(rowCount) { _ -> Array(columnCount) { buffer.get() } }) /** * Creates a new square matrix using buffer values. * * This constructor depends on buffer capacity. Make sure square root of your buffer's capacity is equal to row and * column count. * * @param buffer buffer to create a new matrix from. * @return created matrix. */ constructor(buffer: DoubleBuffer) : this( buffer.let { _ -> val rows = Math.sqrt(buffer.capacity().toDouble()) require(rows - rows.roundToInt() == 0.0) { "Acquired buffer can't be used to create a square matrix." } val rowCount = rows.roundToInt() Array(rowCount) { _ -> Array(rowCount) { buffer.get() } } } ) /** * @return new matrix with negated values. */ override fun unaryMinus() = MatrixD( Array(rowCount) { row -> Array(columnCount) { column -> -wrapped[row][column] } }) /** * Performs matrix addition and returns resulting matrix. * In order to add to matrices together, they must be of same size. * * @param other matrix to add to this one. * @return resulting of matrix addition. */ override fun plus(other: MatrixN<Double>): MatrixD { require(rowCount == other.rowCount && columnCount == other.columnCount) { "Invalid argument matrix size: ${other.rowCount}x${other.columnCount}!" } return MatrixD( Array(rowCount) { row -> Array(columnCount) { column -> wrapped[row][column] + other[row][column] } }) } /** * Performs matrix subtraction and returns resulting matrix. * In order to subtract one matrix from another, matrices must be of same size. * * @param other matrix to subtract from this one. * @return resulting of matrix subtraction. */ override fun minus(other: MatrixN<Double>): MatrixD { require(rowCount == other.rowCount && columnCount == other.columnCount) { "Invalid argument matrix size: ${other.rowCount}x${other.columnCount}!" } return MatrixD( Array(rowCount) { row -> Array(columnCount) { column -> wrapped[row][column] - other[row][column] } }) } /** * Performs matrix multiplication on this matrix. * Returns C from 'C = A×B' where A is this matrix and B is the other / argument matrix. * * @param other matrix to multiply this matrix with. * @return result of matrix multiplication. */ override operator fun times(other: MatrixN<Double>): MatrixD { require(columnCount == other.rowCount) { "Invalid multiplication (mat${rowCount}x$columnCount) * (mat${other.rowCount}x${other.columnCount})!" } return MatrixD(Array(rowCount) { row -> Array(other.columnCount) { column -> (0 until columnCount).sumByDouble { wrapped[row][it] * other.wrapped[it][column] } } }) } /** * Performs matrix multiplication on this matrix. * Returns C from 'C = A×B' where A is this matrix and B is the other / argument vector. * * @param other vector to multiply this matrix with. * @return result of matrix multiplication. */ override fun times(other: VectorN<Double>): VectorD = (this * other.verticalMatrix as MatrixN<Double>).toVector() /** * Performs scalar multiplication on this matrix and returns resulting matrix. * * @param scalar scalar to multiply every member of this matrix with. * @return result of scalar matrix multiplication. */ override operator fun times(scalar: Double): MatrixD { return MatrixD(Array(rowCount) { row -> Array(columnCount) { column -> wrapped[row][column] * scalar } }) } /** * Switches two rows together. * * @param rowA row to be switched with rowB. * @param rowB row to be switched with rowA. * @return resulting matrix. */ override fun switchRows(rowA: Int, rowB: Int): MatrixD { require(rowA in 0..rowCount && rowB in 0..rowCount && rowA != rowB) { "Illegal row argument(s)!" } return MatrixD(Array(rowCount) { row -> Array(columnCount) { column -> when (row) { rowA -> wrapped[rowB][column] rowB -> wrapped[rowA][column] else -> wrapped[row][column] } } }) } /** * Switches two columns together. * * @param columnA column to be switched with columnB. * @param columnB column to be switched with columnA. * @return resulting matrix. */ override fun switchColumns(columnA: Int, columnB: Int): MatrixD { require(columnA in 0..columnCount && columnB in 0..columnCount && columnA != columnB) { "Illegal column argument(s)!" } return MatrixD(Array(rowCount) { row -> Array(columnCount) { column -> when (column) { columnA -> wrapped[row][columnB] columnB -> wrapped[row][columnA] else -> wrapped[row][column] } } }) } /** * Multiplies all entries of a row with given scalar. * * @param row row to multiply. * @param multiplier scalar to multiply rows entries with. * @return resulting matrix. */ override fun multiplyRow(row: Int, multiplier: Double): MatrixD { require(row in 0..rowCount) { "Illegal row argument!" } return MatrixD(Array(rowCount) { rowI -> Array(columnCount) { column -> when (rowI) { row -> wrapped[rowI][column] * multiplier else -> wrapped[rowI][column] } } }) } /** * Multiplies all entries of a column with given scalar. * * @param column column to multiply. * @param multiplier scalar to multiply column entries with. * @return resulting matrix. */ override fun multiplyColumn(column: Int, multiplier: Double): MatrixD { require(column in 0..columnCount) { "Illegal row argument!" } return MatrixD(Array(rowCount) { row -> Array(columnCount) { columnI -> when (columnI) { column -> wrapped[row][columnI] * multiplier else -> wrapped[row][columnI] } } }) } /** * Adds one row from matrix to another. * * @param from row to add to another row. * @param to row to add another row to; data will be stored on this row. * @param multiplier scalar to multiply all members of added row with on addition. It equals to 1 by default. * @return new matrix. */ override fun addRows(from: Int, to: Int, multiplier: Double?): MatrixD { require(from in 0..rowCount && to in 0..rowCount) { "Illegal row argument(s)!" } val multiplierVal = multiplier ?: 1.0 return MatrixD(Array(rowCount) { row -> Array(columnCount) { column -> when (row) { to -> wrapped[to][column] + wrapped[from][column] * multiplierVal else -> wrapped[row][column] } } }) } /** * Adds one column from matrix to another. * * @param from column to add to another column. * @param to column to add another column to; data will be stored on this column. * @param multiplier scalar to multiply all members of added column with on addition. It equals to 1 by default. * @return new matrix. */ override fun addColumns(from: Int, to: Int, multiplier: Double?): MatrixD { require(from in 0..columnCount && to in 0..columnCount) { "Illegal column argument(s)!" } val multiplierVal = multiplier ?: 1.0 return MatrixD(Array(rowCount) { row -> Array(columnCount) { column -> when (column) { to -> wrapped[row][to] + wrapped[row][from] * multiplierVal else -> wrapped[row][column] } } }) } /** * Inserts given row data at given index shifting rest of the matrix to the next index. * * @param index index at which added row data will be stored. * @param data row data to store at given index. * @return new matrix with extended data. */ override fun withRow(index: Int, data: Array<Double>): MatrixD { require(data.size == columnCount) { "Illegal row array size! Should be $columnCount." } return MatrixD(Array(rowCount + 1) { row -> Array(columnCount) { column -> when { row == index -> data[column] row > index -> wrapped[row + 1][column] else -> wrapped[row][column] } } }) } /** * Inserts given column data at given index shifting rest of the matrix to the next index. * * @param index index at which added column data will be stored. * @param data column data to store at given index. * @return new matrix with extended data. */ override fun withColumn(index: Int, data: Array<Double>): MatrixD { require(data.size == rowCount) { "Illegal column array size! Should be $rowCount." } return MatrixD(Array(rowCount) { row -> Array(columnCount + 1) { column -> when { column == index -> data[row] column > index -> wrapped[row][column + 1] else -> wrapped[row][column] } } }) } /** * Creates a new matrix without specified rows & columns. * * @param deletedRows rows to exclude from submatrix. * @param deletedColumns columns to exclude from submatrix. * @return defined submatrix. */ override fun submatrix(deletedRows: Array<Int>, deletedColumns: Array<Int>): MatrixD { require(deletedRows.all { it in 0..rowCount } && deletedColumns.all { it in 0..columnCount }) { "Tried to delete rows which don't exist." } val keptRows = (0..rowCount).toList().filterNot { deletedRows.contains(it) } val keptColumns = (0..columnCount).toList().filterNot { deletedColumns.contains(it) } return MatrixD(Array(keptRows.size) { row -> Array(keptColumns.size) { column -> wrapped[keptRows[row]][keptColumns[column]] } }) } /** * Constructs a new vector out of column / row vector matrix. * * @return vector containing matrix data. */ override fun toVector(): VectorD { require(columnCount == 1 || rowCount == 1 && !(columnCount > 1 && rowCount > 1)) { "Matrix cannot be turned into a vector!" } return if (columnCount > rowCount) { VectorD(firstRow()[0]) } else { VectorD(firstColumn().transpose()[0]) } } /** * Constructs a new vector out of any matrix dismissing extra data. * * @return vector containing only first column of matrix data. */ override fun forceToVector() = VectorD(firstColumn().transpose()[0]) /** * @return a new matrix containing only the first row of this matrix. */ override fun firstRow() = MatrixD( Array(1) { row -> Array(columnCount) { column -> wrapped[row][column] } }) /** * @return a new matrix containing only the first column of this matrix. */ override fun firstColumn() = MatrixD( Array(rowCount) { row -> Array(1) { column -> wrapped[row][column] } }) /** * @return transposed matrix. */ override fun transpose() = MatrixD(wrapped.transpose()) /** * @return buffer containing data of this matrix. */ override fun toBuffer(): Buffer { return ByteBuffer.allocateDirect((columnCount * rowCount) shl 2).order(ByteOrder.nativeOrder()).asDoubleBuffer() .also { buffer -> wrapped.forEach { it.forEach { inner -> buffer.put(inner) } } buffer.flip() } } /** * Returns copy of data of this Matrix as a 2D array. * * @return 2D array containing data of this matrix. */ override fun toArray(): Array<Array<Double>> = Array(rowCount) { row -> Array(columnCount) { column -> wrapped[row][column] } } /** * @return clone of this matrix. */ override fun replicated() = MatrixD(toArray()) /** * @return type supported by this class. */ override fun getTypeClass() = Double::class /** * Creates a new instance of [MatrixD] containing given data. * * @param data data of new wrapper. * @return new instance of wrapper containing argument data. */ override fun withData(wrapped: Array<Array<Double>>) = MatrixD(wrapped) companion object { /** * Initializes a new n-dimensional rotation matrix. * * Unless you're working with 4+ dimensional space, it's recommended you use simpler, dimensionality specific * functions defined in specialised classes as this one is not the fastest for those simpler requirements. * * For details see: <a href="http://wscg.zcu.cz/wscg2004/Papers_2004_Short/N29.pdf">Aguilera - Perez Algorithm</a> * * @param rotationSimplex defining data. Rows of this matrix represent points defining * simplex to perform this rotation around. Points must have their * position in all 'n' dimensions defined and there must be 'n-1' * points to define rotation simplex. * @param angle degrees to rotate by objects multiplied by this rotation matrix. * @return rotation matrix. */ @JvmStatic fun initRotation(rotationSimplex: MatrixD, angle: Double): MatrixD { val n = rotationSimplex.columnCount require(n >= 2) { "Can't do rotation in $n-dimensional space!" } require(rotationSimplex.rowCount == n - 1) { "Insufficient / invalid data! Can't perform rotation." } @Suppress("LocalVariableName") val M = arrayOfNulls<MatrixD>(n * (n - 1) / 2 + 1) val v = arrayOfNulls<MatrixD>(n * (n - 1) / 2 + 1) M[0] = MatrixD.initTranslationMatrix(((-rotationSimplex).firstRow().toVector()).toArray()).transpose() v[0] = rotationSimplex v[1] = (v[0]?.withColumn(n, Array(n - 1) { 1.0 })!! * M[0]!!).submatrix(emptyArray(), arrayOf(n + 1)) var result = MatrixD(M[0]!!.wrapped) var k = 1 for (r in 2 until n) { for (c in n downTo r) { k += 1 M[k - 1] = MatrixD.initPlaneRotation(n + 1, c, c - 1, Math.atan2(v[k - 1]!![r - 1][c - 1], v[k - 1]!![r - 1][c - 2])) v[k] = (v[k - 1]?.withColumn(n, Array(n - 1) { 1.0 })!! * M[k - 1]!!).submatrix(emptyArray(), arrayOf(n + 1)) result *= M[k - 1]!! } } return (result * MatrixD.initPlaneRotation(n + 1, n - 1, n, angle) * result.inverseUnsafe()).submatrix( arrayOf(n + 1), arrayOf(n + 1)) } /** * Initializes a plane rotation matrix. * * @param size size/dimensionality of plane rotation matrix. * @param a rotated axis index. * @param b destination axis index. * @param angle degrees to rotate in objects multiplied by this rotation matrix. * @return plane rotation matrix. */ @JvmStatic fun initPlaneRotation(size: Int, a: Int, b: Int, angle: Double): MatrixD { return MatrixD(Array(size) { row -> Array(size) { column -> when { row == a - 1 && column == a - 1 -> cos(Math.toRadians(angle)) row == b - 1 && column == b - 1 -> cos(Math.toRadians(angle)) row == a - 1 && column == b - 1 -> -sin(Math.toRadians(angle)) row == b - 1 && column == a - 1 -> sin(Math.toRadians(angle)) row == column -> 1.0 else -> 0.0 } } }) } /** * Initializes a new translation matrix using array of axial translations. * * @param location relative location. * @return translation matrix. */ @JvmStatic fun initTranslationMatrix(location: Array<Double>): MatrixD { return MatrixD(Array(location.size + 1) { row -> Array(location.size + 1) { column -> when { row == column -> 1.0 column == location.size && row < location.size -> location[row] else -> 0.0 } } }) } /** * Initializes a new translation matrix using [VectorD]. * * @since 3.0.0 * * @param location relative location. * @return translation matrix. */ @JvmStatic fun initTranslationMatrix(location: VectorD): MatrixD { return MatrixD(Array(location.size + 1) { row -> Array(location.size + 1) { column -> when { row == column -> 1.0 column == location.size && row < location.size -> location[row] else -> 0.0 } } }) } /** * Initializes a new scaling matrix. * * @param scale scale. * @return scale matrix. */ @JvmStatic fun initScalingMatrix(scale: Array<Double>): MatrixD { return MatrixD(Array(scale.size) { row -> Array(scale.size) { column -> if (row == column) scale[row] else 0.0 } }) } /** * Initializes a new identity matrix. * * @param n matrix size. * @return identity matrix. */ @JvmStatic fun initIdentityMatrix(n: Int): MatrixD { return MatrixD(Array(n) { row -> Array(n) { column -> if (row == column) 1.0 else 0.0 } }) } } }
mit
7edcb365b35435116a1671d0aef77c5b
37.202532
155
0.547598
4.540082
false
false
false
false
jainaman224/Algo_Ds_Notes
Naive_String_Matching/Naive_String_Matching.kt
1
769
// Function for Naive_String_Matching fun match(text: String, pattern: String) { for (i in 0 until (text.length - pattern.length + 1)) { for (j in 0 until pattern.length) { if (text[i + j] != pattern[j]) { break } if (j + 1 == pattern.length) { println("Pattern Found at ${i + 1}") } } } } // Driver Function for Naive_String_Matching fun main() { // Taking input of text(String) val text = readLine()!! // Taking input of pattern(String) val pattern = readLine()!! match(text, pattern) } // Input:- Text-> asdf;asdf;asdf; // Pattern-> asdf // Output:- Pattern Found at 1 // Pattern Found at 6 // Pattern Found at 11
gpl-3.0
55363f4b4951a402554872065a83a3e8
26.464286
59
0.530559
3.825871
false
false
false
false
JavaEden/OrchidCore
OrchidCore/src/main/kotlin/com/eden/orchid/StandardModule.kt
1
3088
package com.eden.orchid import com.eden.orchid.api.ApiModule import com.eden.orchid.api.registration.ClasspathModuleInstaller import com.eden.orchid.api.registration.FlagsModule import com.eden.orchid.api.registration.IgnoreModule import com.eden.orchid.impl.ImplModule import com.google.inject.AbstractModule @IgnoreModule class StandardModule private constructor( private val args: Array<String>?, private val flags: Map<String, Any>?, private val includeCoreApi: Boolean, private val includeCoreImpl: Boolean, private val includeFlags: Boolean, private val includeClasspath: Boolean ) : AbstractModule() { override fun configure() { if (includeCoreApi) { install(ApiModule()) } if (includeCoreImpl) { install(ImplModule()) } if (includeFlags) { if (args == null && flags == null) { throw IllegalStateException("A mapping of flags must be provided to use the FlagsModule") } install(FlagsModule(args, flags)) } if (includeClasspath) { install(ClasspathModuleInstaller()) } } class StandardModuleBuilder internal constructor() { private var args: Array<String>? = null private var flags: Map<String, Any>? = null private var includeCoreApi = true private var includeCoreImpl = true private var includeFlags = true private var includeClasspath = true fun args(args: Array<String>): StandardModuleBuilder { this.args = args return this } fun flags(flags: Map<String, Any>): StandardModuleBuilder { this.flags = flags return this } fun includeCoreApi(includeCoreApi: Boolean): StandardModuleBuilder { this.includeCoreApi = includeCoreApi return this } fun includeCoreImpl(includeCoreImpl: Boolean): StandardModuleBuilder { this.includeCoreImpl = includeCoreImpl return this } fun includeFlags(includeFlags: Boolean): StandardModuleBuilder { this.includeFlags = includeFlags return this } fun includeClasspath(includeClasspath: Boolean): StandardModuleBuilder { this.includeClasspath = includeClasspath return this } fun build(): StandardModule { return StandardModule(args, flags, includeCoreApi, includeCoreImpl, includeFlags, includeClasspath) } override fun toString(): String { return "StandardModule.StandardModuleBuilder(args=" + java.util.Arrays.deepToString(this.args) + ", flags=" + this.flags + ", includeCoreApi=" + this.includeCoreApi + ", includeCoreImpl=" + this.includeCoreImpl + ", includeFlags=" + this.includeFlags + ", includeClasspath=" + this.includeClasspath + ")" } } companion object { @JvmStatic fun builder(): StandardModuleBuilder { return StandardModuleBuilder() } } }
mit
7dff8fc9e5cdfcf14015a4a31cfed036
32.934066
316
0.639896
5.553957
false
false
false
false
Kiskae/Twitch-Archiver
ui/src/main/kotlin/net/serverpeon/twitcharchiver/network/ApiWrapper.kt
1
1920
package net.serverpeon.twitcharchiver.network import javafx.beans.binding.BooleanBinding import javafx.beans.property.SimpleObjectProperty import net.serverpeon.twitcharchiver.ReactiveFx import net.serverpeon.twitcharchiver.twitch.LegacyTwitchApi import org.slf4j.LoggerFactory import rx.Observable import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference class ApiWrapper(private val apiLegacy: LegacyTwitchApi) { private val ownerProp: SimpleObjectProperty<Any?> = SimpleObjectProperty(null) private val ownerLock: AtomicReference<Any?> = AtomicReference(null) private val log = LoggerFactory.getLogger(ApiWrapper::class.java) fun hasAccess(lockObj: Any): BooleanBinding { return ownerProp.isNull.or(ownerProp.isEqualTo(lockObj)) } fun <T> request(lockObj: Any, f: LegacyTwitchApi.() -> Observable<T>): Observable<T> { if (setLock(lockObj)) { return apiLegacy.f() .doOnError { log.warn("Error in request", it) } .observeOn(ReactiveFx.scheduler) .doOnUnsubscribe { // Create request and unlock check(setLock(null)) } } else { return Observable.empty() } } fun lock(lockObj: Any): AutoCloseable? { if (setLock(lockObj)) { return AutoCloseable { setLock(null) } } else { return null } } private fun setLock(value: Any?): Boolean { log.debug("Api lock: {} -> {}", ownerLock, value) val success = if (value != null) { ownerLock.compareAndSet(null, value) } else { ownerLock.getAndSet(null) != null } if (success) { ownerProp.set(value) return true } else { return false; } } }
mit
04f8924c1d303c52cdf80496015ee951
31.016667
90
0.6125
4.626506
false
false
false
false
angryziber/picasa-gallery
src/views/head.kt
1
1850
package views import integration.Profile import photos.Config import photos.Config.startTime import web.RequestProps // language=HTML fun head(req: RequestProps, profile: Profile) = """ ${req.urlSuffix.isNotEmpty() / """<meta name="robots" content="noindex">"""} <meta property="fb:admins" content="${profile.slug}"/> <meta name="viewport" content="width=device-width"> <meta name="mobile-web-app-capable" content="yes"> <meta name="theme-color" content="#313131"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="apple-touch-icon" href="/img/picasa-logo.png"/> <link rel="shortcut icon" href="/img/picasa-logo.png"> <link rel="manifest" href="/manifest.json"> <link rel="stylesheet" type="text/css" href="/css/reset.css"> <link rel="stylesheet" type="text/css" href="/css/gallery.css?$startTime"> <link rel="stylesheet" type="text/css" href="/css/scrollbars.css?$startTime"> <link rel="stylesheet" type="text/css" href="/css/loader.css?$startTime"> <script src="/js/jquery.min.js"></script> <script src="/js/prefixfree.min.js"></script> <script src="/js/common.js?$startTime"></script> <script src="/js/thumbs.js?$startTime"></script> ${!req.bot / """ <script defer src="/js/chromecast.js"></script> <script defer src="//maps.google.com/maps/api/js?key=${Config.mapsKey}"></script> """} ${Config.analyticsId / """ <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '${Config.analyticsId}', 'auto'); ga('send', 'pageview'); </script> """} """
gpl-3.0
fbd57bf6a937cf80b423af33399712a5
37.541667
89
0.683784
3.003247
false
true
false
false
DataDog/integrations-core
sonarqube/tests/docker/project/src/kotlin/sample.kt
1
430
fun vulnerableFunction() { val password = "password" // Vulnerability - hardcoded password if (!password.isNull()) println("null password!") } // Code Smell - Empty function fun emptyFunction() { } fun buggyFunction(str: String){ if (str == "hello"){ println("Hello!") } else if (str == "goodbye"){ println("Goodbye!") } else if (str == "hello"){ // Bug - Duplicate condition println("Hello again!") } }
bsd-3-clause
748d589dd2173fe3a90c15c25d5a349f
22.888889
65
0.632558
3.77193
false
false
false
false
JavaEden/OrchidCore
plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/GroovydocGenerator.kt
1
4602
package com.eden.orchid.groovydoc import com.copperleaf.groovydoc.json.models.GroovydocPackageDoc import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.generators.OrchidCollection import com.eden.orchid.api.generators.OrchidGenerator import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.annotations.StringDefault import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.groovydoc.helpers.OrchidGroovydocInvoker import com.eden.orchid.groovydoc.models.GroovydocModel import com.eden.orchid.groovydoc.pages.GroovydocClassPage import com.eden.orchid.groovydoc.pages.GroovydocPackagePage import java.util.ArrayList import java.util.HashMap import java.util.stream.Stream import javax.inject.Inject @Description( "Creates a page for each Class and Package in your project, displaying the expected Groovydoc information " + "of methods, fields, etc. but in your site's theme.", name = "Groovydoc" ) class GroovydocGenerator @Inject constructor( context: OrchidContext, private val model: GroovydocModel, private val groovydocInvoker: OrchidGroovydocInvoker ) : OrchidGenerator(context, GENERATOR_KEY, OrchidGenerator.PRIORITY_EARLY) { companion object { const val GENERATOR_KEY = "groovydoc" } @Option @StringDefault("../../main/groovy", "../../main/java") @Description("The source directories with Kotlin files to document.") lateinit var sourceDirs: List<String> @Option @Description("Arbitrary command line arguments to pass through directly to Groovydoc.") lateinit var args: List<String> override fun startIndexing(): List<OrchidPage> { groovydocInvoker.extractOptions(context, allData) val rootDoc = groovydocInvoker.getRootDoc(sourceDirs, args) if (rootDoc == null) return ArrayList() model.initialize(ArrayList(), ArrayList()) for (classDoc in rootDoc.classes) { model.allClasses.add(GroovydocClassPage(context, classDoc, model)) } val packagePageMap = HashMap<String, GroovydocPackagePage>() for (packageDoc in rootDoc.packages) { val classesInPackage = ArrayList<GroovydocClassPage>() for (classDocPage in model.allClasses) { if (classDocPage.classDoc.`package` == packageDoc.name) { classesInPackage.add(classDocPage) } } classesInPackage.sortBy { it.title } val packagePage = GroovydocPackagePage(context, packageDoc, classesInPackage) model.allPackages.add(packagePage) packagePageMap[packageDoc.name] = packagePage } for (packagePage in packagePageMap.values) { for (possibleInnerPackage in packagePageMap.values) { if (isInnerPackage(packagePage.packageDoc, possibleInnerPackage.packageDoc)) { packagePage.innerPackages.add(possibleInnerPackage) } } } for (classDocPage in model.allClasses) { classDocPage.packagePage = packagePageMap[classDocPage.classDoc.`package`] } return model.allPages } override fun startGeneration(pages: Stream<out OrchidPage>) { pages.forEach { context.renderTemplate(it) } } override fun getCollections(): List<OrchidCollection<*>>? { val collections = ArrayList<OrchidCollection<*>>() collections.add(GroovydocCollection(this, "classes", model.allClasses)) collections.add(GroovydocCollection(this, "packages", model.allPackages)) return collections } private fun isInnerPackage(parent: GroovydocPackageDoc, possibleChild: GroovydocPackageDoc): Boolean { // packages start the same... if (possibleChild.name.startsWith(parent.name)) { // packages are not the same... if (possibleChild.name != parent.name) { val parentSegmentCount = parent.name.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size val possibleChildSegmentCount = possibleChild.name.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size // child has one segment more than the parent, so is immediate child if (possibleChildSegmentCount == parentSegmentCount + 1) { return true } } } return false } }
mit
327862abff22205889cf8907e9467153
34.960938
113
0.67601
4.943072
false
false
false
false
Kotlin/dokka
plugins/base/src/main/kotlin/transformers/pages/merger/PageMerger.kt
1
1699
package org.jetbrains.dokka.base.transformers.pages.merger import org.jetbrains.dokka.base.DokkaBase import org.jetbrains.dokka.pages.PageNode import org.jetbrains.dokka.pages.RootPageNode import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.plugability.plugin import org.jetbrains.dokka.plugability.query import org.jetbrains.dokka.transformers.pages.PageTransformer class PageMerger(context: DokkaContext) : PageTransformer { private val strategies: Iterable<PageMergerStrategy> = context.plugin<DokkaBase>().query { pageMergerStrategy } override fun invoke(input: RootPageNode): RootPageNode = input.modified(children = input.children.map { it.mergeChildren(emptyList()) }) private fun PageNode.mergeChildren(path: List<String>): PageNode = children.groupBy { it::class }.map { it.value.groupBy { it.name }.map { (n, v) -> mergePageNodes(v, path + n) }.map { it.assertSingle(path) } }.let { pages -> modified(children = pages.flatten().map { it.mergeChildren(path + it.name) }) } private fun mergePageNodes(pages: List<PageNode>, path: List<String>): List<PageNode> = strategies.fold(pages) { acc, strategy -> tryMerge(strategy, acc, path) } private fun tryMerge(strategy: PageMergerStrategy, pages: List<PageNode>, path: List<String>) = if (pages.size > 1) strategy.tryMerge(pages, path) else pages } private fun <T> Iterable<T>.assertSingle(path: List<String>): T = try { single() } catch (e: Exception) { val renderedPath = path.joinToString(separator = "/") throw IllegalStateException("Page merger is misconfigured. Error for $renderedPath: ${e.message}") }
apache-2.0
a8e4fee51bead5b1a9054c3a6e9be852
46.222222
115
0.723367
4.045238
false
false
false
false
vase4kin/TeamCityApp
app/src/main/java/com/github/vase4kin/teamcityapp/buildlog/urlprovider/BuildLogUrlProviderImpl.kt
1
1386
/* * Copyright 2020 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.buildlog.urlprovider import com.github.vase4kin.teamcityapp.buildlog.data.BuildLogInteractor /** * Impl of [BuildLogUrlProvider] */ class BuildLogUrlProviderImpl( private val buildLogInteractor: BuildLogInteractor ) : BuildLogUrlProvider { /** * {@inheritDoc} */ override fun provideUrl(): String { val userAccount = buildLogInteractor.activeUser val serverUrl = String.format( BUILD_URL, userAccount.teamcityUrl, buildLogInteractor.buildId ) return if (userAccount.isGuestUser) "$serverUrl&guest=1" else serverUrl } companion object { private const val BUILD_URL = "%s/viewLog.html?buildId=%s&tab=buildLog" } }
apache-2.0
a2070ee37640d3872025e68bf59bf0d4
29.130435
79
0.694805
4.304348
false
false
false
false
mmorihiro/larger-circle
core/src/mmorihiro/matchland/controller/TouchAction.kt
2
4772
package mmorihiro.matchland.controller import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.math.MathUtils.random import ktx.actors.alpha import mmorihiro.matchland.controller.appwarp.WarpPuzzleView import mmorihiro.matchland.model.ItemType import mmorihiro.matchland.model.Point import mmorihiro.matchland.model.PuzzleModel import mmorihiro.matchland.view.ConnectEvent import mmorihiro.matchland.view.MyImage import mmorihiro.matchland.view.Puzzle import mmorihiro.matchland.view.PuzzleView fun touchAction(view: Puzzle, x: Int, y: Int) = view.run { if (connectEvent != null) return val touchedPoint = coordinateToPoint(x, y) if (view is WarpPuzzleView && view.enemyConnected.contains(touchedPoint)) return val touchedItem = try { items[touchedPoint.second][touchedPoint.first] } catch (e: IndexOutOfBoundsException) { return } val sameTypeGroup = sameTypeGroup(view, touchedItem.type, touchedPoint) connectEvent = if (view is PuzzleView) { val point = enemyPoint(view, sameTypeGroup) ConnectEvent( listOf(touchedPoint), sameTypeGroup, // 敵のアイコン sameTypeGroup(view, items[point.second][point.first].type, point) .take(3 + view.level).toList()) } else ConnectEvent(listOf(touchedPoint), sameTypeGroup, listOf()) touchEffect(touchedItem) } private fun enemyPoint(view: PuzzleView, sameTypeGroup: Set<Point>, count: Int = 1): Point = view.run { val point = random(rowSize - 1) to random(colSize - 1) val itemType = items[point.second][point.first].type val tileType = tiles[point.second][point.first].type when { count >= 20 -> true sameTypeGroup.contains(point) || itemType == playerType.position -> false level >= 3 && sameTypeGroup(view, itemType, point).size < 3 -> false level >= 6 && itemType == enemyType.position && tileType == playerType.position -> false level >= 9 && itemType == ItemType.WATER.position && tileType != playerType.position -> false else -> true }.let { if (it) point else enemyPoint(view, sameTypeGroup, count + 1) } } private fun sameTypeGroup(view: Puzzle, type: Point, point: Point): Set<Point> = view.run { // 同じ種類のアイテムの座標のリスト val points = items.mapIndexed { yIndex, row -> row.mapIndexed { xIndex, item -> (xIndex to yIndex) to item.type } .filter { it.second == type } .map { it.first } }.flatten() return PuzzleModel().sameTypeGroup(points).find { it.contains(point) }!! } private fun touchEffect(image: MyImage) { image.color = Color(0.5f, 0.5f, 0.5f, 0.7f) } fun onTouchUp(view: Puzzle, touchUp: (ConnectEvent) -> Unit, notEnough: () -> Unit = {}) { view.connectEvent?.let { view.connectEvent = null val size = it.connectedItems.size if (size <= 2) { view.resetIcons(it.connectedItems) notEnough() } else touchUp(it) } } fun onTouchDragged(view: Puzzle, x: Int, y: Int, onConnect: () -> Unit = {}, onNotConnect: (Float, Float) -> Unit = { _, _ -> }): Unit = view.run { connectEvent?.let { val point = coordinateToPoint(x, y) val item = try { items[point.second][point.first] } catch (e: IndexOutOfBoundsException) { return } if (item.alpha == 0f) return // やり直す時 if (it.connectedItems.size >= 2 && point == it.connectedItems[it.connectedItems.lastIndex - 1]) { val point1 = it.connectedItems.last() connectEvent = it.copy(connectedItems = it.connectedItems.dropLast(1)) val item1 = items[point1.second][point1.first] item1.color = Color.WHITE onNotConnect(item1.x, item1.y) } if (canConnect(it, point, item, x, y)) { touchEffect(item) connectEvent = it.copy(connectedItems = it.connectedItems + point) onConnect() } } } private fun canConnect(event: ConnectEvent, point: Point, item: MyImage, x: Int, y: Int): Boolean = event.sameTypeGroup.contains(point) && !event.connectedItems.contains(point) // 接しているかどうか && PuzzleModel() .getAround(event.connectedItems.last(), listOf(point)) .isNotEmpty() && item.circle().contains(x.toFloat(), y.toFloat())
apache-2.0
87545d30a0f74bb880ab6d511e214322
36.309524
101
0.599574
4.104803
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/browser/history/ViewHistory.kt
1
599
package jp.toastkid.yobidashi.browser.history import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import jp.toastkid.yobidashi.browser.UrlItem /** * ViewHistory model. * * @author toastkidjp */ @Entity(indices = [Index(value = ["url"], unique = true)]) class ViewHistory : UrlItem { @PrimaryKey(autoGenerate = true) var _id: Long = 0 var title: String = "" var url: String = "" var favicon: String = "" var viewCount: Int = 0 var lastViewed: Long = 0 override fun urlString() = url override fun itemId() = _id }
epl-1.0
f02632f1eb8493084f2c3b2d4cff815f
16.617647
58
0.66611
3.791139
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/ui/vntags/TagTabHolder.kt
1
1598
package com.booboot.vndbandroid.ui.vntags import android.view.View import androidx.recyclerview.widget.RecyclerView import com.booboot.vndbandroid.R import com.booboot.vndbandroid.model.vndb.Tag import com.google.android.material.tabs.TabLayout import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.collapsing_tab.* import kotlinx.android.synthetic.main.collapsing_tab.view.* class TagTabHolder( override val containerView: View, private val onTitleClicked: (String) -> Unit ) : RecyclerView.ViewHolder(containerView), LayoutContainer, TabLayout.OnTabSelectedListener { private lateinit var title: String private var collapsed: Boolean = false init { itemView.tabLayout.addOnTabSelectedListener(this) } fun onBind(_title: String, _collapsed: Boolean) { title = _title collapsed = _collapsed val fullTitle = Tag.getCategoryName(title) if (tabLayout.getTabAt(0)?.text != fullTitle) { tabLayout.removeAllTabs() tabLayout.addTab(tabLayout.newTab().setText(fullTitle).setCollapsedIcon()) } } override fun onTabReselected(tab: TabLayout.Tab) { collapsed = !collapsed tab.setCollapsedIcon() onTitleClicked(title) } override fun onTabUnselected(tab: TabLayout.Tab) { } override fun onTabSelected(tab: TabLayout.Tab) { } private fun TabLayout.Tab.setCollapsedIcon() = apply { setIcon(if (collapsed) R.drawable.ic_keyboard_arrow_down_white_24dp else R.drawable.ic_keyboard_arrow_up_white_24dp) } }
gpl-3.0
e1e2cc37e0c4e88f596e669179234d15
31.632653
124
0.71965
4.36612
false
false
false
false
krudayakumar/mahaperiyavaapp
app/src/main/java/com/kanchi/periyava/old/Component/LeadingView.kt
1
3024
package com.kanchi.periyava.old.Component import android.text.Layout import android.text.style.LeadingMarginSpan import android.annotation.TargetApi import android.text.SpannableString import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.os.Build import android.util.AttributeSet import android.view.View import com.kanchi.periyava.R import android.widget.RelativeLayout import kotlinx.android.synthetic.main.layout_leadingview.view.* /** * Created by m84098 on 2/14/18. */ class LeadingView : RelativeLayout { lateinit var view:View init { view = View.inflate(context, R.layout.layout_leadingview, null) } @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr){ onCreate(attrs) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor( context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes){ onCreate(attrs) } fun onCreate(attrs: AttributeSet?) { attrs?.let { val typedArray = context.obtainStyledAttributes(it, R.styleable.LeadingView_attributes, 0, 0) val title = resources.getText(typedArray .getResourceId(R.styleable .LeadingView_attributes_text, R.string.empty)) val ico = resources.getDrawable(typedArray .getResourceId(R.styleable .LeadingView_attributes_src,R.drawable.perivaya_sitting)) val leftMargin = ico.intrinsicWidth + 10 content.text = title icon.setImageDrawable(ico) val ss = SpannableString(title) // Выставляем отступ для первых трех строк абазца ss.setSpan(CustomLeadingMarginSpan2(3, leftMargin), 0, ss.length, 0) content.text = ss typedArray.recycle() } addView(view) } } class CustomLeadingMarginSpan2(private val lines: Int, private val margin: Int) : LeadingMarginSpan.LeadingMarginSpan2 { /* Возвращает значение, на которе должен быть добавлен отступ */ override fun getLeadingMargin(first: Boolean): Int { return if (first) { margin } else { 0 } } override fun drawLeadingMargin(c: Canvas, p: Paint, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, first: Boolean, layout: Layout) { } override fun getLeadingMarginLineCount(): Int { return lines } }
apache-2.0
58d6c17b7d7f1bbe87f70ee58c0abb59
26.942857
124
0.601568
4.620472
false
false
false
false
http4k/http4k
http4k-cloudnative/src/main/kotlin/org/http4k/cloudnative/env/Secret.kt
1
1284
package org.http4k.cloudnative.env import java.io.Closeable import java.nio.charset.StandardCharsets.UTF_8 import java.util.concurrent.atomic.AtomicReference /** * A secret is a value which tries very hard not to expose itself as a string, by storing it's value in a byte array. * You can "use" the value only once, after which the value is destroyed */ class Secret(input: ByteArray) : Closeable { constructor(value: String) : this(value.toByteArray(UTF_8)) init { require(input.isNotEmpty()) { "Cannot create an empty secret" } } private val value = AtomicReference(input) private val initialHashcode = input.contentHashCode() override fun equals(other: Any?): Boolean = (value.get() ?: ByteArray(0)).contentEquals((other as Secret).value.get()) override fun hashCode(): Int = initialHashcode override fun toString(): String = "Secret(hashcode = $initialHashcode)" fun <T> use(fn: (String) -> T) = with(value.get()) { if (isNotEmpty()) fn(toString(UTF_8)) else throw IllegalStateException("Cannot read a secret more than once") }.apply { close() } override fun close(): Unit = run { value.get().apply { (0 until size).forEach { this[it] = 0 } } value.set(ByteArray(0)) } }
apache-2.0
8eb85d1d2337c70945227cf08ddc11c7
32.789474
117
0.673676
3.987578
false
false
false
false
strooooke/quickfit
app/src/main/java/com/lambdasoup/quickfit/util/WakefulIntents.kt
1
3818
/* * Copyright 2016-2019 Juliane Lehmann <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.lambdasoup.quickfit.util import android.content.Context import android.content.Intent import android.os.Build import android.os.PowerManager import android.util.SparseArray import timber.log.Timber import java.util.concurrent.TimeUnit /** * This helper is modeled after the old [androidx.legacy.content.WakefulBroadcastReceiver] - which is deprecated by now, and is indeed * useless now, as it does not start the service as a foreground service - so is in general not allowed to do so. * * The documentation there suggests enqueueing a JobScheduler Job instead. In this project, for the time being, we use ForegroundServices * instead, as it is unclear (especially on API levels below 26) whether there are any guarantees about somewhat-timely execution of * a restriction-free job. The work we're talking about here is not really deferrable, it's just IO work that happens in the background. */ object WakefulIntents { private const val EXTRA_WAKE_LOCK_ID = "com.lambdasoup.quickfit.util.WakefulBroadcastReceiver.WAKE_LOCK_ID" private val activeWakeLocks = SparseArray<PowerManager.WakeLock>() private var nextId = 1 fun startWakefulForegroundService(context: Context, intent: Intent) { synchronized(activeWakeLocks) { val id = nextId nextId++ if (nextId <= 0) { nextId = 1 } intent.putExtra(EXTRA_WAKE_LOCK_ID, id) // Not using [ContextCompat.startForegroundService] here, because we need the ComponentName // because if null is returned, we should not acquire a wakelock - it will never be released. val componentName = if (Build.VERSION.SDK_INT >= 26) { context.startForegroundService(intent) } else { // Pre-O behavior. context.startService(intent) } @Suppress("FoldInitializerAndIfToElvis") if (componentName == null) { return } val wl = (context.getSystemService(Context.POWER_SERVICE) as PowerManager) .newWakeLock( PowerManager.PARTIAL_WAKE_LOCK, "com.lambdasoup.quickfit:wake:" + componentName.flattenToShortString() ) wl.setReferenceCounted(false) wl.acquire(TimeUnit.SECONDS.toMillis(60)) activeWakeLocks.put(id, wl) } } fun completeWakefulIntent(intent: Intent) { val id = intent.getIntExtra(EXTRA_WAKE_LOCK_ID, 0) if (id == 0) { return } synchronized(activeWakeLocks) { val wl = activeWakeLocks[id] if (wl == null) { // We just log a warning here if there is no wake lock found, which could // happen for example if this function is called twice on the same // intent or the process is killed and restarted before processing the intent. Timber.w("No active wake lock id #$id") return } wl.release() activeWakeLocks.remove(id) } } }
apache-2.0
7edb4eebd94c6223f71c8416754c0fb1
37.565657
137
0.644578
4.684663
false
false
false
false
czyzby/gdx-setup
src/main/kotlin/com/github/czyzby/setup/data/platforms/server.kt
1
1385
package com.github.czyzby.setup.data.platforms import com.github.czyzby.setup.data.gradle.GradleFile import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.views.GdxPlatform /** * Represents server application project. * @author MJ */ @GdxPlatform class Server : Platform { companion object { const val ID = "server" } override val id = ID override val isGraphical = false override fun createGradleFile(project: Project): GradleFile = ServerGradleFile(project) override fun initiate(project: Project) { // Server project has no additional dependencies. addGradleTaskDescription(project, "run", "runs the ${id} application.") } } /** * Represents the Gradle file of server project. Allows to set up a different Java version and launch the application * with "run" task. * @author MJ */ class ServerGradleFile(val project: Project) : GradleFile(Server.ID) { override fun getContent(): String = """apply plugin: 'application' sourceCompatibility = ${project.advanced.serverJavaVersion} mainClassName = '${project.basic.rootPackage}.server.ServerLauncher' eclipse.project.name = appName + '-server' dependencies { ${joinDependencies(dependencies)}} jar { from { configurations.compile.collect { zipTree(it) } } manifest { attributes 'Main-Class': project.mainClassName } }""" }
unlicense
f7d709fd5bff41147e8cdc734431f4ec
26.7
117
0.726354
4.171687
false
false
false
false
mingdroid/tumbviewer
app/src/main/java/com/nutrition/express/ui/likes/LikesViewModel.kt
1
1288
package com.nutrition.express.ui.likes import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.switchMap import androidx.lifecycle.viewModelScope import com.nutrition.express.model.api.repo.BlogRepo import com.nutrition.express.model.api.repo.UserRepo import java.util.* class LikesViewModel : ViewModel() { private val userRepo: UserRepo by lazy { UserRepo(viewModelScope.coroutineContext) } private val blogRepo: BlogRepo by lazy { BlogRepo(viewModelScope.coroutineContext) } private val _input = MutableLiveData<LikesRequest>() val likesPostsData = _input.switchMap { if (it.blogName != null) { val options = HashMap<String, String>(2) options["limit"] = (20).toString() options["before"] = it.before.toString() blogRepo.getBlogLikes(it.blogName, options); } else { userRepo.getLikes(20, it.before) } } fun fetchLikesPosts(blogName: String?) { _input.value = LikesRequest(blogName, System.currentTimeMillis() / 1000) } fun fetchNextPage(before: Long) { _input.value?.let { _input.value = LikesRequest(it.blogName, before) } } data class LikesRequest(val blogName: String?, val before: Long) }
apache-2.0
13c86bd4107f5cc6334d1bb345c53ad1
35.828571
88
0.697205
4.236842
false
false
false
false
apoi/quickbeer-android
app/src/main/java/quickbeer/android/feature/barcode/detection/BarcodeProcessor.kt
2
2828
/* * Copyright 2020 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 quickbeer.android.feature.barcode.detection import androidx.annotation.MainThread import com.google.android.gms.tasks.Task import com.google.mlkit.vision.barcode.Barcode import com.google.mlkit.vision.barcode.BarcodeScanning import com.google.mlkit.vision.common.InputImage import java.io.IOException import quickbeer.android.feature.barcode.BarcodeScannerViewModel import quickbeer.android.feature.barcode.ScannerState import quickbeer.android.feature.barcode.graphic.BarcodeReticleGraphic import quickbeer.android.feature.barcode.graphic.CameraReticleAnimator import quickbeer.android.feature.barcode.graphic.GraphicOverlay import quickbeer.android.feature.barcode.utils.BarcodeValidator import timber.log.Timber /** A processor to run the barcode detector. */ class BarcodeProcessor( graphicOverlay: GraphicOverlay, private val viewModel: BarcodeScannerViewModel ) : FrameProcessorBase<List<Barcode>>() { private val scanner = BarcodeScanning.getClient() private val cameraReticleAnimator = CameraReticleAnimator(graphicOverlay) override fun detectInImage(image: InputImage): Task<List<Barcode>> { return scanner.process(image) } @MainThread override fun onSuccess( results: List<Barcode>, graphicOverlay: GraphicOverlay ) { if (!viewModel.isCameraLive) return graphicOverlay.clear() val barcode = results.firstOrNull(BarcodeValidator::isValidBarcode) val rawValue = barcode?.rawValue if (rawValue == null) { cameraReticleAnimator.start() graphicOverlay.add(BarcodeReticleGraphic(graphicOverlay, cameraReticleAnimator)) viewModel.setScannerState(ScannerState.Detecting) } else { stop() cameraReticleAnimator.cancel() viewModel.setScannerState(ScannerState.Detected(rawValue)) } graphicOverlay.invalidate() } override fun onFailure(e: Exception) { Timber.e(e, "Barcode detection failed!") } override fun stop() { super.stop() try { scanner.close() } catch (e: IOException) { Timber.e(e, "Failed to close barcode detector!") } } }
gpl-3.0
30226f2217e53cb025c746f27000ca78
32.666667
92
0.722772
4.729097
false
false
false
false
matkoniecz/StreetComplete
app/src/test/java/de/westnordost/streetcomplete/data/visiblequests/QuestPresetControllerTest.kt
1
2093
package de.westnordost.streetcomplete.data.visiblequests import de.westnordost.streetcomplete.testutils.any import de.westnordost.streetcomplete.testutils.mock import de.westnordost.streetcomplete.testutils.on import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.mockito.Mockito.verify class QuestPresetControllerTest { private lateinit var questPresetsDao: QuestPresetsDao private lateinit var selectedQuestPresetStore: SelectedQuestPresetStore private lateinit var ctrl: QuestPresetsController private lateinit var listener: QuestPresetsSource.Listener private val preset = QuestPreset(1, "test") @Before fun setUp() { questPresetsDao = mock() selectedQuestPresetStore = mock() ctrl = QuestPresetsController(questPresetsDao, selectedQuestPresetStore) listener = mock() ctrl.addListener(listener) } @Test fun get() { on(questPresetsDao.getName(1)).thenReturn("huhu") on(selectedQuestPresetStore.get()).thenReturn(1) assertEquals("huhu", ctrl.selectedQuestPresetName) } @Test fun getAll() { on(questPresetsDao.getAll()).thenReturn(listOf(preset)) assertEquals(listOf(preset), ctrl.getAll()) } @Test fun add() { on(questPresetsDao.add(any())).thenReturn(123) ctrl.add("test") verify(questPresetsDao).add("test") verify(listener).onAddedQuestPreset(QuestPreset(123, "test")) } @Test fun delete() { ctrl.delete(123) verify(questPresetsDao).delete(123) verify(listener).onDeletedQuestPreset(123) } @Test fun `delete current preset switches to preset 0`() { on(ctrl.selectedId).thenReturn(55) ctrl.delete(55) verify(questPresetsDao).delete(55) verify(listener).onDeletedQuestPreset(55) verify(selectedQuestPresetStore).set(0) } @Test fun `change current preset`() { ctrl.selectedId = 11 verify(selectedQuestPresetStore).set(11) verify(listener).onSelectedQuestPresetChanged() } }
gpl-3.0
39fb22b91b8f6bfec529c01ec4da96dd
30.712121
80
0.697086
4.66147
false
true
false
false
MichaelRocks/Sunny
app/src/main/kotlin/io/michaelrocks/forecast/ui/main/ForecastsAdapter.kt
1
3663
/* * Copyright 2016 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.forecast.ui.main import android.content.Context import android.support.v7.widget.RecyclerView import android.util.Log import android.view.ContextThemeWrapper import android.view.LayoutInflater import android.view.ViewGroup import io.michaelrocks.forecast.R import io.michaelrocks.forecast.databinding.ForecastViewBinding import io.michaelrocks.forecast.model.Forecast import io.michaelrocks.forecast.model.repository.ForecastRepository import io.michaelrocks.forecast.model.repository.Operation import io.michaelrocks.forecast.utils.CountryNameResolver import java.io.Closeable import java.util.ArrayList import javax.inject.Inject class ForecastsAdapter @Inject private constructor( context: Context, private val forecastRepository: ForecastRepository, private val formatter: ForecastFormatter, private val resolver: CountryNameResolver, private val uriGenerator: ForecastImageUriGenerator ) : RecyclerView.Adapter<ForecastsAdapter.ViewHolder>(), Closeable { private val inflater = LayoutInflater.from(ContextThemeWrapper(context, R.style.Theme_NoActionBar)) private val forecasts = ArrayList<Forecast>() private val subscription = forecastRepository.operations.subscribe({ applyOperation(it) }) init { setHasStableIds(true) forecastRepository.refreshForecasts() } override fun getItemCount(): Int = forecasts.size override fun getItemId(position: Int): Long = forecasts[position].id.run { mostSignificantBits xor leastSignificantBits } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(ForecastViewBinding.inflate(inflater, parent, false)).apply { binding.formatter = formatter binding.resolver = resolver binding.uriGenerator = uriGenerator } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.binding.forecast = forecasts[position] holder.binding.executePendingBindings() } override fun onViewRecycled(holder: ViewHolder) { holder.binding.unbind() } override fun close() = subscription.unsubscribe() private fun applyOperation(operation: Operation<Forecast>) { when (operation) { is Operation.AddOperation -> { forecasts.addAll(operation.index, operation.items) notifyItemRangeInserted(operation.index, operation.items.size) } is Operation.ChangeOperation -> { operation.items.forEachIndexed { index, forecast -> forecasts[operation.index + index] = forecast } notifyItemRangeChanged(operation.index, operation.items.size) } is Operation.RemoveOperation -> { forecasts.subList(operation.index, operation.index + operation.count).clear() notifyItemRangeRemoved(operation.index, operation.count) } is Operation.ReplaceOperation -> { forecasts.clear() forecasts.addAll(operation.items) notifyDataSetChanged() } } } class ViewHolder(val binding: ForecastViewBinding) : RecyclerView.ViewHolder(binding.root) }
apache-2.0
e45d9d3c06bb1355cdfa1eff2d8d030b
35.63
107
0.755938
4.794503
false
false
false
false
mediathekview/MediathekView
src/main/java/mediathek/controller/SenderFilmlistLoadApprover.kt
1
1691
package mediathek.controller import mediathek.javafx.filterpanel.SenderListBoxModel import mediathek.tool.ApplicationConfiguration import java.util.concurrent.ConcurrentHashMap /** * Approve or deny the load of a sender from a filmlist */ object SenderFilmlistLoadApprover { val senderSet: ConcurrentHashMap.KeySetView<String, Boolean> = ConcurrentHashMap.newKeySet() private const val SENDER_KEY = "filmlist.approved_for_load" private val config = ApplicationConfiguration.getConfiguration() init { //load settings from config val storedSenderList = config.getList(String::class.java, SENDER_KEY) if (storedSenderList == null || storedSenderList.isEmpty()) { //manually approve all of them and store in config :( senderSet.addAll(SenderListBoxModel.readOnlySenderList) config.setProperty(SENDER_KEY, senderSet) } else { senderSet.addAll(storedSenderList) } } /** * Check if a sender is approved to be loaded into the program. */ @JvmStatic fun isApproved(sender: String): Boolean { return senderSet.contains(sender) } /** * Approve that a sender may be loaded from filmlist. */ @JvmStatic fun approve(sender: String) { if (!senderSet.contains(sender)) { senderSet.add(sender) config.setProperty(SENDER_KEY, senderSet) } } /** * Deny a sender from being loaded. */ @JvmStatic fun deny(sender: String) { if (senderSet.contains(sender)) { senderSet.remove(sender) config.setProperty(SENDER_KEY, senderSet) } } }
gpl-3.0
9ab89e6bf38a2bc214643d56805bb306
29.214286
96
0.654051
4.582656
false
true
false
false
ageery/kwicket
kwicket-wicket-bootstrap-core/src/main/kotlin/org/kwicket/agilecoders/wicket/core/ajax/markup/html/bootstrap/navbar/KNavbarText.kt
1
867
package org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.navbar import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.Navbar import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.NavbarText import org.apache.wicket.behavior.Behavior import org.apache.wicket.model.IModel import org.kwicket.component.init open class KNavbarText( id: String = Navbar.componentId(), model: IModel<String?>, position: Navbar.ComponentPosition? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, behaviors: List<Behavior>? = null ) : NavbarText(id, model) { init { init( outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, behaviors = behaviors ) position?.let { this.position(it) } } }
apache-2.0
279b06b2f4f6e308f4db4d98c72f569d
31.111111
77
0.716263
4.292079
false
false
false
false
mgolokhov/dodroid
app/src/main/java/doit/study/droid/data/local/SoundRepository.kt
1
1899
package doit.study.droid.data.local import android.app.Application import android.content.res.AssetManager import doit.study.droid.data.Outcome import java.io.File import javax.inject.Inject import javax.inject.Singleton import timber.log.Timber @Singleton class SoundRepository @Inject constructor(appContext: Application) { private var assetManager: AssetManager = appContext.resources.assets private var cachedFilenamesForSuccess: List<String> = emptyList() private var cachedFilenamesForFailure: List<String> = emptyList() fun getRandomSoundFileForSuccess(): Outcome<String> { return getSoundFile(ASSET_FOLDER_FOR_SUCCESS_SOUNDS) } fun getRandomSoundFileForFailure(): Outcome<String> { return getSoundFile(ASSET_FOLDER_FOR_FAILURE_SOUNDS) } private fun getSoundFile( assetFolder: String ): Outcome<String> { var cachedFilenames = getCache(assetFolder) return try { if (cachedFilenames.isEmpty()) { @Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") cachedFilenames = assetManager .list(assetFolder) .asList() } val path = File(assetFolder, cachedFilenames.random()).path Outcome.Success(path) } catch (e: Exception) { Timber.e(e) Outcome.Error(e) } } private fun getCache(assetFolder: String): List<String> { return when (assetFolder) { ASSET_FOLDER_FOR_SUCCESS_SOUNDS -> { cachedFilenamesForSuccess } ASSET_FOLDER_FOR_FAILURE_SOUNDS -> { cachedFilenamesForFailure } else -> { emptyList() } } } companion object { private const val ASSET_FOLDER_FOR_SUCCESS_SOUNDS = "right" private const val ASSET_FOLDER_FOR_FAILURE_SOUNDS = "wrong" } }
mit
c7d96234fbcd07bb8a54519cc44becfd
32.910714
84
0.653502
4.67734
false
false
false
false