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/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/ModuleOperationExecutor.kt
2
12925
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.OperationItem import com.intellij.buildsystem.model.unified.UnifiedCoordinates import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.openapi.application.readAction import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageIdentifier import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank internal class ModuleOperationExecutor { private val operations = mutableListOf<suspend () -> Result>() sealed class Result { companion object { fun from(operation: PackageSearchOperation<*>, operationFailures: List<OperationFailure<out OperationItem>>) = if (operationFailures.isEmpty()) Success(operation) else Failure(operation, operationFailures) } abstract val operation: PackageSearchOperation<*> data class Success(override val operation: PackageSearchOperation<*>) : Result() data class Failure( override val operation: PackageSearchOperation<*>, val operationFailures: List<OperationFailure<out OperationItem>> ) : Result() { val message get() = "${operation.projectModule.name} - " + when (operation) { is PackageSearchOperation.Package.Install -> "${PackageSearchBundle.message("packagesearch.operation.verb.install")} ${operation.model.displayName}" is PackageSearchOperation.Package.Remove -> "${PackageSearchBundle.message("packagesearch.operation.verb.remove")} ${operation.model.displayName}" is PackageSearchOperation.Package.ChangeInstalled -> "${PackageSearchBundle.message("packagesearch.operation.verb.change")} ${operation.model.displayName}" is PackageSearchOperation.Repository.Install -> "${PackageSearchBundle.message("packagesearch.operation.verb.install")} ${operation.model.displayName}" is PackageSearchOperation.Repository.Remove -> "${PackageSearchBundle.message("packagesearch.operation.verb.remove")} ${operation.model.displayName}" } } } fun addOperation(operation: PackageSearchOperation<*>) = when (operation) { is PackageSearchOperation.Package.Install -> installPackage(operation) is PackageSearchOperation.Package.Remove -> removePackage(operation) is PackageSearchOperation.Package.ChangeInstalled -> changePackage(operation) is PackageSearchOperation.Repository.Install -> installRepository(operation) is PackageSearchOperation.Repository.Remove -> removeRepository(operation) } fun addOperations(operations: Iterable<PackageSearchOperation<*>>) = operations.forEach { addOperation(it) } private fun installPackage(operation: PackageSearchOperation.Package.Install) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem( projectModule ) val operationMetadata = dependencyOperationMetadataFrom( projectModule = projectModule, dependency = operation.model, newVersion = operation.newVersion, newScope = operation.newScope ) operations.add { logDebug("ModuleOperationExecutor#installPackage()") { "Installing package ${operation.model.displayName} in ${projectModule.name}" } val errors = operationProvider.addDependencyToModule(operationMetadata, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logPackageInstalled( packageIdentifier = operation.model.coordinates.toIdentifier(), packageVersion = operation.newVersion, targetModule = operation.projectModule ) } logTrace("ModuleOperationExecutor#installPackage()") { if (errors.isEmpty()) { "Package ${operation.model.displayName} installed in ${projectModule.name}" } else { "Package ${operation.model.displayName} failed to be installed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } private fun UnifiedCoordinates.toIdentifier() = PackageIdentifier("$groupId:$artifactId") private fun removePackage(operation: PackageSearchOperation.Package.Remove) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem( projectModule ) val operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model) operations.add { logDebug("ModuleOperationExecutor#removePackage()") { "Removing package ${operation.model.displayName} from ${projectModule.name}" } val errors = operationProvider.removeDependencyFromModule(operationMetadata, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logPackageRemoved( packageIdentifier = operation.model.coordinates.toIdentifier(), packageVersion = operation.currentVersion, targetModule = operation.projectModule ) } logTrace("ModuleOperationExecutor#removePackage()") { if (errors.isEmpty()) { "Package ${operation.model.displayName} removed from ${projectModule.name}" } else { "Package ${operation.model.displayName} failed to be removed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } private fun changePackage(operation: PackageSearchOperation.Package.ChangeInstalled) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) val operationMetadata = dependencyOperationMetadataFrom( projectModule = projectModule, dependency = operation.model, newVersion = operation.newVersion, newScope = operation.newScope ) operations.add { logDebug("ModuleOperationExecutor#changePackage()") { "Changing package ${operation.model.displayName} in ${projectModule.name}" } val errors = operationProvider.updateDependencyInModule(operationMetadata, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logPackageUpdated( packageIdentifier = operation.model.coordinates.toIdentifier(), packageFromVersion = operation.currentVersion, packageVersion = operation.newVersion, targetModule = operation.projectModule ) } logTrace("ModuleOperationExecutor#changePackage()") { if (errors.isEmpty()) { "Package ${operation.model.displayName} changed in ${projectModule.name}" } else { "Package ${operation.model.displayName} failed to be changed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } private fun dependencyOperationMetadataFrom( projectModule: ProjectModule, dependency: UnifiedDependency, newVersion: PackageVersion? = null, newScope: PackageScope? = null ) = DependencyOperationMetadata( module = projectModule, groupId = dependency.coordinates.groupId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency), artifactId = dependency.coordinates.artifactId.nullIfBlank() ?: throw OperationException.InvalidPackage(dependency), currentVersion = dependency.coordinates.version.nullIfBlank(), currentScope = dependency.scope.nullIfBlank(), newVersion = newVersion?.versionName.nullIfBlank() ?: dependency.coordinates.version.nullIfBlank(), newScope = newScope?.scopeName.nullIfBlank() ?: dependency.scope.nullIfBlank() ) private fun installRepository(operation: PackageSearchOperation.Repository.Install) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem( projectModule ) operations.add { logDebug("ModuleOperationExecutor#installRepository()") { "Installing repository ${operation.model.displayName} in ${projectModule.name}" } val errors = operationProvider.addRepositoryToModule(operation.model, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logRepositoryAdded(operation.model) } logTrace("ModuleOperationExecutor#installRepository()") { if (errors.isEmpty()) { "Repository ${operation.model.displayName} installed in ${projectModule.name}" } else { "Repository ${operation.model.displayName} failed to be installed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } private fun removeRepository(operation: PackageSearchOperation.Repository.Remove) { val projectModule = operation.projectModule val operationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem( projectModule ) operations.add { logDebug("ModuleOperationExecutor#removeRepository()") { "Removing repository ${operation.model.displayName} from ${projectModule.name}" } val errors = operationProvider.removeRepositoryFromModule(operation.model, projectModule) if (errors.isEmpty()) { PackageSearchEventsLogger.logRepositoryRemoved(operation.model) } logTrace("ModuleOperationExecutor#removeRepository()") { if (errors.isEmpty()) { "Repository ${operation.model.displayName} removed from ${projectModule.name}" } else { "Repository ${operation.model.displayName} failed to be removed due to:" + "\n${errors.joinToString("\n") { it.error.stackTraceToString() }}" } } Result.from(operation, errors) } } suspend fun execute() = operations.map { it() } }
apache-2.0
ccff52dbcd69782417941c9bc8755670
50.086957
163
0.671025
6.145982
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/stash/ui/GitStashActions.kt
6
2668
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.stash.ui import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.savedPatches.SavedPatchesOperationsGroup import com.intellij.openapi.vcs.changes.savedPatches.SavedPatchesProvider import git4idea.stash.GitStashOperations import git4idea.stash.GitStashTracker import git4idea.ui.StashInfo val STASH_INFO = DataKey.create<List<StashInfo>>("GitStashInfoList") abstract class GitSingleStashAction : DumbAwareAction() { abstract fun perform(project: Project, stashInfo: StashInfo): Boolean override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project != null && e.getData(STASH_INFO)?.size == 1 e.presentation.isVisible = e.isFromActionToolbar || (e.project != null && e.getData(STASH_INFO) != null) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun actionPerformed(e: AnActionEvent) { if (perform(e.project!!, e.getRequiredData(STASH_INFO).single())) { e.project!!.serviceIfCreated<GitStashTracker>()?.scheduleRefresh() } } } class GitDropStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.dropStashWithConfirmation(project, null, stashInfo) } } class GitPopStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.unstash(project, stashInfo, null, true, false) } } class GitApplyStashAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { return GitStashOperations.unstash(project, stashInfo, null, false, false) } } class GitUnstashAsAction : GitSingleStashAction() { override fun perform(project: Project, stashInfo: StashInfo): Boolean { val dialog = GitUnstashAsDialog(project, stashInfo) if (dialog.showAndGet()) { return GitStashOperations.unstash(project, stashInfo, dialog.branch, dialog.popStash, dialog.keepIndex) } return false } } class GitStashOperationsGroup : SavedPatchesOperationsGroup() { override fun isApplicable(patchObject: SavedPatchesProvider.PatchObject<*>): Boolean { return patchObject.data is StashInfo } }
apache-2.0
a6aaf2795dbd352e58e5158ebab1fcd5
37.128571
120
0.779235
4.45409
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/CodeInliner.kt
1
37858
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInliner import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.search.LocalSearchScope import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.isExtensionFunctionType import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.findUsages.ReferencesSearchScopeHelper import org.jetbrains.kotlin.idea.inspections.RedundantLambdaOrAnonymousFunctionInspection import org.jetbrains.kotlin.idea.inspections.RedundantUnitExpressionInspection import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.idea.refactoring.inline.KotlinInlineAnonymousFunctionProcessor import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.ImportInsertHelper import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.* import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs class CodeInliner<TCallElement : KtElement>( private val languageVersionSettings: LanguageVersionSettings, private val usageExpression: KtSimpleNameExpression?, private val bindingContext: BindingContext, private val resolvedCall: ResolvedCall<out CallableDescriptor>, private val callElement: TCallElement, private val inlineSetter: Boolean, codeToInline: CodeToInline ) { private val codeToInline = codeToInline.toMutable() private val project = callElement.project private val psiFactory = KtPsiFactory(project) fun doInline(): KtElement? { val descriptor = resolvedCall.resultingDescriptor val file = callElement.containingKtFile val qualifiedElement = if (callElement is KtExpression) { callElement.getQualifiedExpressionForSelector() ?: callElement.callableReferenceExpressionForReference() ?: callElement } else callElement val assignment = (qualifiedElement as? KtExpression) ?.getAssignmentByLHS() ?.takeIf { it.operationToken == KtTokens.EQ } val callableForParameters = if (assignment != null && descriptor is PropertyDescriptor) descriptor.setter?.takeIf { inlineSetter && it.hasBody() } ?: descriptor else descriptor val elementToBeReplaced = assignment.takeIf { callableForParameters is PropertySetterDescriptor } ?: qualifiedElement val commentSaver = CommentSaver(elementToBeReplaced, saveLineBreaks = true) // if the value to be inlined is not used and has no side effects we may drop it if (codeToInline.mainExpression != null && !codeToInline.alwaysKeepMainExpression && assignment == null && elementToBeReplaced is KtExpression && !elementToBeReplaced.isUsedAsExpression(bindingContext) && !codeToInline.mainExpression.shouldKeepValue(usageCount = 0) && elementToBeReplaced.getStrictParentOfType<KtAnnotationEntry>() == null ) { codeToInline.mainExpression?.getCopyableUserData(CommentHolder.COMMENTS_TO_RESTORE_KEY)?.let { commentHolder -> codeToInline.addExtraComments(CommentHolder(emptyList(), commentHolder.leadingComments + commentHolder.trailingComments)) } codeToInline.mainExpression = null } var receiver = usageExpression?.receiverExpression() receiver?.marked(USER_CODE_KEY) var receiverType = if (receiver != null) bindingContext.getType(receiver) else null if (receiver == null) { val receiverValue = if (descriptor.isExtension) resolvedCall.extensionReceiver else resolvedCall.dispatchReceiver if (receiverValue is ImplicitReceiver) { val resolutionScope = elementToBeReplaced.getResolutionScope(bindingContext, elementToBeReplaced.getResolutionFacade()) receiver = receiverValue.asExpression(resolutionScope, psiFactory) receiverType = receiverValue.type } } receiver?.mark(RECEIVER_VALUE_KEY) if (receiver != null) { for (instanceExpression in codeToInline.collectDescendantsOfType<KtInstanceExpressionWithLabel> { // for this@ClassName we have only option to keep it as is (although it's sometimes incorrect but we have no other options) it is KtThisExpression && !it[CodeToInline.SIDE_RECEIVER_USAGE_KEY] && it.labelQualifier == null || it is KtSuperExpression && it[CodeToInline.FAKE_SUPER_CALL_KEY] }) { codeToInline.replaceExpression(instanceExpression, receiver) } } val introduceValuesForParameters = processValueParameterUsages(callableForParameters) processTypeParameterUsages() val lexicalScopeElement = callElement.parentsWithSelf .takeWhile { it !is KtBlockExpression } .last() as KtElement val lexicalScope = lexicalScopeElement.getResolutionScope(lexicalScopeElement.analyze(BodyResolveMode.PARTIAL_FOR_COMPLETION)) if (elementToBeReplaced is KtSafeQualifiedExpression && receiverType?.isMarkedNullable != false) { wrapCodeForSafeCall(receiver!!, receiverType, elementToBeReplaced) } else if (callElement is KtBinaryExpression && callElement.operationToken == KtTokens.IDENTIFIER) { keepInfixFormIfPossible() } codeToInline.convertToCallableReferenceIfNeeded(elementToBeReplaced) if (elementToBeReplaced is KtExpression) { if (receiver != null) { val thisReplaced = codeToInline.collectDescendantsOfType<KtExpression> { it[RECEIVER_VALUE_KEY] } if (receiver.shouldKeepValue(usageCount = thisReplaced.size)) { codeToInline.introduceValue(receiver, receiverType, thisReplaced, elementToBeReplaced) } } for ((parameter, value, valueType) in introduceValuesForParameters) { val usagesReplaced = codeToInline.collectDescendantsOfType<KtExpression> { it[PARAMETER_VALUE_KEY] == parameter } codeToInline.introduceValue( value, valueType, usagesReplaced, elementToBeReplaced, nameSuggestion = parameter.name.asString() ) } } for (importPath in codeToInline.fqNamesToImport) { val importDescriptor = file.resolveImportReference(importPath.fqName).firstOrNull() ?: continue ImportInsertHelper.getInstance(project).importDescriptor(file, importDescriptor, aliasName = importPath.alias) } codeToInline.extraComments?.restoreComments(elementToBeReplaced) findAndMarkNewDeclarations() val replacementPerformer = when (elementToBeReplaced) { is KtExpression -> { if (descriptor.isInvokeOperator) { val call = elementToBeReplaced.getPossiblyQualifiedCallExpression() val callee = call?.calleeExpression if (callee != null && callee.text != OperatorNameConventions.INVOKE.asString()) { val receiverExpression = (codeToInline.mainExpression as? KtQualifiedExpression)?.receiverExpression when { elementToBeReplaced is KtCallExpression && receiverExpression is KtThisExpression -> receiverExpression.replace(callee) elementToBeReplaced is KtDotQualifiedExpression -> receiverExpression?.replace(psiFactory.createExpressionByPattern("$0.$1", receiverExpression, callee)) } } } ExpressionReplacementPerformer(codeToInline, elementToBeReplaced) } is KtAnnotationEntry -> AnnotationEntryReplacementPerformer(codeToInline, elementToBeReplaced) is KtSuperTypeCallEntry -> SuperTypeCallEntryReplacementPerformer(codeToInline, elementToBeReplaced) else -> { assert(!canBeReplaced(elementToBeReplaced)) error("Unsupported element") } } assert(canBeReplaced(elementToBeReplaced)) return replacementPerformer.doIt(postProcessing = { range -> val newRange = postProcessInsertedCode(range, lexicalScope) if (!newRange.isEmpty) { commentSaver.restore(newRange) } newRange }) } private fun KtElement.callableReferenceExpressionForReference(): KtCallableReferenceExpression? = parent.safeAs<KtCallableReferenceExpression>()?.takeIf { it.callableReference == callElement } private fun KtSimpleNameExpression.receiverExpression(): KtExpression? = getReceiverExpression() ?: parent.safeAs<KtCallableReferenceExpression>()?.receiverExpression private fun MutableCodeToInline.convertToCallableReferenceIfNeeded(elementToBeReplaced: KtElement) { if (elementToBeReplaced !is KtCallableReferenceExpression) return val qualified = mainExpression?.safeAs<KtQualifiedExpression>() ?: return val reference = qualified.callExpression?.calleeExpression ?: qualified.selectorExpression ?: return val callableReference = if (elementToBeReplaced.receiverExpression == null) { psiFactory.createExpressionByPattern("::$0", reference) } else { psiFactory.createExpressionByPattern("$0::$1", qualified.receiverExpression, reference) } codeToInline.replaceExpression(qualified, callableReference) } private fun findAndMarkNewDeclarations() { for (it in codeToInline.statementsBefore) { if (it is KtNamedDeclaration) { it.mark(NEW_DECLARATION_KEY) } } } private fun renameDuplicates( declarations: List<KtNamedDeclaration>, lexicalScope: LexicalScope, endOfScope: Int, ) { val validator = CollectingNameValidator { !it.nameHasConflictsInScope(lexicalScope, languageVersionSettings) } for (declaration in declarations) { val oldName = declaration.name if (oldName != null && oldName.nameHasConflictsInScope(lexicalScope, languageVersionSettings)) { val newName = Fe10KotlinNameSuggester.suggestNameByName(oldName, validator) for (reference in ReferencesSearchScopeHelper.search(declaration, LocalSearchScope(declaration.parent))) { if (reference.element.startOffset < endOfScope) { reference.handleElementRename(newName) } } declaration.nameIdentifier?.replace(psiFactory.createNameIdentifier(newName)) } } } private fun processValueParameterUsages(descriptor: CallableDescriptor): Collection<IntroduceValueForParameter> { val introduceValuesForParameters = ArrayList<IntroduceValueForParameter>() // process parameters in reverse order because default values can use previous parameters for (parameter in descriptor.valueParameters.asReversed()) { val argument = argumentForParameter(parameter, descriptor) ?: continue val expression = argument.expression.apply { if (this is KtCallElement) { insertExplicitTypeArgument() } put(PARAMETER_VALUE_KEY, parameter) } val parameterName = parameter.name val usages = codeToInline.collectDescendantsOfType<KtExpression> { it[CodeToInline.PARAMETER_USAGE_KEY] == parameterName } usages.forEach { val usageArgument = it.parent as? KtValueArgument if (argument.isNamed) { usageArgument?.mark(MAKE_ARGUMENT_NAMED_KEY) } if (argument.isDefaultValue) { usageArgument?.mark(DEFAULT_PARAMETER_VALUE_KEY) } codeToInline.replaceExpression(it, expression.copied()) } if (expression.shouldKeepValue(usageCount = usages.size)) { introduceValuesForParameters.add(IntroduceValueForParameter(parameter, expression, argument.expressionType)) } } return introduceValuesForParameters } private fun KtCallElement.insertExplicitTypeArgument() { if (InsertExplicitTypeArgumentsIntention.isApplicableTo(this, bindingContext)) { InsertExplicitTypeArgumentsIntention.createTypeArguments(this, bindingContext)?.let { typeArgumentList -> clear(USER_CODE_KEY) for (child in children) { child.safeAs<KtElement>()?.mark(USER_CODE_KEY) } addAfter(typeArgumentList, calleeExpression) } } } private data class IntroduceValueForParameter( val parameter: ValueParameterDescriptor, val value: KtExpression, val valueType: KotlinType? ) private fun processTypeParameterUsages() { val typeParameters = resolvedCall.resultingDescriptor.original.typeParameters val callElement = resolvedCall.call.callElement val callExpression = callElement as? KtCallElement val explicitTypeArgs = callExpression?.typeArgumentList?.arguments if (explicitTypeArgs != null && explicitTypeArgs.size != typeParameters.size) return for ((index, typeParameter) in typeParameters.withIndex()) { val parameterName = typeParameter.name val usages = codeToInline.collectDescendantsOfType<KtExpression> { it[CodeToInline.TYPE_PARAMETER_USAGE_KEY] == parameterName } val type = resolvedCall.typeArguments[typeParameter] ?: continue val typeElement = if (explicitTypeArgs != null) { // we use explicit type arguments if available to avoid shortening val explicitArgTypeElement = explicitTypeArgs[index].typeReference?.typeElement ?: continue explicitArgTypeElement.marked(USER_CODE_KEY) } else { psiFactory.createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type)).typeElement ?: continue } val typeClassifier = type.constructor.declarationDescriptor for (usage in usages) { val parent = usage.parent if (parent is KtClassLiteralExpression && typeClassifier != null) { // for class literal ("X::class") we need type arguments only for kotlin.Array val arguments = if (typeElement is KtUserType && KotlinBuiltIns.isArray(type)) typeElement.typeArgumentList?.text.orEmpty() else "" codeToInline.replaceExpression( usage, psiFactory.createExpression( IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(typeClassifier) + arguments ) ) } else if (parent is KtUserType) { parent.replace(typeElement) } else { //TODO: tests for this? codeToInline.replaceExpression(usage, psiFactory.createExpression(typeElement.text)) } } } } private fun wrapCodeForSafeCall(receiver: KtExpression, receiverType: KotlinType?, expressionToBeReplaced: KtExpression) { if (codeToInline.statementsBefore.isEmpty()) { val qualified = codeToInline.mainExpression as? KtQualifiedExpression if (qualified != null) { if (qualified.receiverExpression[RECEIVER_VALUE_KEY]) { if (qualified is KtSafeQualifiedExpression) return // already safe val selector = qualified.selectorExpression if (selector != null) { codeToInline.mainExpression = psiFactory.createExpressionByPattern("$0?.$1", receiver, selector) return } } } } if (codeToInline.statementsBefore.isEmpty() || expressionToBeReplaced.isUsedAsExpression(bindingContext)) { val thisReplaced = codeToInline.collectDescendantsOfType<KtExpression> { it[RECEIVER_VALUE_KEY] } codeToInline.introduceValue(receiver, receiverType, thisReplaced, expressionToBeReplaced, safeCall = true) } else { codeToInline.mainExpression = psiFactory.buildExpression { appendFixedText("if (") appendExpression(receiver) appendFixedText("!=null) {") with(codeToInline) { appendExpressionsFromCodeToInline(postfixForMainExpression = "\n") } appendFixedText("}") } codeToInline.statementsBefore.clear() } } private fun keepInfixFormIfPossible() { if (codeToInline.statementsBefore.isNotEmpty()) return val dotQualified = codeToInline.mainExpression as? KtDotQualifiedExpression ?: return val receiver = dotQualified.receiverExpression if (!receiver[RECEIVER_VALUE_KEY]) return val call = dotQualified.selectorExpression as? KtCallExpression ?: return val nameExpression = call.calleeExpression as? KtSimpleNameExpression ?: return val argument = call.valueArguments.singleOrNull() ?: return if (argument.isNamed()) return val argumentExpression = argument.getArgumentExpression() ?: return codeToInline.mainExpression = psiFactory.createExpressionByPattern("$0 ${nameExpression.text} $1", receiver, argumentExpression) } private fun KtExpression?.shouldKeepValue(usageCount: Int): Boolean { if (usageCount == 1) return false val sideEffectOnly = usageCount == 0 return when (this) { is KtSimpleNameExpression -> false is KtQualifiedExpression -> receiverExpression.shouldKeepValue(usageCount) || selectorExpression.shouldKeepValue(usageCount) is KtUnaryExpression -> operationToken in setOf(KtTokens.PLUSPLUS, KtTokens.MINUSMINUS) || baseExpression.shouldKeepValue(usageCount) is KtStringTemplateExpression -> entries.any { if (sideEffectOnly) it.expression.shouldKeepValue(usageCount) else it is KtStringTemplateEntryWithExpression } is KtThisExpression, is KtSuperExpression, is KtConstantExpression -> false is KtParenthesizedExpression -> expression.shouldKeepValue(usageCount) is KtArrayAccessExpression -> !sideEffectOnly || arrayExpression.shouldKeepValue(usageCount) || indexExpressions.any { it.shouldKeepValue(usageCount) } is KtBinaryExpression -> !sideEffectOnly || operationToken == KtTokens.IDENTIFIER || left.shouldKeepValue(usageCount) || right.shouldKeepValue(usageCount) is KtIfExpression -> !sideEffectOnly || condition.shouldKeepValue(usageCount) || then.shouldKeepValue(usageCount) || `else`.shouldKeepValue(usageCount) is KtBinaryExpressionWithTypeRHS -> !(sideEffectOnly && left.isNull()) is KtClassLiteralExpression -> false is KtCallableReferenceExpression -> false null -> false else -> true } } private class Argument( val expression: KtExpression, val expressionType: KotlinType?, val isNamed: Boolean = false, val isDefaultValue: Boolean = false ) private fun argumentForParameter(parameter: ValueParameterDescriptor, callableDescriptor: CallableDescriptor): Argument? { if (callableDescriptor is PropertySetterDescriptor) { val valueAssigned = (callElement as? KtExpression) ?.getQualifiedExpressionForSelectorOrThis() ?.getAssignmentByLHS() ?.right ?: return null return Argument(valueAssigned, bindingContext.getType(valueAssigned)) } when (val resolvedArgument = resolvedCall.valueArguments[parameter] ?: return null) { is ExpressionValueArgument -> { val valueArgument = resolvedArgument.valueArgument val expression = valueArgument?.getArgumentExpression() expression?.mark(USER_CODE_KEY) ?: return null val expressionType = bindingContext.getType(expression) val resultExpression = kotlin.run { if (expression !is KtLambdaExpression) return@run null if (valueArgument is LambdaArgument) { expression.mark(WAS_FUNCTION_LITERAL_ARGUMENT_KEY) } if (!parameter.type.isExtensionFunctionType) return@run null expression.functionLiteral.descriptor?.safeAs<FunctionDescriptor>()?.let { descriptor -> LambdaToAnonymousFunctionIntention.convertLambdaToFunction(expression, descriptor) } } ?: expression return Argument(resultExpression, expressionType, isNamed = valueArgument.isNamed()) } is DefaultValueArgument -> { val (defaultValue, parameterUsages) = OptionalParametersHelper.defaultParameterValue(parameter, project) ?: return null for ((param, usages) in parameterUsages) { usages.forEach { it.put(CodeToInline.PARAMETER_USAGE_KEY, param.name) } } val defaultValueCopy = defaultValue.copied() // clean up user data in original defaultValue.forEachDescendantOfType<KtExpression> { it.clear(CodeToInline.PARAMETER_USAGE_KEY) } return Argument(defaultValueCopy, null/*TODO*/, isDefaultValue = true) } is VarargValueArgument -> { val arguments = resolvedArgument.arguments val single = arguments.singleOrNull() if (single?.getSpreadElement() != null) { val expression = single.getArgumentExpression()!!.marked(USER_CODE_KEY) return Argument(expression, bindingContext.getType(expression), isNamed = single.isNamed()) } val elementType = parameter.varargElementType!! val expression = psiFactory.buildExpression { appendFixedText(arrayOfFunctionName(elementType)) appendFixedText("(") for ((i, argument) in arguments.withIndex()) { if (i > 0) appendFixedText(",") if (argument.getSpreadElement() != null) { appendFixedText("*") } appendExpression(argument.getArgumentExpression()!!.marked(USER_CODE_KEY)) } appendFixedText(")") } return Argument(expression, parameter.type, isNamed = single?.isNamed() ?: false) } else -> error("Unknown argument type: $resolvedArgument") } } private fun postProcessInsertedCode(range: PsiChildRange, lexicalScope: LexicalScope?): PsiChildRange { val pointers = range.filterIsInstance<KtElement>().map { it.createSmartPointer() }.toList() if (pointers.isEmpty()) return PsiChildRange.EMPTY lexicalScope?.let { scope -> val declarations = pointers.mapNotNull { pointer -> pointer.element?.takeIf { it[NEW_DECLARATION_KEY] } as? KtNamedDeclaration } if (declarations.isNotEmpty()) { val endOfScope = pointers.last().element?.endOffset ?: error("Can't find the end of the scope") renameDuplicates(declarations, scope, endOfScope) } } for (pointer in pointers) { restoreComments(pointer) introduceNamedArguments(pointer) restoreFunctionLiteralArguments(pointer) //TODO: do this earlier dropArgumentsForDefaultValues(pointer) removeRedundantLambdasAndAnonymousFunctions(pointer) simplifySpreadArrayOfArguments(pointer) removeExplicitTypeArguments(pointer) removeRedundantUnitExpressions(pointer) } val shortenFilter = { element: PsiElement -> if (element[USER_CODE_KEY]) { ShortenReferences.FilterResult.SKIP } else { val thisReceiver = (element as? KtQualifiedExpression)?.receiverExpression as? KtThisExpression if (thisReceiver != null && thisReceiver[USER_CODE_KEY]) // don't remove explicit 'this' coming from user's code ShortenReferences.FilterResult.GO_INSIDE else ShortenReferences.FilterResult.PROCESS } } // can simplify to single call after KTIJ-646 val newElements = pointers.mapNotNull { it.element?.let { element -> ShortenReferences { ShortenReferences.Options(removeThis = true) }.process(element, elementFilter = shortenFilter) } } for (element in newElements) { // clean up user data element.forEachDescendantOfType<KtExpression> { it.clear(CommentHolder.COMMENTS_TO_RESTORE_KEY) it.clear(USER_CODE_KEY) it.clear(CodeToInline.PARAMETER_USAGE_KEY) it.clear(CodeToInline.TYPE_PARAMETER_USAGE_KEY) it.clear(CodeToInline.FAKE_SUPER_CALL_KEY) it.clear(PARAMETER_VALUE_KEY) it.clear(RECEIVER_VALUE_KEY) it.clear(WAS_FUNCTION_LITERAL_ARGUMENT_KEY) it.clear(NEW_DECLARATION_KEY) } element.forEachDescendantOfType<KtValueArgument> { it.clear(MAKE_ARGUMENT_NAMED_KEY) it.clear(DEFAULT_PARAMETER_VALUE_KEY) } } return if (newElements.isEmpty()) PsiChildRange.EMPTY else PsiChildRange(newElements.first(), newElements.last()) } private fun removeRedundantLambdasAndAnonymousFunctions(pointer: SmartPsiElementPointer<KtElement>) { val element = pointer.element ?: return for (function in element.collectDescendantsOfType<KtFunction>().asReversed()) { val call = RedundantLambdaOrAnonymousFunctionInspection.findCallIfApplicableTo(function) if (call != null) { KotlinInlineAnonymousFunctionProcessor.performRefactoring(call, editor = null) } } } private fun restoreComments(pointer: SmartPsiElementPointer<KtElement>) { pointer.element?.forEachDescendantOfType<KtExpression> { it.getCopyableUserData(CommentHolder.COMMENTS_TO_RESTORE_KEY)?.restoreComments(it) } } private fun removeRedundantUnitExpressions(pointer: SmartPsiElementPointer<KtElement>) { pointer.element?.forEachDescendantOfType<KtReferenceExpression> { if (RedundantUnitExpressionInspection.isRedundantUnit(it)) { it.delete() } } } private fun introduceNamedArguments(pointer: SmartPsiElementPointer<KtElement>) { val element = pointer.element ?: return val callsToProcess = LinkedHashSet<KtCallExpression>() element.forEachDescendantOfType<KtValueArgument> { if (it[MAKE_ARGUMENT_NAMED_KEY] && !it.isNamed()) { val callExpression = (it.parent as? KtValueArgumentList)?.parent as? KtCallExpression callsToProcess.addIfNotNull(callExpression) } } for (callExpression in callsToProcess) { val resolvedCall = callExpression.resolveToCall() ?: return if (!resolvedCall.isReallySuccess()) return val argumentsToMakeNamed = callExpression.valueArguments.dropWhile { !it[MAKE_ARGUMENT_NAMED_KEY] } for (argument in argumentsToMakeNamed) { if (argument.isNamed()) continue if (argument is KtLambdaArgument) continue val argumentMatch = resolvedCall.getArgumentMapping(argument) as ArgumentMatch val name = argumentMatch.valueParameter.name //TODO: not always correct for vararg's val newArgument = psiFactory.createArgument(argument.getArgumentExpression()!!, name, argument.getSpreadElement() != null) if (argument[DEFAULT_PARAMETER_VALUE_KEY]) { newArgument.mark(DEFAULT_PARAMETER_VALUE_KEY) } argument.replace(newArgument) } } } private fun dropArgumentsForDefaultValues(pointer: SmartPsiElementPointer<KtElement>) { val result = pointer.element ?: return val project = result.project val newBindingContext = result.analyze() val argumentsToDrop = ArrayList<ValueArgument>() // we drop only those arguments that added to the code from some parameter's default fun canDropArgument(argument: ValueArgument) = (argument as KtValueArgument)[DEFAULT_PARAMETER_VALUE_KEY] result.forEachDescendantOfType<KtCallElement> { callExpression -> val resolvedCall = callExpression.getResolvedCall(newBindingContext) ?: return@forEachDescendantOfType argumentsToDrop.addAll(OptionalParametersHelper.detectArgumentsToDropForDefaults(resolvedCall, project, ::canDropArgument)) } for (argument in argumentsToDrop) { argument as KtValueArgument val argumentList = argument.parent as KtValueArgumentList argumentList.removeArgument(argument) if (argumentList.arguments.isEmpty()) { val callExpression = argumentList.parent as KtCallElement if (callExpression.lambdaArguments.isNotEmpty()) { argumentList.delete() } } } } private fun arrayOfFunctionName(elementType: KotlinType): String { return when { KotlinBuiltIns.isInt(elementType) -> "kotlin.intArrayOf" KotlinBuiltIns.isLong(elementType) -> "kotlin.longArrayOf" KotlinBuiltIns.isShort(elementType) -> "kotlin.shortArrayOf" KotlinBuiltIns.isChar(elementType) -> "kotlin.charArrayOf" KotlinBuiltIns.isBoolean(elementType) -> "kotlin.booleanArrayOf" KotlinBuiltIns.isByte(elementType) -> "kotlin.byteArrayOf" KotlinBuiltIns.isDouble(elementType) -> "kotlin.doubleArrayOf" KotlinBuiltIns.isFloat(elementType) -> "kotlin.floatArrayOf" elementType.isError -> "kotlin.arrayOf" else -> "kotlin.arrayOf<" + IdeDescriptorRenderers.SOURCE_CODE.renderType(elementType) + ">" } } private fun removeExplicitTypeArguments(pointer: SmartPsiElementPointer<KtElement>) { val result = pointer.element ?: return for (typeArgumentList in result.collectDescendantsOfType<KtTypeArgumentList>(canGoInside = { !it[USER_CODE_KEY] }).asReversed()) { if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(typeArgumentList, approximateFlexible = true)) { typeArgumentList.delete() } } } private fun simplifySpreadArrayOfArguments(pointer: SmartPsiElementPointer<KtElement>) { val result = pointer.element ?: return //TODO: test for nested val argumentsToExpand = ArrayList<Pair<KtValueArgument, Collection<KtValueArgument>>>() result.forEachDescendantOfType<KtValueArgument>(canGoInside = { !it[USER_CODE_KEY] }) { argument -> if (argument.getSpreadElement() != null && !argument.isNamed()) { val argumentExpression = argument.getArgumentExpression() ?: return@forEachDescendantOfType val resolvedCall = argumentExpression.resolveToCall() ?: return@forEachDescendantOfType val callExpression = resolvedCall.call.callElement as? KtCallElement ?: return@forEachDescendantOfType if (CompileTimeConstantUtils.isArrayFunctionCall(resolvedCall)) { argumentsToExpand.add(argument to callExpression.valueArgumentList?.arguments.orEmpty()) } } } for ((argument, replacements) in argumentsToExpand) { argument.replaceByMultiple(replacements) } } private fun KtValueArgument.replaceByMultiple(arguments: Collection<KtValueArgument>) { val list = parent as KtValueArgumentList if (arguments.isEmpty()) { list.removeArgument(this) } else { var anchor = this for (argument in arguments) { anchor = list.addArgumentAfter(argument, anchor) } list.removeArgument(this) } } private fun restoreFunctionLiteralArguments(pointer: SmartPsiElementPointer<KtElement>) { val expression = pointer.element ?: return val callExpressions = ArrayList<KtCallExpression>() expression.forEachDescendantOfType<KtExpression>(fun(expr) { if (!expr[WAS_FUNCTION_LITERAL_ARGUMENT_KEY]) return assert(expr.unpackFunctionLiteral() != null) val argument = expr.parent as? KtValueArgument ?: return if (argument is KtLambdaArgument) return val argumentList = argument.parent as? KtValueArgumentList ?: return if (argument != argumentList.arguments.last()) return val callExpression = argumentList.parent as? KtCallExpression ?: return if (callExpression.lambdaArguments.isNotEmpty()) return callExpression.resolveToCall() ?: return callExpressions.add(callExpression) }) callExpressions.forEach { if (it.canMoveLambdaOutsideParentheses()) { it.moveFunctionLiteralOutsideParentheses() } } } private operator fun <T : Any> PsiElement.get(key: Key<T>): T? = getCopyableUserData(key) private operator fun PsiElement.get(key: Key<Unit>): Boolean = getCopyableUserData(key) != null private fun <T : Any> KtElement.clear(key: Key<T>) = putCopyableUserData(key, null) private fun <T : Any> KtElement.put(key: Key<T>, value: T) = putCopyableUserData(key, value) private fun KtElement.mark(key: Key<Unit>) = putCopyableUserData(key, Unit) private fun <T : KtElement> T.marked(key: Key<Unit>): T { putCopyableUserData(key, Unit) return this } companion object { // keys below are used on expressions private val USER_CODE_KEY = Key<Unit>("USER_CODE") private val PARAMETER_VALUE_KEY = Key<ValueParameterDescriptor>("PARAMETER_VALUE") private val RECEIVER_VALUE_KEY = Key<Unit>("RECEIVER_VALUE") private val WAS_FUNCTION_LITERAL_ARGUMENT_KEY = Key<Unit>("WAS_FUNCTION_LITERAL_ARGUMENT") private val NEW_DECLARATION_KEY = Key<Unit>("NEW_DECLARATION") // these keys are used on KtValueArgument private val MAKE_ARGUMENT_NAMED_KEY = Key<Unit>("MAKE_ARGUMENT_NAMED") private val DEFAULT_PARAMETER_VALUE_KEY = Key<Unit>("DEFAULT_PARAMETER_VALUE") fun canBeReplaced(element: KtElement): Boolean = when (element) { is KtExpression, is KtAnnotationEntry, is KtSuperTypeCallEntry -> true else -> false } } }
apache-2.0
1ffb27bf64a36d6ce00b3f8ab308f393
46.860936
140
0.653759
6.026425
false
false
false
false
GunoH/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/compilation/upload.kt
1
9388
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package org.jetbrains.intellij.build.impl.compilation import com.github.luben.zstd.Zstd import com.github.luben.zstd.ZstdDirectBufferCompressingStreamNoFinalizer import com.intellij.diagnostic.telemetry.forkJoinTask import com.intellij.diagnostic.telemetry.use import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream import okhttp3.* import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import okio.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import java.nio.ByteBuffer import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.* import java.util.concurrent.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong private val MEDIA_TYPE_JSON = "application/json".toMediaType() internal val READ_OPERATION = EnumSet.of(StandardOpenOption.READ) internal const val MAX_BUFFER_SIZE = 4_000_000 internal fun uploadArchives(reportStatisticValue: (key: String, value: String) -> Unit, config: CompilationCacheUploadConfiguration, metadataJson: String, httpClient: OkHttpClient, items: List<PackAndUploadItem>, bufferPool: DirectFixedSizeByteBufferPool) { val uploadedCount = AtomicInteger() val uploadedBytes = AtomicLong() val reusedCount = AtomicInteger() val reusedBytes = AtomicLong() var fallbackToHeads = false val alreadyUploaded: Set<String> = try { if (config.checkFiles) { spanBuilder("fetch info about already uploaded files").use { HashSet(getFoundAndMissingFiles(metadataJson, config.serverUrl, httpClient).found) } } else { emptySet() } } catch (e: Throwable) { Span.current().recordException(e, Attributes.of( AttributeKey.stringKey("message"), "failed to fetch info about already uploaded files, will fallback to HEAD requests" )) fallbackToHeads = true emptySet() } ForkJoinTask.invokeAll(items.mapNotNull { item -> if (alreadyUploaded.contains(item.name)) { reusedCount.getAndIncrement() reusedBytes.getAndAdd(Files.size(item.archive)) return@mapNotNull null } forkJoinTask(spanBuilder("upload archive").setAttribute("name", item.name).setAttribute("hash", item.hash!!)) { val isUploaded = uploadFile(url = "${config.serverUrl}/$uploadPrefix/${item.name}/${item.hash!!}.jar", file = item.archive, useHead = fallbackToHeads, span = Span.current(), httpClient = httpClient, bufferPool = bufferPool) val size = Files.size(item.archive) if (isUploaded) { uploadedCount.getAndIncrement() uploadedBytes.getAndAdd(size) } else { reusedCount.getAndIncrement() reusedBytes.getAndAdd(size) } } }) Span.current().addEvent("upload complete", Attributes.of( AttributeKey.longKey("reusedParts"), reusedCount.get().toLong(), AttributeKey.longKey("uploadedParts"), uploadedCount.get().toLong(), AttributeKey.longKey("reusedBytes"), reusedBytes.get(), AttributeKey.longKey("uploadedBytes"), uploadedBytes.get(), AttributeKey.longKey("totalBytes"), reusedBytes.get() + uploadedBytes.get(), AttributeKey.longKey("totalCount"), (reusedCount.get() + uploadedCount.get()).toLong(), )) reportStatisticValue("compile-parts:reused:bytes", reusedBytes.get().toString()) reportStatisticValue("compile-parts:reused:count", reusedCount.get().toString()) reportStatisticValue("compile-parts:uploaded:bytes", uploadedBytes.get().toString()) reportStatisticValue("compile-parts:uploaded:count", uploadedCount.get().toString()) reportStatisticValue("compile-parts:total:bytes", (reusedBytes.get() + uploadedBytes.get()).toString()) reportStatisticValue("compile-parts:total:count", (reusedCount.get() + uploadedCount.get()).toString()) } private fun getFoundAndMissingFiles(metadataJson: String, serverUrl: String, client: OkHttpClient): CheckFilesResponse { client.newCall(Request.Builder() .url("$serverUrl/check-files") .post(metadataJson.toRequestBody(MEDIA_TYPE_JSON)) .build()).execute().useSuccessful { return Json.decodeFromStream(it.body.byteStream()) } } // Using ZSTD dictionary doesn't make the difference, even slightly worse (default compression level 3). // That's because in our case we compress a relatively large archive of class files. private fun uploadFile(url: String, file: Path, useHead: Boolean, span: Span, httpClient: OkHttpClient, bufferPool: DirectFixedSizeByteBufferPool): Boolean { if (useHead) { val request = Request.Builder().url(url).head().build() val code = httpClient.newCall(request).execute().use { it.code } when { code == 200 -> { span.addEvent("already exist on server, nothing to upload", Attributes.of( AttributeKey.stringKey("url"), url, )) return false } code != 404 -> { span.addEvent("responded with unexpected", Attributes.of( AttributeKey.longKey("code"), code.toLong(), AttributeKey.stringKey("url"), url, )) } } } val fileSize = Files.size(file) if (Zstd.compressBound(fileSize) <= MAX_BUFFER_SIZE) { compressSmallFile(file = file, fileSize = fileSize, bufferPool = bufferPool, url = url) } else { val request = Request.Builder() .url(url) .put(object : RequestBody() { override fun contentType() = MEDIA_TYPE_BINARY override fun writeTo(sink: BufferedSink) { compressFile(file = file, output = sink, bufferPool = bufferPool) } }) .build() httpClient.newCall(request).execute().useSuccessful { } } return true } private fun compressSmallFile(file: Path, fileSize: Long, bufferPool: DirectFixedSizeByteBufferPool, url: String) { val targetBuffer = bufferPool.allocate() try { var readOffset = 0L val sourceBuffer = bufferPool.allocate() var isSourceBufferReleased = false try { FileChannel.open(file, READ_OPERATION).use { input -> do { readOffset += input.read(sourceBuffer, readOffset) } while (readOffset < fileSize) } sourceBuffer.flip() Zstd.compress(targetBuffer, sourceBuffer, 3, false) targetBuffer.flip() bufferPool.release(sourceBuffer) isSourceBufferReleased = true } finally { if (!isSourceBufferReleased) { bufferPool.release(sourceBuffer) } } val compressedSize = targetBuffer.remaining() val request = Request.Builder() .url(url) .put(object : RequestBody() { override fun contentLength() = compressedSize.toLong() override fun contentType() = MEDIA_TYPE_BINARY override fun writeTo(sink: BufferedSink) { targetBuffer.mark() sink.write(targetBuffer) targetBuffer.reset() } }) .build() httpClient.newCall(request).execute().useSuccessful { } } finally { bufferPool.release(targetBuffer) } } private fun compressFile(file: Path, output: BufferedSink, bufferPool: DirectFixedSizeByteBufferPool) { val targetBuffer = bufferPool.allocate() object : ZstdDirectBufferCompressingStreamNoFinalizer(targetBuffer, 3) { override fun flushBuffer(toFlush: ByteBuffer): ByteBuffer { toFlush.flip() while (toFlush.hasRemaining()) { output.write(toFlush) } toFlush.clear() return toFlush } override fun close() { try { super.close() } finally { bufferPool.release(targetBuffer) } } }.use { compressor -> val sourceBuffer = bufferPool.allocate() try { var offset = 0L FileChannel.open(file, READ_OPERATION).use { input -> val fileSize = input.size() while (offset < fileSize) { val actualBlockSize = (fileSize - offset).toInt() if (sourceBuffer.remaining() > actualBlockSize) { sourceBuffer.limit(sourceBuffer.position() + actualBlockSize) } var readOffset = offset do { readOffset += input.read(sourceBuffer, readOffset) } while (sourceBuffer.hasRemaining()) sourceBuffer.flip() compressor.compress(sourceBuffer) sourceBuffer.clear() offset = readOffset } } } finally { bufferPool.release(sourceBuffer) } } } @Serializable private data class CheckFilesResponse( val found: List<String> = emptyList(), )
apache-2.0
f713814893580d71bdedf5c376815ed2
32.65233
124
0.657968
4.799591
false
false
false
false
GunoH/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/MethodDataExternalizer.kt
2
6233
// 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.codeInspection.dataFlow.inference import com.intellij.codeInsight.Nullability import com.intellij.codeInspection.dataFlow.ContractReturnValue import com.intellij.codeInspection.dataFlow.StandardMethodContract import com.intellij.codeInspection.dataFlow.StandardMethodContract.ValueConstraint import com.intellij.openapi.util.io.DataInputOutputUtilRt.* import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil.readNullable import com.intellij.util.io.DataInputOutputUtil.writeNullable import java.io.DataInput import java.io.DataOutput import java.util.* internal object MethodDataExternalizer : DataExternalizer<Map<Int, MethodData>> { override fun save(out: DataOutput, value: Map<Int, MethodData>?) { writeSeq(out, value!!.toList()) { writeINT(out, it.first); writeMethod(out, it.second) } } override fun read(input: DataInput): Map<Int, MethodData> { return readSeq(input) { readINT(input) to readMethod(input) }.toMap() } private fun writeMethod(out: DataOutput, data: MethodData) { writeNullable(out, data.methodReturn) { writeNullity(out, it) } writeNullable(out, data.purity) { writePurity(out, it) } writeSeq(out, data.contracts) { writeContract(out, it) } writeBitSet(out, data.notNullParameters) writeINT(out, data.bodyStart) writeINT(out, data.bodyEnd) } private fun readMethod(input: DataInput): MethodData { val nullity = readNullable(input) { readNullity(input) } val purity = readNullable(input) { readPurity(input) } val contracts = readSeq(input) { readContract(input) } val notNullParameters = readBitSet(input) return MethodData(nullity, purity, contracts, notNullParameters, readINT(input), readINT(input)) } private fun writeBitSet(out: DataOutput, bitSet: BitSet) { val bytes = bitSet.toByteArray() val size = bytes.size // Write up to 255 bytes, thus up to 2040 bits which is far more than number of allowed Java method parameters assert(size in 0..255) out.writeByte(size) out.write(bytes) } private fun readBitSet(input: DataInput): BitSet { val size = input.readUnsignedByte() val bytes = ByteArray(size) input.readFully(bytes) return BitSet.valueOf(bytes) } private fun writeNullity(out: DataOutput, methodReturn: MethodReturnInferenceResult) { return when (methodReturn) { is MethodReturnInferenceResult.Predefined -> { out.writeByte(0) out.writeByte(methodReturn.value.ordinal) } is MethodReturnInferenceResult.FromDelegate -> { out.writeByte(1) out.writeByte(methodReturn.value.ordinal); writeRanges(out, methodReturn.delegateCalls) } else -> throw IllegalArgumentException(methodReturn.toString()) } } private fun readNullity(input: DataInput): MethodReturnInferenceResult { return when (input.readByte().toInt()) { 0 -> MethodReturnInferenceResult.Predefined(Nullability.values()[input.readByte().toInt()]) else -> MethodReturnInferenceResult.FromDelegate(Nullability.values()[input.readByte().toInt()], readRanges(input)) } } private fun writeRanges(out: DataOutput, ranges: List<ExpressionRange>) { writeSeq(out, ranges) { writeRange(out, it) } } private fun readRanges(input: DataInput) = readSeq(input) { readRange(input) } private fun writeRange(out: DataOutput, range: ExpressionRange) { writeINT(out, range.startOffset) writeINT(out, range.endOffset) } private fun readRange(input: DataInput) = ExpressionRange(readINT(input), readINT(input)) private fun writePurity(out: DataOutput, purity: PurityInferenceResult) { out.writeBoolean(purity.mutatesThis) writeRanges(out, purity.mutatedRefs) writeNullable(out, purity.singleCall) { writeRange(out, it) } } private fun readPurity(input: DataInput): PurityInferenceResult { return PurityInferenceResult(input.readBoolean(), readRanges(input), readNullable(input) { readRange(input) }) } private fun writeContract(out: DataOutput, contract: PreContract) { return when (contract) { is DelegationContract -> { out.writeByte(0) writeRange(out, contract.expression); out.writeBoolean(contract.negated) } is KnownContract -> { out.writeByte(1) writeContractArguments(out, contract.contract.constraints) out.writeByte(contract.contract.returnValue.ordinal()) } is MethodCallContract -> { out.writeByte(2) writeRange(out, contract.call) writeSeq(out, contract.states) { writeContractArguments(out, it) } } is NegatingContract -> { out.writeByte(3) writeContract(out, contract.negated) } is SideEffectFilter -> { out.writeByte(4) writeRanges(out, contract.expressionsToCheck) writeSeq(out, contract.contracts) { writeContract(out, it) } } else -> throw IllegalArgumentException(contract.toString()) } } private fun readContract(input: DataInput): PreContract { return when (input.readByte().toInt()) { 0 -> DelegationContract(readRange(input), input.readBoolean()) 1 -> KnownContract(StandardMethodContract(readContractArguments(input).toTypedArray(), readReturnValue(input))) 2 -> MethodCallContract(readRange(input), readSeq(input) { readContractArguments(input) }) 3 -> NegatingContract(readContract(input)) else -> SideEffectFilter(readRanges(input), readSeq(input) { readContract(input) }) } } private fun writeContractArguments(out: DataOutput, arguments: List<ValueConstraint>) { writeSeq(out, arguments) { out.writeByte(it.ordinal) } } private fun readContractArguments(input: DataInput): MutableList<ValueConstraint> { return readSeq(input) { readValueConstraint(input) } } private fun readValueConstraint(input: DataInput) = ValueConstraint.values()[input.readByte().toInt()] private fun readReturnValue(input: DataInput) = ContractReturnValue.valueOf(input.readByte().toInt()) }
apache-2.0
18d4467e71fa5d744619bf11fe9128eb
38.449367
140
0.720841
4.370968
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/blockingCallsDetection/CoroutineBlockingCallInspectionUtils.kt
1
5550
// 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.inspections.blockingCallsDetection import com.intellij.codeInsight.actions.OptimizeImportsProcessor import com.intellij.openapi.components.service import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.parentOfType import org.jetbrains.kotlin.builtins.isSuspendFunctionType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.formatter.commitAndUnblockDocument import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.idea.intentions.receiverType import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.callUtil.getFirstArgumentExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode internal object CoroutineBlockingCallInspectionUtils { fun isInSuspendLambdaOrFunction(ktElement: KtElement): Boolean { val lambdaArgument = ktElement.parentOfType<KtLambdaArgument>() if (lambdaArgument != null) { val callExpression = lambdaArgument.getStrictParentOfType<KtCallExpression>() ?: return false val call = callExpression.resolveToCall(BodyResolveMode.PARTIAL) ?: return false val parameterForArgument = call.getParameterForArgument(lambdaArgument) ?: return false return parameterForArgument.returnType?.isSuspendFunctionType ?: false } return ktElement.parentOfType<KtNamedFunction>()?.hasModifier(KtTokens.SUSPEND_KEYWORD) ?: false } fun isKotlinxOnClasspath(ktElement: KtElement): Boolean { val module = ModuleUtilCore.findModuleForPsiElement(ktElement) ?: return false val searchScope = GlobalSearchScope.moduleWithLibrariesScope(module) return module.project .service<JavaPsiFacade>() .findClass(DISPATCHERS_FQN, searchScope) != null } fun isInsideFlowChain(resolvedCall: ResolvedCall<*>): Boolean { val descriptor = resolvedCall.resultingDescriptor val isFlowGenerator = descriptor.fqNameOrNull()?.asString()?.startsWith(FLOW_PACKAGE_FQN) ?: false return descriptor.receiverType()?.fqName?.asString() == FLOW_FQN || (descriptor.receiverType() == null && isFlowGenerator) } fun isCalledInsideNonIoContext(resolvedCall: ResolvedCall<*>): Boolean { val callFqn = resolvedCall.resultingDescriptor?.fqNameSafe?.asString() ?: return false if (callFqn != WITH_CONTEXT_FQN) return false return isNonBlockingDispatcher(resolvedCall) } private fun isNonBlockingDispatcher(call: ResolvedCall<out CallableDescriptor>): Boolean { val dispatcherFqnOrNull = call.getFirstArgumentExpression() ?.resolveToCall() ?.resultingDescriptor ?.fqNameSafe?.asString() return dispatcherFqnOrNull != null && dispatcherFqnOrNull != IO_DISPATCHER_FQN } fun postProcessQuickFix(replacedElement: KtElement, project: Project) { val containingKtFile = replacedElement.containingKtFile ShortenReferences.DEFAULT.process(replacedElement.reformatted() as KtElement) OptimizeImportsProcessor(project, containingKtFile).run() containingKtFile.commitAndUnblockDocument() } tailrec fun KtExpression.findFlowOnCall(): ResolvedCall<out CallableDescriptor>? { val dotQualifiedExpression = this.getStrictParentOfType<KtDotQualifiedExpression>() ?: return null val candidate = dotQualifiedExpression .children .asSequence() .filterIsInstance<KtCallExpression>() .mapNotNull { it.resolveToCall(BodyResolveMode.PARTIAL) } .firstOrNull { it.isCalling(FqName(FLOW_ON_FQN)) } return candidate ?: dotQualifiedExpression.findFlowOnCall() } const val BLOCKING_EXECUTOR_ANNOTATION = "org.jetbrains.annotations.BlockingExecutor" const val NONBLOCKING_EXECUTOR_ANNOTATION = "org.jetbrains.annotations.NonBlockingExecutor" const val DISPATCHERS_FQN = "kotlinx.coroutines.Dispatchers" const val IO_DISPATCHER_FQN = "kotlinx.coroutines.Dispatchers.IO" const val MAIN_DISPATCHER_FQN = "kotlinx.coroutines.Dispatchers.Main" const val DEFAULT_DISPATCHER_FQN = "kotlinx.coroutines.Dispatchers.Default" const val COROUTINE_SCOPE = "kotlinx.coroutines.CoroutineScope" const val COROUTINE_CONTEXT = "kotlin.coroutines.CoroutineContext" const val FLOW_ON_FQN = "kotlinx.coroutines.flow.flowOn" const val FLOW_PACKAGE_FQN = "kotlinx.coroutines.flow" const val FLOW_FQN = "kotlinx.coroutines.flow.Flow" const val WITH_CONTEXT_FQN = "kotlinx.coroutines.withContext" }
apache-2.0
68ff3155333210550746039b3f33a72e
52.893204
158
0.767748
5.138889
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/util/modifierListModifactor.kt
2
2514
// 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.util import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode fun KtModifierListOwner.addAnnotation( annotationFqName: FqName, annotationInnerText: String? = null, whiteSpaceText: String = "\n", addToExistingAnnotation: ((KtAnnotationEntry) -> Boolean)? = null ): Boolean { val annotationText = when (annotationInnerText) { null -> "@${annotationFqName.render()}" else -> "@${annotationFqName.render()}($annotationInnerText)" } val psiFactory = KtPsiFactory(this) val modifierList = modifierList if (modifierList == null) { val addedAnnotation = addAnnotationEntry(psiFactory.createAnnotationEntry(annotationText)) ShortenReferences.DEFAULT.process(addedAnnotation) return true } val entry = findAnnotation(annotationFqName) if (entry == null) { // no annotation val newAnnotation = psiFactory.createAnnotationEntry(annotationText) val addedAnnotation = modifierList.addBefore(newAnnotation, modifierList.firstChild) as KtElement val whiteSpace = psiFactory.createWhiteSpace(whiteSpaceText) modifierList.addAfter(whiteSpace, addedAnnotation) ShortenReferences.DEFAULT.process(addedAnnotation) return true } if (addToExistingAnnotation != null) { return addToExistingAnnotation(entry) } return false } fun KtAnnotated.findAnnotation(annotationFqName: FqName): KtAnnotationEntry? { if (annotationEntries.isEmpty()) return null val context = analyze(bodyResolveMode = BodyResolveMode.PARTIAL) val descriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] ?: return null // Make sure all annotations are resolved descriptor.annotations.toList() return annotationEntries.firstOrNull { entry -> context.get(BindingContext.ANNOTATION, entry)?.fqName == annotationFqName } } fun KtAnnotated.hasJvmFieldAnnotation(): Boolean = findAnnotation(JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME) != null
apache-2.0
1a438a06a8ce057e386cdab934711b4e
37.676923
158
0.749801
5.007968
false
false
false
false
smmribeiro/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUObjectLiteralExpression.kt
2
2150
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.PsiMethod import com.intellij.psi.PsiNewExpression import com.intellij.psi.PsiType import com.intellij.psi.ResolveResult import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* @ApiStatus.Internal class JavaUObjectLiteralExpression( override val sourcePsi: PsiNewExpression, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UObjectLiteralExpression, UCallExpression, UMultiResolvable { override val declaration: UClass by lz { JavaUClass.create(sourcePsi.anonymousClass!!, this) } override val classReference: UReferenceExpression? by lz { sourcePsi.classReference?.let { ref -> JavaConverter.convertReference(ref, this) as? UReferenceExpression } } override val valueArgumentCount: Int get() = sourcePsi.argumentList?.expressions?.size ?: 0 override val valueArguments: List<UExpression> by lz { sourcePsi.argumentList?.expressions?.map { JavaConverter.convertOrEmpty(it, this) } ?: emptyList() } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override val typeArgumentCount: Int by lz { sourcePsi.classReference?.typeParameters?.size ?: 0 } override val typeArguments: List<PsiType> get() = sourcePsi.classReference?.typeParameters?.toList() ?: emptyList() override fun resolve(): PsiMethod? = sourcePsi.resolveMethod() override fun multiResolve(): Iterable<ResolveResult> = sourcePsi.classReference?.multiResolve(false)?.asIterable() ?: emptyList() }
apache-2.0
7b78055a26b1574d071938bf6e21a6bf
37.392857
103
0.766047
4.694323
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/importexport/usecases/GetShortcutSelectionDialogUseCase.kt
1
2845
package ch.rmy.android.http_shortcuts.activities.settings.importexport.usecases import android.app.Activity import android.app.Dialog import ch.rmy.android.framework.extensions.addOrRemove import ch.rmy.android.framework.extensions.runFor import ch.rmy.android.framework.viewmodel.WithDialog import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutRepository import ch.rmy.android.http_shortcuts.utils.DialogBuilder import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.actions.getActionButton import com.afollestad.materialdialogs.callbacks.onShow import javax.inject.Inject class GetShortcutSelectionDialogUseCase @Inject constructor( private val shortcutRepository: ShortcutRepository, ) { suspend operator fun invoke(onConfirm: (Collection<ShortcutId>?) -> Unit): DialogState { val shortcuts = shortcutRepository.getShortcuts() return object : DialogState { override val id = "select-shortcuts-for-export" private val selectedShortcutIds = shortcuts.map { it.id }.toMutableSet() private var onSelectionChanged: (() -> Unit)? = null override fun createDialog(activity: Activity, viewModel: WithDialog?): Dialog = DialogBuilder(activity) .title(R.string.dialog_title_select_shortcuts_for_export) .runFor(shortcuts) { shortcut -> checkBoxItem( name = shortcut.name, shortcutIcon = shortcut.icon, checked = { shortcut.id in selectedShortcutIds }, ) { isChecked -> selectedShortcutIds.addOrRemove(shortcut.id, isChecked) onSelectionChanged?.invoke() } } .positive(R.string.dialog_button_export) { onConfirm(selectedShortcutIds.takeUnless { it.size == shortcuts.size }) } .negative(R.string.dialog_cancel) .dismissListener { onSelectionChanged = null viewModel?.onDialogDismissed(this) } .build() .onShow { dialog -> val okButton = dialog.getActionButton(WhichButton.POSITIVE) onSelectionChanged = { okButton.isEnabled = selectedShortcutIds.isNotEmpty() } onSelectionChanged?.invoke() } } } }
mit
e18d831124616e91297f6605ff5e56e8
43.453125
95
0.605975
5.513566
false
false
false
false
glorantq/KalanyosiRamszesz
src/glorantq/ramszesz/commands/MemeCommand.kt
1
6332
package glorantq.ramszesz.commands import glorantq.ramszesz.utils.BotUtils import glorantq.ramszesz.memes.* import org.slf4j.Logger import org.slf4j.LoggerFactory import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent import sx.blah.discord.handle.obj.IUser import sx.blah.discord.util.EmbedBuilder import java.util.* import kotlin.concurrent.thread /** * Created by glora on 2017. 07. 26.. */ class MemeCommand : ICommand { override val commandName: String get() = "memegen" override val description: String get() = "Generate memes in Discord" override val permission: Permission get() = Permission.USER override val extendedHelp: String get() = "Generate memes in Discord." override val aliases: List<String> get() = listOf("meme") override val usage: String get() = "Meme [Arguments]" companion object { val memes: ArrayList<IMeme> = ArrayList() } init { memes.add(MemeList()) memes.add(TriggeredMeme()) memes.add(NumberOneMeme()) memes.add(ThinkingMeme()) memes.add(EmojiMovieMeme()) memes.add(RainbowMeme()) memes.add(OpenCVDemo()) memes.add(LensflareMeme()) } val logger: Logger = LoggerFactory.getLogger(this::class.java) val checkIDRegex: Regex = Regex("^<@![0-9]{18}>$|^<@[0-9]{18}>$") val replaceTagsRegex: Regex = Regex("<@!|<@|>") override fun execute(event: MessageReceivedEvent, args: List<String>) { if(args.isEmpty()) { BotUtils.sendUsageEmbed("You need to provide a meme, and optionally arguments", "Meme", event.author, event, this) return } val parts: List<String> = event.message.content.split(" ") val memeArgs: List<String> = if (parts.size == 1) { java.util.ArrayList() } else { parts.subList(1, parts.size) } for(meme: IMeme in memes) { if(meme.name.equals(args[0], true)) { if(meme.parameters.isNotEmpty()) { if(memeArgs.size - 1 < meme.parameters.size) { BotUtils.sendUsageEmbed("This meme requires more arguments!", "Meme", event.author, event, this) return } else if(memeArgs.size - 1 > meme.parameters.size) { BotUtils.sendUsageEmbed("This meme requires fewer arguments!", "Meme", event.author, event, this) return } else { for(i: Int in 1 until memeArgs.size) { when(meme.parameters[i - 1].type) { MemeParameter.Companion.Type.STRING -> { setParam(i - 1, meme, memeArgs[i]) } MemeParameter.Companion.Type.INT -> { try { setParam(i - 1, meme, memeArgs[i].toInt()) } catch (e: NumberFormatException) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Meme", "`${memeArgs[i]}` is not a valid number!", event.author), event.channel) return } } MemeParameter.Companion.Type.USER -> { val idParam: String = memeArgs[i] val userId: Long if(idParam.equals("random_user", true)) { userId = event.guild.users[Random().nextInt(event.guild.users.size)].longID } else { if (!idParam.matches(checkIDRegex)) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Meme", "`$idParam` is not a valid tag!", event.author), event.channel) return } else { userId = idParam.replace(replaceTagsRegex, "").toLong() } } val user: IUser? = event.guild.getUserByID(userId) if(user == null) { BotUtils.sendMessage(BotUtils.createSimpleEmbed("Meme", "`$userId` is not a valid ID!", event.author), event.channel) return } else { setParam(i - 1, meme, user) } } } } } } exec(event, meme) return } } BotUtils.sendMessage(BotUtils.createSimpleEmbed("Meme Generator", "`${args[0]}` is not a valid meme", event.author), event.channel) } private fun exec(event: MessageReceivedEvent, meme: IMeme) { thread(name = "MemeExec-${meme.name}-${event.author.name}-${System.nanoTime()}", isDaemon = true, start = true) { logger.info("Executing meme...") try { meme.execute(event) } catch (e: Exception) { val embed: EmbedBuilder = BotUtils.embed("Meme Generator", event.author) embed.withDescription("I couldn't deliver your meme because @glorantq can't code") embed.appendField(e::class.simpleName, e.message, false) BotUtils.sendMessage(embed.build(), event.channel) } logger.info("Finished!") } } private fun setParam(index: Int, meme: IMeme, value: Any) { val param: MemeParameter = meme.parameters[index] param.value = value val parameters: ArrayList<MemeParameter> = meme.parameters.clone() as ArrayList<MemeParameter> parameters[index] = param meme.parameters = parameters println(meme.parameters[index].value) } }
gpl-3.0
bae7064a4efa0a1fba23376936b5bc5b
42.081633
168
0.493841
5.081862
false
false
false
false
blademainer/intellij-community
plugins/settings-repository/src/RepositoryManager.kt
4
4275
/* * 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.openapi.progress.ProgressIndicator import gnu.trove.THashSet import java.io.InputStream import java.util.Collections public interface RepositoryManager { public fun createRepositoryIfNeed(): Boolean /** * Think twice before use */ public fun deleteRepository() public fun isRepositoryExists(): Boolean public fun getUpstream(): String? public fun hasUpstream(): Boolean /** * Return error message if failed */ public fun setUpstream(url: String?, branch: String? = null) public fun read(path: String): InputStream? /** * Returns false if file is not written (for example, due to ignore rules). */ public fun write(path: String, content: ByteArray, size: Int): Boolean public fun delete(path: String) public fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean) /** * Not all implementations support progress indicator (will not be updated on progress). * * syncType will be passed if called before sync. * * If fixStateIfCannotCommit, repository state will be fixed before commit. */ public fun commit(indicator: ProgressIndicator? = null, syncType: SyncType? = null, fixStateIfCannotCommit: Boolean = true): Boolean public fun getAheadCommitsCount(): Int public fun commit(paths: List<String>) public fun push(indicator: ProgressIndicator? = null) public fun fetch(indicator: ProgressIndicator? = null): Updater public fun pull(indicator: ProgressIndicator? = null): UpdateResult? public fun has(path: String): Boolean public fun resetToTheirs(indicator: ProgressIndicator): UpdateResult? public fun resetToMy(indicator: ProgressIndicator, localRepositoryInitializer: (() -> Unit)?): UpdateResult? public fun canCommit(): Boolean public interface Updater { fun merge(): UpdateResult? // valid only if merge was called before val definitelySkipPush: Boolean } } public interface UpdateResult { val changed: Collection<String> val deleted: Collection<String> } val EMPTY_UPDATE_RESULT = ImmutableUpdateResult(Collections.emptySet(), Collections.emptySet()) public data class ImmutableUpdateResult(override val changed: Collection<String>, override val deleted: Collection<String>) : UpdateResult { public fun toMutable(): MutableUpdateResult = MutableUpdateResult(changed, deleted) } public data class MutableUpdateResult(changed: Collection<String>, deleted: Collection<String>) : UpdateResult { override val changed = THashSet(changed) override val deleted = THashSet(deleted) fun add(result: UpdateResult?): MutableUpdateResult { if (result != null) { add(result.changed, result.deleted) } return this } fun add(newChanged: Collection<String>, newDeleted: Collection<String>): MutableUpdateResult { changed.removeAll(newDeleted) deleted.removeAll(newChanged) changed.addAll(newChanged) deleted.addAll(newDeleted) return this } fun addChanged(newChanged: Collection<String>): MutableUpdateResult { deleted.removeAll(newChanged) changed.addAll(newChanged) return this } } public fun UpdateResult?.isEmpty(): Boolean = this == null || (changed.isEmpty() && deleted.isEmpty()) public fun UpdateResult?.concat(result: UpdateResult?): UpdateResult? { if (result.isEmpty()) { return this } else if (isEmpty()) { return result } else { this!! return MutableUpdateResult(changed, deleted).add(result!!) } } public class AuthenticationException(cause: Throwable) : RuntimeException(cause.getMessage(), cause)
apache-2.0
7f7d0d60b1e025dd1fbeff72a6f68dfc
29.326241
141
0.737076
4.621622
false
false
false
false
seventhroot/elysium
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/undirected/LogComponent.kt
1
2825
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.chatchannel.undirected import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.pipeline.UndirectedChatChannelPipelineComponent import com.rpkit.chat.bukkit.context.UndirectedChatChannelMessageContext import org.bukkit.Bukkit import org.bukkit.configuration.serialization.ConfigurationSerializable import org.bukkit.configuration.serialization.SerializableAs import java.io.BufferedWriter import java.io.File import java.io.FileWriter import java.io.IOException import java.text.SimpleDateFormat import java.util.* /** * Log component. * Logs messages to a dated log file. */ @SerializableAs("LogComponent") class LogComponent(private val plugin: RPKChatBukkit): UndirectedChatChannelPipelineComponent, ConfigurationSerializable { override fun process(context: UndirectedChatChannelMessageContext): UndirectedChatChannelMessageContext { val logDirectory = File(plugin.dataFolder, "logs") val logDateFormat = SimpleDateFormat("yyyy-MM-dd") val datedLogDirectory = File(logDirectory, logDateFormat.format(Date())) if (!datedLogDirectory.exists()) { if (!datedLogDirectory.mkdirs()) throw IOException("Could not create log directory. Does the server have permission to write to the directory?") } val log = File(datedLogDirectory, context.chatChannel.name + ".log") if (!log.exists()) { if (!log.createNewFile()) throw IOException("Failed to create log file. Does the server have permission to write to the directory?") } val writer = BufferedWriter(FileWriter(log, true)) val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") writer.append("[").append(dateFormat.format(Date())).append("] ").append(context.message).append("\n") writer.close() return context } override fun serialize(): MutableMap<String, Any> { return mutableMapOf() } companion object { @JvmStatic fun deserialize(serialized: MutableMap<String, Any>): LogComponent { return LogComponent(Bukkit.getPluginManager().getPlugin("rpk-chat-bukkit") as RPKChatBukkit) } } }
apache-2.0
e506c34f37692ca566f8840641cc615b
39.371429
127
0.724248
4.72408
false
true
false
false
gradle/gradle
subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/DelegatedGradlePropertiesIntegrationTest.kt
3
8002
package org.gradle.kotlin.dsl.integration import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest import org.hamcrest.CoreMatchers.containsString import org.hamcrest.MatcherAssert.assertThat import org.junit.Test /** * See https://docs.gradle.org/current/userguide/build_environment.html */ class DelegatedGradlePropertiesIntegrationTest : AbstractKotlinIntegrationTest() { @Test fun `non-nullable delegated property access of non-existing gradle property throws`() { withSettings( """ val nonExisting: String by settings println(nonExisting) """ ) assertThat( buildAndFail("help").error, containsString("Cannot get non-null property 'nonExisting' on settings '${projectRoot.name}' as it does not exist") ) withSettings("") withBuildScript( """ val nonExisting: String by project println(nonExisting) """ ) assertThat( buildAndFail("help").error, containsString("Cannot get non-null property 'nonExisting' on root project '${projectRoot.name}' as it does not exist") ) } @Test fun `delegated properties follow Gradle mechanics and allow to model optional properties via nullable kotlin types`() { // given: build root gradle.properties file withFile( "gradle.properties", """ setBuildProperty=build value emptyBuildProperty= userHomeOverriddenBuildProperty=build value cliOverriddenBuildProperty=build value projectMutatedBuildProperty=build value """.trimIndent() ) // and: gradle user home gradle.properties file withFile( "gradle-user-home/gradle.properties", """ setUserHomeProperty=user home value emptyUserHomeProperty= userHomeOverriddenBuildProperty=user home value cliOverriddenUserHomeProperty=user home value projectMutatedUserHomeProperty=user home value """.trimIndent() ) // and: isolated gradle user home executer.withGradleUserHomeDir(existing("gradle-user-home")) executer.requireIsolatedDaemons() // and: gradle command line with properties val buildArguments = arrayOf( "-PsetCliProperty=cli value", "-PemptyCliProperty=", "-PcliOverriddenBuildProperty=cli value", "-PcliOverriddenUserHomeProperty=cli value", "-Dorg.gradle.project.setOrgGradleProjectSystemProperty=system property value", "-Dorg.gradle.project.emptyOrgGradleProjectSystemProperty=", "help" ) // when: both settings and project scripts asserting on delegated properties withSettings(requirePropertiesFromSettings()) withBuildScript(requirePropertiesFromProject()) // then: build(*buildArguments) // when: project script buildscript block asserting on delegated properties withSettings("") withBuildScript( """ buildscript { ${requirePropertiesFromProject()} } """ ) // then: build(*buildArguments) } private fun requirePropertiesFromSettings() = """ ${requireNotOverriddenPropertiesFrom("settings")} ${requireOverriddenPropertiesFrom("settings")} ${requireEnvironmentPropertiesFrom("settings")} ${requireProjectMutatedPropertiesOriginalValuesFrom("settings")} """.trimIndent() private fun requirePropertiesFromProject() = """ ${requireNotOverriddenPropertiesFrom("project")} ${requireOverriddenPropertiesFrom("project")} ${requireEnvironmentPropertiesFrom("project")} ${requireProjectExtraProperties()} ${requireProjectMutatedPropertiesOriginalValuesFrom("project")} ${requireProjectPropertiesMutation()} """.trimIndent() private fun requireNotOverriddenPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "setUserHomeProperty", """"user home value"""")} ${requireProperty<String>(source, "emptyUserHomeProperty", """""""")} ${requireProperty<String>(source, "setBuildProperty", """"build value"""")} ${requireProperty<String>(source, "emptyBuildProperty", """""""")} ${requireProperty<String>(source, "setCliProperty", """"cli value"""")} ${requireProperty<String>(source, "emptyCliProperty", """""""")} ${requireNullableProperty<String>(source, "unsetProperty", "null")} """.trimIndent() private fun requireOverriddenPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "userHomeOverriddenBuildProperty", """"user home value"""")} ${requireProperty<String>(source, "cliOverriddenBuildProperty", """"cli value"""")} ${requireProperty<String>(source, "cliOverriddenUserHomeProperty", """"cli value"""")} """.trimIndent() private fun requireEnvironmentPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "setOrgGradleProjectSystemProperty", """"system property value"""")} ${requireProperty<String>(source, "emptyOrgGradleProjectSystemProperty", """""""")} """.trimIndent() private fun requireProjectExtraProperties() = """ run { extra["setExtraProperty"] = "extra value" extra["emptyExtraProperty"] = "" extra["unsetExtraProperty"] = null val setExtraProperty: String by project require(setExtraProperty == "extra value") val emptyExtraProperty: String by project require(emptyExtraProperty == "") val unsetExtraProperty: String? by project require(unsetExtraProperty == null) setProperty("setExtraProperty", "mutated") require(setExtraProperty == "mutated") } """.trimIndent() private fun requireProjectMutatedPropertiesOriginalValuesFrom(source: String) = """ ${requireProperty<String>(source, "projectMutatedBuildProperty", """"build value"""")} ${requireProperty<String>(source, "projectMutatedUserHomeProperty", """"user home value"""")} """.trimIndent() private fun requireProjectPropertiesMutation() = """ run { val projectMutatedBuildProperty: String by project require(projectMutatedBuildProperty == "build value") setProperty("projectMutatedBuildProperty", "mutated") require(projectMutatedBuildProperty == "mutated") val projectMutatedUserHomeProperty: String by project require(projectMutatedUserHomeProperty == "user home value") setProperty("projectMutatedUserHomeProperty", "mutated") require(projectMutatedUserHomeProperty == "mutated") } """.trimIndent() private inline fun <reified T : Any> requireProperty(source: String, name: String, valueRepresentation: String) = requireProperty(source, name, T::class.qualifiedName!!, valueRepresentation) private inline fun <reified T : Any> requireNullableProperty(source: String, name: String, valueRepresentation: String) = requireProperty(source, name, "${T::class.qualifiedName!!}?", valueRepresentation) private fun requireProperty(source: String, name: String, type: String, valueRepresentation: String) = """ run { val $name: $type by $source require($name == $valueRepresentation) { ${"\"".repeat(3)}expected $name to be '$valueRepresentation' but was '${'$'}$name'${"\"".repeat(3)} } } """.trimIndent() }
apache-2.0
4ceaff59592323ca2f44c703862e3884
34.723214
131
0.628593
6.057532
false
false
false
false
Camano/CoolKotlin
calendar/dayssince.kt
1
5340
import java.util.Calendar import java.util.HashMap import java.util.Scanner /************************************** * How to use: * Enter a date like: * [day] [month] [year] * EXAMPLE: * 01 01 2000 */ internal fun IsLeapYear(y: Int): Boolean { var bl = false if (y % 4 == 0) { bl = true } return bl } internal fun MonthSize(m: Int, y: Int): Int { var size = 0 val monthsize = HashMap<Int, Int>() monthsize.put(1, 31) monthsize.put(2, 28) monthsize.put(3, 31) monthsize.put(4, 30) monthsize.put(5, 31) monthsize.put(6, 30) monthsize.put(7, 31) monthsize.put(8, 31) monthsize.put(9, 30) monthsize.put(10, 31) monthsize.put(11, 30) monthsize.put(12, 31) if (IsLeapYear(y) && m == 2) { size = 29 } else { size = monthsize[m] as Int } return size } internal fun GetDayCount(curday: Int, curmonth: Int, curyear: Int, gday: Int, gmonth: Int, gyear: Int): Int { var calc = 0 // calculate year days if (gmonth < curmonth) { for (c in gyear..curyear - 1) { if (IsLeapYear(c)) { calc += 366 } else { calc += 365 } } } else if (gmonth == curmonth) { if (gday <= curday) { for (c in gyear..curyear - 1) { if (IsLeapYear(c)) { calc += 366 } else { calc += 365 } } } } else { for (c in gyear + 1..curyear - 1) { if (IsLeapYear(c)) { calc += 366 } else { calc += 365 } } } if ((curyear - gyear) / 100 >= 1) { calc -= (curyear - gyear) / 100 } // calculate month days if (gmonth > curmonth) { for (c in gmonth..12) { calc += MonthSize(c, curyear - 1) } for (c in 1..curmonth - 1) { calc += MonthSize(c, curyear) } } else { if (gday > curday) { for (c in gmonth..curmonth - 1 - 1) { calc += MonthSize(c, curyear) } } else { for (c in gmonth..curmonth - 1) { calc += MonthSize(c, curyear) } } } // calculate days if (gday > curday) { if (curmonth == 1) { for (c in gday..MonthSize(12, curyear - 1) - 1) { calc += 1 } } else { for (c in gday..MonthSize(curmonth - 1, curyear) - 1) { calc += 1 } } for (c in 1..curday) { calc += 1 } } else { for (c in gday..curday - 1) { calc += 1 } } return calc } fun main(args: Array<String>) { try { arrayOf("", "") val currentyear = Calendar.getInstance().get(Calendar.YEAR) val currentmonth = Calendar.getInstance().get(Calendar.MONTH) + 1 val currentday = Calendar.getInstance().get(Calendar.DAY_OF_MONTH) var inputday = 0 var inputmonth = 0 var inputyear = 0 val inp = Scanner(System.`in`) val input = inp.nextLine().split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val inpn = intArrayOf(Integer.parseInt(input[0]), Integer.parseInt(input[1]), Integer.parseInt(input[2])) var cont = true if (Integer.parseInt(input[0]) < 1 || Integer.parseInt(input[0]) > 31) { println("Please enter valid day. 1 | 31") cont = false } else { inputday = Integer.parseInt(input[0]) } if (Integer.parseInt(input[1]) < 1 || Integer.parseInt(input[1]) > 12) { println("Please enter valid month. 1 | 12") cont = false } else { inputmonth = Integer.parseInt(input[1]) } if (Integer.parseInt(input[2]) < 1) { println("Please enter valid year. 1 | " + currentyear) cont = false } else { inputyear = Integer.parseInt(input[2]) } if (inpn[2] > currentyear) { println("Please enter day in the past.") cont = false } else if (inpn[2] == currentyear) { if (inpn[1] > currentmonth) { println("Please enter day in the past.") cont = false } else if (inpn[1] == currentmonth) { if (inpn[0] > currentday) { println("Please enter day in the past.") cont = false } else if (inpn[0] == currentday) { println("You entered today!") cont = false } else if (inpn[0] < currentday) { cont = true } } } if (cont) { println("\n\n\n\n$inputday/$inputmonth/$inputyear Was:") println("-----------------") println(GetDayCount(currentday, currentmonth, currentyear, inputday, inputmonth, inputyear)) println("-----------------") println("Days ago. \n") } } catch (e: Exception) { println("Error, Please enter input as '[day] [month] [year]' EXAMPLE: 01 01 2000") } }
apache-2.0
0e18ce7dbc720f77112b81d28f2f2175
25.969697
113
0.462547
3.935151
false
false
false
false
andretietz/retroauth
demo-android/src/main/java/com/andretietz/retroauth/demo/auth/LoginActivity.kt
1
2800
package com.andretietz.retroauth.demo.auth import android.annotation.SuppressLint import android.os.Bundle import android.webkit.CookieManager import android.webkit.WebView import android.webkit.WebViewClient import androidx.lifecycle.lifecycleScope import com.andretietz.retroauth.AuthenticationActivity import com.andretietz.retroauth.Credentials import com.andretietz.retroauth.demo.databinding.ActivityLoginBinding import com.github.scribejava.core.oauth.OAuth20Service import com.squareup.moshi.JsonClass import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import retrofit2.http.GET import retrofit2.http.Header import javax.inject.Inject @AndroidEntryPoint class LoginActivity : AuthenticationActivity() { @Inject lateinit var helper: OAuth20Service @Inject lateinit var api: SignInApi @SuppressLint("SetJavaScriptEnabled") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) CookieManager.getInstance().removeAllCookies { } val views = ActivityLoginBinding.inflate(layoutInflater) setContentView(views.root) views.webView.loadUrl(helper.authorizationUrl) views.webView.settings.javaScriptEnabled = true views.webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { val authorization = helper.extractAuthorization(url) val code = authorization.code if (code == null) { view.loadUrl(url) } else { lifecycleScope.launch(Dispatchers.IO) { val token = helper.getAccessToken(code) val userInfo = api.getUser("Bearer ${token.accessToken}") withContext(Dispatchers.Main) { val account = createOrGetAccount(userInfo.login) storeCredentials( account, GithubAuthenticator.createTokenType(application), Credentials(token.accessToken) ) // storeUserData(account, "email", userInfo.email) finalizeAuthentication(account) } } } return true } } } interface SignInApi { /** * We call this method right after authentication in order to get user information * to store within the account. At this point of time, the account and it's token isn't stored * yet, why we cannot use the annotation. * * https://docs.github.com/en/rest/reference/users#get-the-authenticated-user */ @GET("user") suspend fun getUser(@Header("Authorization") token: String): User @JsonClass(generateAdapter = true) data class User( val login: String ) } }
apache-2.0
d983bd9932c182d7199766748a63dd8f
33.146341
98
0.711071
4.886562
false
false
false
false
industrial-data-space/trusted-connector
ids-dataflow-control/src/main/kotlin/de/fhg/aisec/ids/dataflowcontrol/lucon/CounterExampleImpl.kt
1
3417
/*- * ========================LICENSE_START================================= * ids-dataflow-control * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.dataflowcontrol.lucon import alice.tuprolog.Struct import alice.tuprolog.Term import de.fhg.aisec.ids.api.router.CounterExample import java.util.LinkedList class CounterExampleImpl(term: Term) : CounterExample() { init { val traceIterator = (term as Struct).listIterator() val steps = LinkedList<String>() // process explanation val reasonIterator = (traceIterator.next() as Struct).listIterator() val sb = StringBuilder() .append("Service ") .append(reasonIterator.next().toString()) .append(" may receive messages") reasonIterator.next() // val explanation = reasonIterator.next() // if (explanation.isList) { // sb.append(" labeled [") // appendCSList(sb, explanation) // sb.append("]") // } sb.append(", which is forbidden by rule \"") .append(reasonIterator.next().toString()) .append("\".") this.explanation = sb.toString() // process steps and prepend them to list (inverse trace to get the right order) traceIterator.forEachRemaining { t: Term? -> steps.addFirst(termToStep(t)) } this.steps = steps } companion object { fun termToStep(t: Term?): String? { if (t == null) { return null } val traceEntry = t as Struct val sb = StringBuilder() // node name is the head of the list val node = traceEntry.listHead().toString() sb.append(node) // the label list is the new head of the remaining list (tail) val labelList = traceEntry.listTail().listHead() return if (!labelList.isEmptyList) { sb.append(" receives message labelled ") appendCSList(sb, labelList) sb.toString() } else { sb.append(" receives message without labels").toString() } } private fun appendCSList(sb: StringBuilder?, l: Term?) { if (sb == null || l == null) { return } if (l.isList && !l.isEmptyList) { val listIterator = (l as Struct).listIterator() // add first element sb.append(listIterator.next().toString()) // add remaining elements listIterator.forEachRemaining { lt: Term -> sb.append(", ").append(lt.toString()) } } } } }
apache-2.0
2de349cb8f0744292b17d255a6aecf33
37.393258
99
0.552824
4.726141
false
false
false
false
RyotaMurohoshi/snippets
kotlin/kotlin_java_interpolator/src/main/kotlin/com/muhron/kotlin_java_interpolator/java_method_usage.kt
1
547
package com.muhron.kotlin_java_interpolator fun main(args: Array<String>) { f10() } fun f10(): Unit { val str = Utility.returnStringJava() println(str?.length) println(str.length) val strNotNull: String = str val strNullable: String? = str } fun f11(): Unit { val str: String = Utility.returnStringJava() println(str.length) println(str?.length) } fun f12(): Unit { val str: String? = Utility.returnStringJava() println(str?.length) // println(str.length)は、コンパイルエラー }
mit
ef825f6d931d9669b182a136f4cac8e9
15.46875
49
0.648956
3.29375
false
false
false
false
McGars/Zoomimage
zoomimage/src/main/java/mcgars/com/zoomimage/listeners/FromImageViewListener.kt
1
1351
package mcgars.com.zoomimage.listeners import android.view.View import android.widget.ImageView import com.alexvasilkov.gestures.animation.ViewPositionAnimator import com.alexvasilkov.gestures.transition.ViewsCoordinator import com.alexvasilkov.gestures.transition.ViewsTracker import com.alexvasilkov.gestures.transition.ViewsTransitionAnimator class FromImageViewListener<ID>( private val imageView: ImageView, private val mTracker: ViewsTracker<ID>, private val mAnimator: ViewsTransitionAnimator<ID> ) : ViewsCoordinator.OnRequestViewListener<ID> { init { mAnimator.addPositionUpdateListener(UpdateListener()) } override fun onRequestView(id: ID) { // Trying to find requested view on screen. If it is not currently on screen // or it is not fully visible than we should scroll to it at first. val position = mTracker.getPositionForId(id) if (position == ViewsTracker.NO_POSITION) { return // Nothing we can do } mAnimator.setFromView(id, imageView) } private inner class UpdateListener : ViewPositionAnimator.PositionUpdateListener { override fun onPositionUpdate(state: Float, isLeaving: Boolean) { imageView.visibility = if (state == 0f && isLeaving) View.VISIBLE else View.INVISIBLE } } }
apache-2.0
69601fc5b35b1d1bd9048ae450ca9a74
33.641026
97
0.725389
4.690972
false
false
false
false
azizbekian/Spyur
app/src/main/kotlin/com/incentive/yellowpages/utils/AnimUtils.kt
1
1341
package com.incentive.yellowpages.utils import android.content.Context import android.support.v4.view.animation.PathInterpolatorCompat import android.transition.Transition import android.view.animation.AnimationUtils import android.view.animation.Interpolator class AnimUtils private constructor() { init { throw RuntimeException("Unable to instantiate class " + javaClass.canonicalName) } open class TransitionListenerAdapter : Transition.TransitionListener { override fun onTransitionStart(transition: Transition) { } override fun onTransitionEnd(transition: Transition) { } override fun onTransitionCancel(transition: Transition) { } override fun onTransitionPause(transition: Transition) { } override fun onTransitionResume(transition: Transition) { } } companion object { private var overshoot: Interpolator? = null val EASE_OUT_CUBIC = PathInterpolatorCompat.create(0.215f, 0.61f, 0.355f, 1f)!! fun getOvershootInterpolator(context: Context): Interpolator { if (overshoot == null) { overshoot = AnimationUtils.loadInterpolator(context, android.R.interpolator.overshoot) } return overshoot!! } } }
gpl-2.0
274b6a46924ec04c675aa98ab406bc60
24.788462
88
0.672632
5.060377
false
false
false
false
newbieandroid/AppBase
app/src/main/java/com/fuyoul/sanwenseller/ui/order/AppointMentTimeActivity.kt
1
4827
package com.fuyoul.sanwenseller.ui.order import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import com.fuyoul.sanwenseller.R import com.fuyoul.sanwenseller.base.BaseActivity import com.fuyoul.sanwenseller.configs.TopBarOption import com.fuyoul.sanwenseller.structure.model.EmptyM import com.fuyoul.sanwenseller.structure.presenter.EmptyP import com.fuyoul.sanwenseller.structure.view.EmptyV import com.fuyoul.sanwenseller.ui.order.fragment.NormalTestFragment import com.fuyoul.sanwenseller.ui.order.fragment.QuickTestFragment import com.fuyoul.sanwenseller.utils.AddFragmentUtils import com.netease.nim.uikit.StatusBarUtils import kotlinx.android.synthetic.main.appointmentlayout.* import net.lucode.hackware.magicindicator.FragmentContainerHelper import net.lucode.hackware.magicindicator.buildins.UIUtil import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView /** * @author: chen * @CreatDate: 2017\10\30 0030 * @Desc: */ class AppointMentTimeActivity : BaseActivity<EmptyM, EmptyV, EmptyP>() { private val mFragmentContainerHelper = FragmentContainerHelper() override fun setLayoutRes(): Int = R.layout.appointmentlayout override fun initData(savedInstanceState: Bundle?) { StatusBarUtils.setTranslucentForImageView(this, topFuncLayout) StatusBarUtils.StatusBarLightMode(this, R.color.color_white) val fragments = ArrayList<Fragment>() fragments.add(NormalTestFragment()) fragments.add(QuickTestFragment()) val addFragmentUtils = AddFragmentUtils(this, R.id.appointmentContent) val commonNavigator = CommonNavigator(this) commonNavigator.adapter = object : CommonNavigatorAdapter() { override fun getTitleView(p0: Context?, p1: Int): IPagerTitleView { val colorTransitionPagerTitleView = ColorTransitionPagerTitleView(this@AppointMentTimeActivity) colorTransitionPagerTitleView.width = UIUtil.getScreenWidth(this@AppointMentTimeActivity) / 4 colorTransitionPagerTitleView.normalColor = resources.getColor(R.color.color_666666) colorTransitionPagerTitleView.selectedColor = resources.getColor(R.color.color_3CC5BC) colorTransitionPagerTitleView.text = when (p1) { 0 -> "详测" 1 -> "闪测" else -> "闪测" } colorTransitionPagerTitleView.setOnClickListener({ mFragmentContainerHelper.handlePageSelected(p1, true) addFragmentUtils.showFragment(fragments[p1], fragments[p1].javaClass.name) }) return colorTransitionPagerTitleView } override fun getCount(): Int = fragments.size override fun getIndicator(p0: Context?): IPagerIndicator { val indicator = LinePagerIndicator(this@AppointMentTimeActivity) indicator.mode = LinePagerIndicator.MODE_EXACTLY indicator.lineHeight = UIUtil.dip2px(this@AppointMentTimeActivity, 4.0).toFloat() indicator.lineWidth = UIUtil.dip2px(this@AppointMentTimeActivity, 15.0).toFloat() indicator.roundRadius = UIUtil.dip2px(this@AppointMentTimeActivity, 3.0).toFloat() indicator.startInterpolator = AccelerateInterpolator() indicator.endInterpolator = DecelerateInterpolator(2.0f) indicator.setColors(resources.getColor(R.color.color_3CC5BC)) return indicator } } appointmentIndicator.navigator = commonNavigator mFragmentContainerHelper.attachMagicIndicator(appointmentIndicator) mFragmentContainerHelper.handlePageSelected(0, false) addFragmentUtils.showFragment(fragments[0], fragments[0].javaClass.name) } override fun setListener() { toolbarBack.setOnClickListener { finish() } } override fun getPresenter(): EmptyP = EmptyP(initViewImpl()) override fun initViewImpl(): EmptyV = EmptyV() override fun initTopBar(): TopBarOption = TopBarOption() }
apache-2.0
3feead352845a1335dcdb30f71370c9d
44.866667
111
0.724611
5.149733
false
false
false
false
jabbink/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/services/BotService.kt
2
2511
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.services import ink.abb.pogo.scraper.Bot import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.startBot import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.credentials.GoogleAutoCredentials import ink.abb.pogo.scraper.util.io.SettingsJSONWriter import okhttp3.OkHttpClient import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.io.File import java.util.concurrent.CountDownLatch import javax.annotation.PreDestroy import kotlin.concurrent.thread @Service class BotService { @Autowired lateinit var http: OkHttpClient private val bots: MutableList<Bot> = mutableListOf() val settingsJSONWriter = SettingsJSONWriter() fun submitBot(name: String): Settings { val settings = settingsJSONWriter.load(name) addBot(startBot(settings, http)) settingsJSONWriter.save(settings) // Is this needed after starting? return settings } @Synchronized fun addBot(bot: Bot) { bots.add(bot) } @Synchronized fun removeBot(bot: Bot) { bots.remove(bot) } fun getJSONConfigBotNames(): List<String> { return settingsJSONWriter.getJSONConfigBotNames() } fun getBotContext(name: String): Context { val bot = bots.find { it.settings.name == name } bot ?: throw IllegalArgumentException("Bot $name doesn't exists !") return bot.ctx } @Synchronized fun getAllBotSettings(): List<Settings> { return bots.map { it.settings.copy(credentials = GoogleAutoCredentials(), restApiPassword = "") } } @Synchronized fun doWithBot(name: String, action: (bot: Bot) -> Unit): Boolean { val bot = bots.find { it.settings.name == name } ?: return false action(bot) return true } @PreDestroy @Synchronized fun stopAllBots() { val latch = CountDownLatch(bots.size) bots.forEach { thread { it.stop() latch.countDown() } } latch.await() } }
gpl-3.0
a5172e5ab389ac0d3a189a888e0624fc
26.293478
105
0.682597
4.307033
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/features/weapons/detail/WeaponBowDetailViewHolder.kt
1
3596
package com.ghstudios.android.features.weapons.detail import android.graphics.Typeface import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.ghstudios.android.AssetLoader import com.ghstudios.android.data.classes.ElementStatus import com.ghstudios.android.data.classes.Weapon import com.ghstudios.android.mhgendatabase.R import com.ghstudios.android.mhgendatabase.databinding.ViewWeaponDetailBowBinding import com.ghstudios.android.util.getColorCompat /** * Inflates bow data into a view and binds the bow data. * Use in the WeaponDetailFragment or any sort of fragment to show full bow data. */ class WeaponBowDetailViewHolder(parent: ViewGroup) : WeaponDetailViewHolder { private val binding: ViewWeaponDetailBowBinding private val chargeCells: List<TextView> init { val inflater = LayoutInflater.from(parent.context) binding = ViewWeaponDetailBowBinding.inflate(inflater, parent, true) chargeCells = with(binding) { listOf( weaponBowCharge1, weaponBowCharge2, weaponBowCharge3, weaponBowCharge4 ) } } override fun bindWeapon(weapon: Weapon) { val context = binding.root.context with(binding) { // Usual weapon parameters attackValue.text = weapon.attack.toString() affinityValue.text = weapon.affinity + "%" defenseValue.text = weapon.defense.toString() slots.setSlots(weapon.numSlots, 0) // bind weapon element (todo: if awaken element ever returns...make an isAwakened flag instead) if (weapon.elementEnum != ElementStatus.NONE) { element1Icon.setImageDrawable(AssetLoader.loadIconFor(weapon.elementEnum)) element1Value.text = weapon.elementAttack.toString() element1Group.visibility = View.VISIBLE } weaponBowArc.text = weapon.recoil // Charge levels for ((view, level) in chargeCells.zip(weapon.charges)) { view.visibility = View.VISIBLE view.text = AssetLoader.localizeChargeLevel(level) if (level.locked) { val lockColor = context.getColorCompat(R.color.text_color_secondary) view.setTextColor(lockColor) } } // Internal function to "enable" a weapon coating view fun setCoating(enabled: Boolean, view: TextView) { if (enabled) { val color = context.getColorCompat(R.color.text_color_focused) view.setTextColor(color) view.setTypeface(null, Typeface.BOLD) } } weapon.coatings?.let { coatings -> setCoating(coatings.power1, power1Text) setCoating(coatings.power2, power2Text) setCoating(coatings.elem1, element1Text) setCoating(coatings.elem2, element2Text) setCoating(coatings.crange, crangeText) setCoating(coatings.poison, poisonText) setCoating(coatings.para, paraText) setCoating(coatings.sleep, sleepText) setCoating(coatings.exhaust, exhaustText) setCoating(coatings.blast, blastText) setCoating(coatings.hasPower, powerLabel) setCoating(coatings.hasElem, elementLabel) } } } }
mit
f1b4a6a8fe360a4367e386d03179f0dc
37.255319
107
0.628476
4.807487
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hcl/codeinsight/AddClosingQuoteQuickFix.kt
1
2281
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hcl.codeinsight import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import org.intellij.plugins.hcl.psi.HCLPsiUtil import org.intellij.plugins.hcl.psi.impl.HCLStringLiteralMixin class AddClosingQuoteQuickFix(element: PsiElement) : LocalQuickFixAndIntentionActionOnPsiElement(element) { companion object { private val LOG = Logger.getInstance(AddClosingQuoteQuickFix::class.java) } override fun getText(): String { return "Add closing quote" } override fun getFamilyName(): String { return text } override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) { if (!FileModificationService.getInstance().prepareFileForWrite(file)) return val element = startElement val rawText = element.text if (element !is HCLStringLiteralMixin) { LOG.error("Quick fix was applied to unexpected element", rawText, element.parent.text) return } if (rawText.isEmpty()) { LOG.error("Quick fix was applied to empty string element", rawText, element.parent.text) return } val content = HCLPsiUtil.stripQuotes(rawText) val quote = element.quoteSymbol CodeStyleManager.getInstance(project).performActionWithFormatterDisabled { element.updateText(quote + content + quote) } } }
apache-2.0
2fe2d1f1f2045f7f4f984b0b76cfa7b2
37.033333
123
0.765454
4.543825
false
false
false
false
oboenikui/UnivCoopFeliCaReader
app/src/main/java/com/oboenikui/campusfelica/ScannerActivity.kt
1
5635
package com.oboenikui.campusfelica import android.Manifest import android.app.PendingIntent import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.nfc.NfcAdapter import android.nfc.Tag import android.nfc.TagLostException import android.nfc.tech.NfcF import android.os.Bundle import android.os.Handler import android.support.v13.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.widget.TextView import android.widget.Toast import java.io.ByteArrayOutputStream import java.util.* import kotlin.concurrent.thread import com.oboenikui.campusfelica.ExecuteNfcF as ex class ScannerActivity : AppCompatActivity() { lateinit var adapter: NfcAdapter private var filters: Array<IntentFilter>? = null private var techLists: Array<Array<String>>? = null private var pendingIntent: PendingIntent? = null private val REQUEST_WRITE_STORAGE = 112 private var index = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_scanner) adapter = NfcAdapter.getDefaultAdapter(this) val tech = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) tech.priority = IntentFilter.SYSTEM_HIGH_PRIORITY filters = arrayOf(tech) pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0) techLists = arrayOf(arrayOf<String>(NfcF::class.java.name)) val hasPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) if (!hasPermission) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_STORAGE) } } public override fun onResume() { adapter.enableForegroundDispatch( this, pendingIntent, filters, techLists) super.onResume() } public override fun onPause() { if (this.isFinishing) { adapter.disableForegroundDispatch(this) } super.onPause() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_WRITE_STORAGE -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show() } } } } override fun onNewIntent(intent: Intent) { val action = intent.action if (action == NfcAdapter.ACTION_TECH_DISCOVERED) { val handler = Handler() val textView = findViewById(R.id.scan_results) as TextView thread { val nfcF = NfcF.get(intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)) nfcF.connect() val idm = try { Arrays.copyOfRange(nfcF.transceive(ex.POLLING_COMMAND), 2, 10) } catch (e: TagLostException) { return@thread } val stream = ByteArrayOutputStream() println(nfcF.maxTransceiveLength) val service = ex.createService(CampusFeliCa.SERVICE_CODE_INFORMATION, CampusFeliCa.SERVICE_CODE_BALANCE) val block = ex.createBlock(3, 1) stream.write(2 + idm.size + service.size + block.size) stream.write(6) stream.write(idm) stream.write(service) stream.write(block) val array = stream.toByteArray() stream.close() val result = ex.bytesToText(nfcF.transceive(array)) handler.post { textView.text = result } /*for (i in index..65535) { val stream = ByteArrayOutputStream() if (i % 100 == 0) { println(i) } val blockList = ex.createBlock(10) stream.write(2 + idm.size + 3 + blockList.size) stream.write(6) stream.write(idm) stream.write(1) stream.write(ByteBuffer.allocate(2).putChar(i.toChar()).array()) stream.write(blockList) try { val response = nfcF.transceive(stream.toByteArray()) if (i == 0) { first = response } else { handler.post { file.appendText("$i:${ex.bytesToText(response ?: byteArrayOf())}\n") } } index = i } catch (e: TagLostException) { e.printStackTrace() System.err.println(i) break } finally { stream.close() } }*/ nfcF.close() } } } }
apache-2.0
e88cfd99346cbef640fc540aac3bf20b
37.862069
199
0.572493
5.022282
false
false
false
false
world-federation-of-advertisers/common-jvm
src/main/kotlin/org/wfanet/measurement/gcloud/spanner/SpannerDatabaseConnector.kt
1
4498
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.gcloud.spanner import com.google.cloud.spanner.DatabaseId import com.google.cloud.spanner.Spanner import java.time.Duration import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import java.util.logging.Logger import kotlinx.coroutines.TimeoutCancellationException /** * Wraps a connection to a Spanner database for convenient access to an [AsyncDatabaseClient], the * [DatabaseId], waiting for the connection to be ready, etc. */ class SpannerDatabaseConnector( projectName: String, instanceName: String, databaseName: String, private val readyTimeout: Duration, transactionTimeout: Duration, maxTransactionThreads: Int, emulatorHost: String?, ) : AutoCloseable { init { require(maxTransactionThreads > 0) } private val spanner: Spanner = buildSpanner(projectName, emulatorHost).also { Runtime.getRuntime() .addShutdownHook( Thread { System.err.println("Ensuring Spanner is closed...") if (!it.isClosed) { it.close() } System.err.println("Spanner closed") } ) } private val transactionExecutor: Lazy<ExecutorService> = lazy { if (emulatorHost == null) { ThreadPoolExecutor(1, maxTransactionThreads, 60L, TimeUnit.SECONDS, LinkedBlockingQueue()) } else { // Spanner emulator only supports a single read-write transaction at a time. Executors.newSingleThreadExecutor() } } val databaseId: DatabaseId = DatabaseId.of(projectName, instanceName, databaseName) val databaseClient: AsyncDatabaseClient by lazy { spanner.getAsyncDatabaseClient(databaseId, transactionExecutor.value, transactionTimeout) } /** * Suspends until [databaseClient] is ready, throwing a * [kotlinx.coroutines.TimeoutCancellationException] if [readyTimeout] is reached. */ suspend fun waitUntilReady() { databaseClient.waitUntilReady(readyTimeout) } override fun close() { spanner.close() if (transactionExecutor.isInitialized()) { transactionExecutor.value.shutdown() } } /** * Executes [block] with this [SpannerDatabaseConnector] once it's ready, ensuring that this is * closed when done. */ suspend fun <R> usingSpanner(block: suspend (spanner: SpannerDatabaseConnector) -> R): R { use { spanner -> try { logger.info { "Waiting for Spanner connection to $databaseId to be ready..." } spanner.waitUntilReady() logger.info { "Spanner connection to $databaseId ready" } } catch (e: TimeoutCancellationException) { // Closing Spanner can take a long time (e.g. 1 minute) and delay the // exception being surfaced, so we log here to give immediate feedback. logger.severe { "Timed out waiting for Spanner to be ready" } throw e } return block(spanner) } } companion object { private val logger = Logger.getLogger(this::class.java.name) } } /** Builds a [SpannerDatabaseConnector] from these flags. */ private fun SpannerFlags.toSpannerDatabaseConnector(): SpannerDatabaseConnector { return SpannerDatabaseConnector( projectName = projectName, instanceName = instanceName, databaseName = databaseName, readyTimeout = readyTimeout, transactionTimeout = transactionTimeout, maxTransactionThreads = maxTransactionThreads, emulatorHost = emulatorHost, ) } /** * Executes [block] with a [SpannerDatabaseConnector] resource once it's ready, ensuring that the * resource is closed. */ suspend fun <R> SpannerFlags.usingSpanner( block: suspend (spanner: SpannerDatabaseConnector) -> R ): R { return toSpannerDatabaseConnector().usingSpanner(block) }
apache-2.0
b5b16cd40a231d21495362a47cad72db
32.819549
98
0.719209
4.705021
false
false
false
false
ThanosFisherman/MayI
mayi/src/main/java/com/thanosfisherman/mayi/MayIFragment.kt
1
5172
@file:Suppress("DEPRECATION") package com.thanosfisherman.mayi import android.app.Fragment import android.content.pm.PackageManager import android.os.Build import androidx.annotation.RequiresApi class MayIFragment : Fragment(), PermissionToken { companion object { const val TAG = "MayIFragment" private const val PERMISSION_REQUEST_CODE = 1001 } private var permissionResultSingleListener: ((PermissionBean) -> Unit)? = null private var rationaleSingleListener: ((PermissionBean, PermissionToken) -> Unit)? = null private var permissionResultMultiListener: ((List<PermissionBean>) -> Unit)? = null private var rationaleMultiListener: ((List<PermissionBean>, PermissionToken) -> Unit)? = null private var isShowingNativeDialog: Boolean = false private lateinit var rationalePermissions: List<String> private lateinit var permissionMatcher: PermissionMatcher @RequiresApi(api = Build.VERSION_CODES.M) override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == PERMISSION_REQUEST_CODE) { isShowingNativeDialog = false if (grantResults.isEmpty()) return val beansResultList = mutableListOf<PermissionBean>() for (i in permissions.indices) { if (grantResults[i] == PackageManager.PERMISSION_DENIED) { if (shouldShowRequestPermissionRationale(permissions[i])) beansResultList.add(PermissionBean(permissions[i], isGranted = false, isPermanentlyDenied = false)) else beansResultList.add(PermissionBean(permissions[i], isGranted = false, isPermanentlyDenied = true)) } else { beansResultList.add(PermissionBean(permissions[i], isGranted = true, isPermanentlyDenied = false)) } } permissionResultSingleListener?.invoke(beansResultList[0]) permissionResultMultiListener?.let { val grantedBeans = permissionMatcher.grantedPermissions.map { PermissionBean(it, true) } it(beansResultList.plus(grantedBeans)) } } } @RequiresApi(api = Build.VERSION_CODES.M) internal fun checkPermissions(permissionMatcher: PermissionMatcher) { this.permissionMatcher = permissionMatcher rationalePermissions = permissionMatcher.deniedPermissions.filter(this::shouldShowRequestPermissionRationale) val rationaleBeanList = rationalePermissions.map { PermissionBean(it) } if (rationaleBeanList.isEmpty()) { if (!isShowingNativeDialog) requestPermissions(permissionMatcher.deniedPermissions.toTypedArray(), PERMISSION_REQUEST_CODE) isShowingNativeDialog = true } else { rationaleSingleListener?.invoke(rationaleBeanList[0], PermissionRationaleToken(this)) rationaleMultiListener?.invoke(rationaleBeanList, PermissionRationaleToken(this)) } } @RequiresApi(api = Build.VERSION_CODES.M) override fun continuePermissionRequest() { if (!isShowingNativeDialog) requestPermissions(permissionMatcher.deniedPermissions.toTypedArray(), PERMISSION_REQUEST_CODE) isShowingNativeDialog = true } override fun skipPermissionRequest() { isShowingNativeDialog = false permissionResultSingleListener?.invoke(PermissionBean(rationalePermissions[0])) val totalBeanGranted = permissionMatcher.grantedPermissions.map { PermissionBean(it, true) } val totalBeanDenied = permissionMatcher.deniedPermissions.map { PermissionBean(it) } val totalBeanPermanentlyDenied = permissionMatcher.permissions .filterNot { s -> permissionMatcher.deniedPermissions.contains(s) } .filterNot { s -> permissionMatcher.grantedPermissions.contains(s) } .map { PermissionBean(it, isGranted = false, isPermanentlyDenied = true) } permissionResultMultiListener?.invoke(totalBeanGranted.asSequence() .plus(totalBeanDenied) .plus(totalBeanPermanentlyDenied) .toList()) } internal fun setListeners(listenerResult: ((PermissionBean) -> Unit)?, listenerResultMulti: ((List<PermissionBean>) -> Unit)?, rationaleSingle: ((PermissionBean, PermissionToken) -> Unit)?, rationaleMulti: ((List<PermissionBean>, PermissionToken) -> Unit)?) { permissionResultSingleListener = listenerResult permissionResultMultiListener = listenerResultMulti rationaleSingleListener = rationaleSingle rationaleMultiListener = rationaleMulti } /* private fun isPermissionsDialogShowing(): Boolean { val am = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val cn = am.getRunningTasks(1).get(0).topActivity return "com.android.packageinstaller.permission.ui.GrantPermissionsActivity" == cn.className }*/ }
apache-2.0
a45b806a51eea0bed62823f16de3bbf3
46.027273
123
0.680588
5.804714
false
false
false
false
vase4kin/TeamCityApp
app/src/main/java/com/github/vase4kin/teamcityapp/runningbuilds/view/RunningBuildsListViewImpl.kt
1
4500
/* * Copyright 2019 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.runningbuilds.view import android.app.Activity import android.view.View import androidx.annotation.StringRes import com.github.vase4kin.teamcityapp.R import com.github.vase4kin.teamcityapp.base.list.view.SimpleSectionedRecyclerViewAdapter import com.github.vase4kin.teamcityapp.buildlist.data.BuildListDataModel import com.github.vase4kin.teamcityapp.buildlist.data.OnBuildListPresenterListener import com.github.vase4kin.teamcityapp.buildlist.view.BuildListActivity import com.github.vase4kin.teamcityapp.buildlist.view.BuildListAdapter import com.github.vase4kin.teamcityapp.buildlist.view.BuildListViewImpl import com.github.vase4kin.teamcityapp.filter_bottom_sheet_dialog.filter.Filter import com.github.vase4kin.teamcityapp.filter_bottom_sheet_dialog.filter.FilterProvider import java.util.ArrayList /** * impl of [RunningBuildListView] */ open class RunningBuildsListViewImpl( view: View, activity: Activity, @StringRes emptyMessage: Int, adapter: SimpleSectionedRecyclerViewAdapter<BuildListAdapter>, protected val filterProvider: FilterProvider ) : BuildListViewImpl(view, activity, emptyMessage, adapter), RunningBuildListView { /** * @return default tool bar title */ protected open val title: String get() = activity.getString(R.string.running_builds_drawer_item) /** * {@inheritDoc} */ override fun showData(dataModel: BuildListDataModel) { val baseAdapter = adapter.baseAdapter baseAdapter.dataModel = dataModel baseAdapter.setOnBuildListPresenterListener(listener ?: OnBuildListPresenterListener.EMPTY) val sections = ArrayList<SimpleSectionedRecyclerViewAdapter.Section>() if (dataModel.itemCount != 0) { for (i in 0 until dataModel.itemCount) { val buildTypeTitle = if (dataModel.hasBuildTypeInfo(i)) dataModel.getBuildTypeFullName(i) else dataModel.getBuildTypeId(i) if (sections.size != 0) { val prevSection = sections[sections.size - 1] if (prevSection.title != buildTypeTitle) { sections.add(SimpleSectionedRecyclerViewAdapter.Section(i, buildTypeTitle)) } } else { sections.add(SimpleSectionedRecyclerViewAdapter.Section(i, buildTypeTitle)) } } adapter.setListener { position -> val buildTypeName = dataModel.getBuildTypeName(position) val buildTypeId = dataModel.getBuildTypeId(position) BuildListActivity.start(buildTypeName, buildTypeId, null, activity) } } val userStates = arrayOfNulls<SimpleSectionedRecyclerViewAdapter.Section>(sections.size) adapter.setSections(sections.toArray(userStates)) recyclerView.adapter = adapter recyclerView.adapter?.notifyDataSetChanged() } /** * {@inheritDoc} */ override fun showRunBuildFloatActionButton() { // Do not show running build float action button here } /** * {@inheritDoc} */ override fun hideRunBuildFloatActionButton() { // Do not show running build float action button here } /** * {@inheritDoc} */ override val emptyMessage: Int get() = if (filterProvider.runningBuildsFilter === Filter.RUNNING_FAVORITES) { R.string.empty_list_message_favorite_running_builds } else { R.string.empty_list_message_running_builds } /** * {@inheritDoc} */ override fun emptyTitleId(): Int { return R.id.running_empty_title_view } /** * {@inheritDoc} */ override fun recyclerViewId(): Int { return R.id.running_builds_recycler_view } }
apache-2.0
a5b172beb66b4f6754e6ae2cb029e61b
34.433071
99
0.680667
4.736842
false
false
false
false
AIDEA775/UNCmorfi
app/src/main/java/com/uncmorfi/map/MapFragment.kt
1
2436
package com.uncmorfi.map import android.os.Bundle import androidx.fragment.app.Fragment import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.uncmorfi.R import android.view.ViewGroup import android.view.LayoutInflater import android.view.View import com.google.android.gms.maps.MapsInitializer import kotlinx.android.synthetic.main.fragment_map.* /** * Muestra las ubicaciones de los comedores en un GoogleMap. */ class MapFragment : Fragment() { private lateinit var mMap: GoogleMap override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_map, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mapView.onCreate(savedInstanceState) mapView.onResume() try { MapsInitializer.initialize(activity!!.applicationContext) } catch (e: Exception) { e.printStackTrace() } mapView.getMapAsync { onMapReady(it) } } override fun onResume() { super.onResume() requireActivity().setTitle(R.string.navigation_map) mapView.onResume() } override fun onPause() { super.onPause() mapView.onPause() } override fun onLowMemory() { super.onLowMemory() mapView.onLowMemory() } private fun onMapReady(googleMap: GoogleMap) { mMap = googleMap mMap.addMarker(MarkerOptions() .position(CENTRAL) .title(getString(R.string.map_central))) mMap.addMarker(MarkerOptions() .position(BELGRANO) .title(getString(R.string.map_belgrano))) val cameraPosition = CameraPosition.builder() .target(CENTER) .zoom(14f) .build() mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)) } companion object { private val CENTRAL = LatLng(-31.439734, -64.189293) private val BELGRANO = LatLng(-31.416686, -64.189000) private val CENTER = LatLng(-31.428570, -64.184912) } }
gpl-3.0
17a29f95245e785b303f1bef44d4cd7b
28.719512
116
0.66954
4.373429
false
false
false
false
denisrmp/hacker-rank
cracking-the-code-interview/arraysandstrings/OneAway.kt
1
1208
package arraysandstrings import java.lang.Math.abs /* pg. 91 Question 1.5 One Away */ fun oneAway(a: CharArray, b: CharArray): Boolean { val sizeDiff = a.size - b.size if (abs(sizeDiff) > 1) return false // by storing the bigger string in x we can treat the "remove" case as an insertion on x val (x, y) = if (sizeDiff >= 0) Pair(a, b) else Pair(b, a) var xIdx = 0 var yIdx = 0 var diff = 0 while (diff <= 1 && yIdx < y.size) { if (x[xIdx] != y[yIdx]) { // the case when the bigger string has one insertion if (xIdx + 1 < x.size && x[xIdx + 1] == y[yIdx]) xIdx++ diff++ } xIdx++ yIdx++ } return diff <= 1 } fun main() { println("Is oneAway? true == ${ oneAway("pale".toCharArray(), "ale".toCharArray()) }") println("Is oneAway? true == ${ oneAway("pales".toCharArray(), "pale".toCharArray()) }") println("Is oneAway? true == ${ oneAway("pales".toCharArray(), "bale".toCharArray()) }") println("Is oneAway? false == ${ oneAway("pales".toCharArray(), "bake".toCharArray()) }") println("Is oneAway? true == ${ oneAway("apple".toCharArray(), "aple".toCharArray()) }") }
mit
6bcb203413c007e76f1f804a7c1edbd4
26.454545
93
0.569536
3.461318
false
false
false
false
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/model/codeelements/DefaultValue.kt
1
861
package wu.seal.jsontokotlin.model.codeelements import wu.seal.jsontokotlin.utils.* /** * Default Value relative * Created by Seal.wu on 2017/9/25. */ fun getDefaultValue(propertyType: String): String { val rawType = getRawType(propertyType) return when { rawType == TYPE_INT -> 0.toString() rawType == TYPE_LONG -> 0L.toString() rawType == TYPE_STRING -> "\"\"" rawType == TYPE_DOUBLE -> 0.0.toString() rawType == TYPE_BOOLEAN -> false.toString() rawType.contains("List<") -> "listOf()" rawType.contains("Map<") -> "mapOf()" rawType == TYPE_ANY -> "Any()" rawType.contains("Array<") -> "emptyArray()" else -> "$rawType()" } } fun getDefaultValueAllowNull(propertyType: String) = if (propertyType.endsWith("?")) "null" else getDefaultValue(propertyType)
gpl-3.0
dc7eaa03b903a797cf9b208689b0f708
26.774194
77
0.615563
4.2
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/cargo/toolchain/RustToolchain.kt
1
5951
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.toolchain import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.text.SemVer import org.rust.utils.GeneralCommandLine import org.rust.utils.seconds import java.io.File import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths private val LOG = Logger.getInstance(RustToolchain::class.java) data class RustToolchain(val location: String) { fun looksLikeValidToolchain(): Boolean = hasExecutable(CARGO) && hasExecutable(RUSTC) fun queryVersions(): VersionInfo { check(!ApplicationManager.getApplication().isDispatchThread) return VersionInfo( rustc = scrapeRustcVersion(pathToExecutable(RUSTC)) ) } fun cargo(cargoProjectDirectory: Path): Cargo = Cargo(pathToExecutable(CARGO), pathToExecutable(RUSTC), cargoProjectDirectory, rustup(cargoProjectDirectory)) fun rustup(cargoProjectDirectory: Path): Rustup? = if (isRustupAvailable) Rustup(pathToExecutable(RUSTUP), pathToExecutable(RUSTC), cargoProjectDirectory) else null val isRustupAvailable: Boolean get() = hasExecutable(RUSTUP) fun nonProjectCargo(): Cargo = Cargo(pathToExecutable(CARGO), pathToExecutable(RUSTC), null, null) val presentableLocation: String = pathToExecutable(CARGO).toString() private fun pathToExecutable(toolName: String): Path { val exeName = if (SystemInfo.isWindows) "$toolName.exe" else toolName return Paths.get(location, exeName).toAbsolutePath() } private fun hasExecutable(exec: String): Boolean = Files.isExecutable(pathToExecutable(exec)) data class VersionInfo( val rustc: RustcVersion ) companion object { private val RUSTC = "rustc" private val CARGO = "cargo" private val RUSTUP = "rustup" val CARGO_TOML = "Cargo.toml" val CARGO_LOCK = "Cargo.lock" fun suggest(): RustToolchain? = Suggestions.all().mapNotNull { val candidate = RustToolchain(it.absolutePath) if (candidate.looksLikeValidToolchain()) candidate else null }.firstOrNull() } } data class RustcVersion( val semver: SemVer?, val nightlyCommitHash: String? ) { companion object { val UNKNOWN = RustcVersion(null, null) } } private fun scrapeRustcVersion(rustc: Path): RustcVersion { val lines = GeneralCommandLine(rustc) .withParameters("--version", "--verbose") .runExecutable() ?: return RustcVersion.UNKNOWN // We want to parse following // // ``` // rustc 1.8.0-beta.1 (facbfdd71 2016-03-02) // binary: rustc // commit-hash: facbfdd71cb6ed0aeaeb06b6b8428f333de4072b // commit-date: 2016-03-02 // host: x86_64-unknown-linux-gnu // release: 1.8.0-beta.1 // ``` val commitHashRe = "commit-hash: (.*)".toRegex() val releaseRe = """release: (\d+\.\d+\.\d+)(.*)""".toRegex() val find = { re: Regex -> lines.mapNotNull { re.matchEntire(it) }.firstOrNull() } val commitHash = find(commitHashRe)?.let { it.groups[1]!!.value } val releaseMatch = find(releaseRe) ?: return RustcVersion.UNKNOWN val versionText = releaseMatch.groups[1]?.value ?: return RustcVersion.UNKNOWN val semVer = SemVer.parseFromText(versionText) ?: return RustcVersion.UNKNOWN val isStable = releaseMatch.groups[2]?.value.isNullOrEmpty() return RustcVersion(semVer, if (isStable) null else commitHash) } private object Suggestions { fun all() = sequenceOf( fromRustup(), fromPath(), forMac(), forUnix(), forWindows() ).flatten() private fun fromRustup(): Sequence<File> { val file = File(FileUtil.expandUserHome("~/.cargo/bin")) return if (file.isDirectory) { sequenceOf(file) } else { emptySequence() } } private fun fromPath(): Sequence<File> = System.getenv("PATH").orEmpty() .split(File.pathSeparator) .asSequence() .filter { !it.isEmpty() } .map(::File) .filter { it.isDirectory } private fun forUnix(): Sequence<File> { if (!SystemInfo.isUnix) return emptySequence() return sequenceOf(File("/usr/local/bin")) } private fun forMac(): Sequence<File> { if (!SystemInfo.isMac) return emptySequence() return sequenceOf(File("/usr/local/Cellar/rust/bin")) } private fun forWindows(): Sequence<File> { if (!SystemInfo.isWindows) return emptySequence() val fromHome = File(System.getProperty("user.home") ?: "", ".cargo/bin") val programFiles = File(System.getenv("ProgramFiles") ?: "") val fromProgramFiles = if (!programFiles.exists() || !programFiles.isDirectory) emptySequence() else programFiles.listFiles { file -> file.isDirectory }.asSequence() .filter { it.nameWithoutExtension.toLowerCase().startsWith("rust") } .map { File(it, "bin") } return sequenceOf(fromHome) + fromProgramFiles } } private fun GeneralCommandLine.runExecutable(): List<String>? { val procOut = try { CapturingProcessHandler(this).runProcess(1.seconds) } catch (e: ExecutionException) { LOG.warn("Failed to run executable!", e) return null } if (procOut.exitCode != 0 || procOut.isCancelled || procOut.isTimeout) return null return procOut.stdoutLines }
mit
3a3d7048192a89e395bee3592715d210
31.519126
117
0.662914
4.398374
false
false
false
false
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/feedback/Actions.kt
1
1552
package wu.seal.jsontokotlin.feedback import java.text.SimpleDateFormat import java.util.* /** * * Created by Seal.Wu on 2017/9/25. */ const val ACTION_START = "action_start" const val ACTION_SUCCESS_COMPLETE = "action_success_complete" const val ACTION_FORMAT_JSON = "action_format_json" const val ACTION_CLICK_PROJECT_URL = "action_click_project_url" data class StartAction( val uuid: String = UUID, val pluginVersion: String = PLUGIN_VERSION, val actionType: String = ACTION_START, val time: String = Date().time.toString(), val daytime: String = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date()) ) data class SuccessCompleteAction( val uuid: String = UUID, val pluginVersion: String = PLUGIN_VERSION, val actionType: String = ACTION_SUCCESS_COMPLETE, val time: String = Date().time.toString(), val daytime: String = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date()) ) data class FormatJSONAction( val uuid: String = UUID, val pluginVersion: String = PLUGIN_VERSION, val actionType: String = ACTION_FORMAT_JSON, val time: String = Date().time.toString(), val daytime: String = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date()) ) data class ClickProjectURLAction( val uuid: String = UUID, val pluginVersion: String = PLUGIN_VERSION, val actionType: String = ACTION_CLICK_PROJECT_URL, val time: String = Date().time.toString(), val daytime: String = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date()) )
gpl-3.0
9070a4a2d77a37e017ba707b773c130b
32.76087
89
0.701675
3.813268
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/ui/preferences/PreferencesFragment.kt
1
2418
package com.booboot.vndbandroid.ui.preferences import android.content.Context import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatDelegate import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreference import com.booboot.vndbandroid.R import com.booboot.vndbandroid.extensions.setupStatusBar import com.booboot.vndbandroid.extensions.setupToolbar import com.booboot.vndbandroid.extensions.toBooleanOrFalse import com.booboot.vndbandroid.model.vndbandroid.NO import com.booboot.vndbandroid.model.vndbandroid.Preferences import com.booboot.vndbandroid.model.vndbandroid.YES class PreferencesFragment : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupStatusBar() setupToolbar() } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { preferenceManager.sharedPreferencesName = Preferences.kotprefName preferenceManager.sharedPreferencesMode = Context.MODE_PRIVATE addPreferencesFromResource(R.xml.app_preferences) /* Replicating indirect preferences from Preferences to the UI */ val prefGdprCrashlytics = preferenceScreen.findPreference(getString(R.string.pref_key_gdpr_crashlytics)) as? SwitchPreference prefGdprCrashlytics?.isChecked = Preferences.gdprCrashlytics == YES for (i in 0 until preferenceScreen.preferenceCount) { preferenceScreen.getPreference(i).onPreferenceChangeListener = this } } override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean { when (preference.key) { getString(R.string.pref_key_night_mode) -> { val value = newValue.toString().toInt() if (Preferences.nightMode != value) { AppCompatDelegate.setDefaultNightMode(value) Preferences.nightMode = value activity?.recreate() } } getString(R.string.pref_key_gdpr_crashlytics) -> { val value = newValue.toString().toBooleanOrFalse() Preferences.gdprCrashlytics = if (value) YES else NO } } return true } }
gpl-3.0
7d43c6952de8c89128b827c2ca279356
42.196429
133
0.718776
5.373333
false
false
false
false
jtransc/jtransc
benchmark_kotlin_mpp/wip/jzlib/InfCodes.kt
1
20821
/* -*-mode:java; c-basic-offset:2; -*- */ /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly([email protected]) and Mark Adler([email protected]) * and contributors of zlib. */ package com.jtransc.compression.jzlib import com.jtransc.annotation.JTranscInvisible @JTranscInvisible internal class InfCodes(private val z: ZStream, s: InfBlocks) { var mode // current inflate_codes mode = 0 // mode dependent information var len = 0 var tree // pointer into tree : IntArray? var tree_index = 0 var need // bits needed = 0 var lit = 0 // if EXT or COPY, where and how much var get // bits to get for extra = 0 var dist // distance back to copy from = 0 var lbits // ltree bits decoded per branch : Byte = 0 var dbits // dtree bits decoder per branch : Byte = 0 var ltree // literal/length/eob tree : IntArray var ltree_index // literal/length/eob tree = 0 var dtree // distance tree : IntArray var dtree_index // distance tree = 0 private val s: InfBlocks fun init( bl: Int, bd: Int, tl: IntArray, tl_index: Int, td: IntArray, td_index: Int ) { mode = START lbits = bl.toByte() dbits = bd.toByte() ltree = tl ltree_index = tl_index dtree = td dtree_index = td_index tree = null } fun proc(r: Int): Int { var r = r var j: Int // temporary storage var t: IntArray // temporary pointer val tindex: Int // temporary pointer val e: Int // extra bits or operation var b = 0 // bit buffer var k = 0 // bits in bit buffer var p = 0 // input data pointer var n: Int // bytes available there var q: Int // output window write pointer var m: Int // bytes to end of window or read pointer var f: Int // pointer to copy strings from // copy input/output information to locals (UPDATE macro restores) p = z.next_in_index n = z.avail_in b = s.bitb k = s.bitk q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q // process input and output based on current state while (true) { when (mode) { START -> { if (m >= 258 && n >= 10) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q r = inflate_fast( lbits.toInt(), dbits.toInt(), ltree, ltree_index, dtree, dtree_index, s, z ) p = z.next_in_index n = z.avail_in b = s.bitb k = s.bitk q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (r != Z_OK) { mode = if (r == Z_STREAM_END) WASH else BADCODE break } } need = lbits.toInt() tree = ltree tree_index = ltree_index mode = LEN j = need while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } tindex = (tree_index + (b and inflate_mask[j])) * 3 b = b ushr tree!![tindex + 1] k -= tree!![tindex + 1] e = tree!![tindex] if (e == 0) { // literal lit = tree!![tindex + 2] mode = LIT break } if (e and 16 != 0) { // length get = e and 15 len = tree!![tindex + 2] mode = LENEXT break } if (e and 64 == 0) { // next table need = e tree_index = tindex / 3 + tree!![tindex + 2] break } if (e and 32 != 0) { // end of block mode = WASH break } mode = BADCODE // invalid code z.msg = "invalid literal/length code" r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } LEN -> { j = need while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } tindex = (tree_index + (b and inflate_mask[j])) * 3 b = b ushr tree!![tindex + 1] k -= tree!![tindex + 1] e = tree!![tindex] if (e == 0) { lit = tree!![tindex + 2] mode = LIT break } if (e and 16 != 0) { get = e and 15 len = tree!![tindex + 2] mode = LENEXT break } if (e and 64 == 0) { need = e tree_index = tindex / 3 + tree!![tindex + 2] break } if (e and 32 != 0) { mode = WASH break } mode = BADCODE z.msg = "invalid literal/length code" r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } LENEXT -> { j = get while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } len += b and inflate_mask[j] b = b shr j k -= j need = dbits.toInt() tree = dtree tree_index = dtree_index mode = DIST j = need while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } tindex = (tree_index + (b and inflate_mask[j])) * 3 b = b shr tree!![tindex + 1] k -= tree!![tindex + 1] e = tree!![tindex] if (e and 16 != 0) { // distance get = e and 15 dist = tree!![tindex + 2] mode = DISTEXT break } if (e and 64 == 0) { // next table need = e tree_index = tindex / 3 + tree!![tindex + 2] break } mode = BADCODE // invalid code z.msg = "invalid distance code" r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } DIST -> { j = need while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } tindex = (tree_index + (b and inflate_mask[j])) * 3 b = b shr tree!![tindex + 1] k -= tree!![tindex + 1] e = tree!![tindex] if (e and 16 != 0) { get = e and 15 dist = tree!![tindex + 2] mode = DISTEXT break } if (e and 64 == 0) { need = e tree_index = tindex / 3 + tree!![tindex + 2] break } mode = BADCODE z.msg = "invalid distance code" r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } DISTEXT -> { j = get while (k < j) { if (n != 0) r = Z_OK else { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } dist += b and inflate_mask[j] b = b shr j k -= j mode = COPY f = q - dist while (f < 0) { // modulo window size-"while" instead f += s.end // of "if" handles invalid distances } while (len != 0) { if (m == 0) { if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.write = q r = s.inflate_flush(r) q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } } } s.window.get(q++) = s.window.get(f++) m-- if (f == s.end) f = 0 len-- } mode = START } COPY -> { f = q - dist while (f < 0) { f += s.end } while (len != 0) { if (m == 0) { if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.write = q r = s.inflate_flush(r) q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } } } s.window.get(q++) = s.window.get(f++) m-- if (f == s.end) f = 0 len-- } mode = START } LIT -> { if (m == 0) { if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.write = q r = s.inflate_flush(r) q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (q == s.end && s.read !== 0) { q = 0 m = if (q < s.read) s.read - q - 1 else s.end - q } if (m == 0) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } } } r = Z_OK s.window.get(q++) = lit.toByte() m-- mode = START } WASH -> { if (k > 7) { // return unused byte, if any k -= 8 n++ p-- // can always return one } s.write = q r = s.inflate_flush(r) q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q if (s.read !== s.write) { s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } mode = END r = Z_STREAM_END s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } END -> { r = Z_STREAM_END s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } BADCODE -> { r = Z_DATA_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } else -> { r = Z_STREAM_ERROR s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return s.inflate_flush(r) } } } } fun free(z: ZStream?) { // ZFREE(z, c); } // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. fun inflate_fast( bl: Int, bd: Int, tl: IntArray, tl_index: Int, td: IntArray, td_index: Int, s: InfBlocks, z: ZStream ): Int { var t: Int // temporary pointer var tp: IntArray // temporary pointer var tp_index: Int // temporary pointer var e: Int // extra bits or operation var b: Int // bit buffer var k: Int // bits in bit buffer var p: Int // input data pointer var n: Int // bytes available there var q: Int // output window write pointer var m: Int // bytes to end of window or read pointer val ml: Int // mask for literal/length tree val md: Int // mask for distance tree var c: Int // bytes to copy var d: Int // distance back to copy from var r: Int // copy source pointer var tp_index_t_3: Int // (tp_index+t)*3 // load input, output, bit values p = z.next_in_index n = z.avail_in b = s.bitb k = s.bitk q = s.write m = if (q < s.read) s.read - q - 1 else s.end - q // initialize masks ml = inflate_mask[bl] md = inflate_mask[bd] // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while (k < 20) { // max bits for literal/length code n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } t = b and ml tp = tl tp_index = tl_index tp_index_t_3 = (tp_index + t) * 3 if (tp[tp_index_t_3].also { e = it } == 0) { b = b shr tp[tp_index_t_3 + 1] k -= tp[tp_index_t_3 + 1] s.window.get(q++) = tp[tp_index_t_3 + 2].toByte() m-- continue } do { b = b shr tp[tp_index_t_3 + 1] k -= tp[tp_index_t_3 + 1] if (e and 16 != 0) { e = e and 15 c = tp[tp_index_t_3 + 2] + (b and inflate_mask[e]) b = b shr e k -= e // decode distance base of block to copy while (k < 15) { // max bits for distance code n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } t = b and md tp = td tp_index = td_index tp_index_t_3 = (tp_index + t) * 3 e = tp[tp_index_t_3] do { b = b shr tp[tp_index_t_3 + 1] k -= tp[tp_index_t_3 + 1] if (e and 16 != 0) { // get extra bits to add to distance base e = e and 15 while (k < e) { // get extra bits (up to 13) n-- b = b or (z.next_in.get(p++) and 0xff shl k) k += 8 } d = tp[tp_index_t_3 + 2] + (b and inflate_mask[e]) b = b shr e k -= e // do the copy m -= c if (q >= d) { // offset before dest // just copy r = q - d if (q - r > 0 && 2 > q - r) { s.window.get(q++) = s.window.get(r++) // minimum count is three, s.window.get(q++) = s.window.get(r++) // so unroll loop a little c -= 2 } else { java.lang.System.arraycopy(s.window, r, s.window, q, 2) q += 2 r += 2 c -= 2 } } else { // else offset after destination r = q - d do { r += s.end // force pointer in window } while (r < 0) // covers invalid distances e = s.end - r if (c > e) { // if source crosses, c -= e // wrapped copy if (q - r > 0 && e > q - r) { do { s.window.get(q++) = s.window.get(r++) } while (--e != 0) } else { java.lang.System.arraycopy(s.window, r, s.window, q, e) q += e r += e e = 0 } r = 0 // copy rest from start of window } } // copy all or what's left if (q - r > 0 && c > q - r) { do { s.window.get(q++) = s.window.get(r++) } while (--c != 0) } else { java.lang.System.arraycopy(s.window, r, s.window, q, c) q += c r += c c = 0 } break } else if (e and 64 == 0) { t += tp[tp_index_t_3 + 2] t += b and inflate_mask[e] tp_index_t_3 = (tp_index + t) * 3 e = tp[tp_index_t_3] } else { z.msg = "invalid distance code" c = z.avail_in - n c = if (k shr 3 < c) k shr 3 else c n += c p -= c k -= c shl 3 s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return Z_DATA_ERROR } } while (true) break } if (e and 64 == 0) { t += tp[tp_index_t_3 + 2] t += b and inflate_mask[e] tp_index_t_3 = (tp_index + t) * 3 if (tp[tp_index_t_3].also { e = it } == 0) { b = b shr tp[tp_index_t_3 + 1] k -= tp[tp_index_t_3 + 1] s.window.get(q++) = tp[tp_index_t_3 + 2].toByte() m-- break } } else if (e and 32 != 0) { c = z.avail_in - n c = if (k shr 3 < c) k shr 3 else c n += c p -= c k -= c shl 3 s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return Z_STREAM_END } else { z.msg = "invalid literal/length code" c = z.avail_in - n c = if (k shr 3 < c) k shr 3 else c n += c p -= c k -= c shl 3 s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return Z_DATA_ERROR } } while (true) } while (m >= 258 && n >= 10) // not enough input or output--restore pointers and return c = z.avail_in - n c = if (k shr 3 < c) k shr 3 else c n += c p -= c k -= c shl 3 s.bitb = b s.bitk = k z.avail_in = n z.total_in += p - z.next_in_index z.next_in_index = p s.write = q return Z_OK } companion object { private val inflate_mask = intArrayOf( 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff ) private const val Z_OK = 0 private const val Z_STREAM_END = 1 private const val Z_NEED_DICT = 2 private const val Z_ERRNO = -1 private const val Z_STREAM_ERROR = -2 private const val Z_DATA_ERROR = -3 private const val Z_MEM_ERROR = -4 private const val Z_BUF_ERROR = -5 private const val Z_VERSION_ERROR = -6 // waiting for "i:"=input, // "o:"=output, // "x:"=nothing private const val START = 0 // x: set up for LEN private const val LEN = 1 // i: get length/literal/eob next private const val LENEXT = 2 // i: getting length extra (have base) private const val DIST = 3 // i: get distance next private const val DISTEXT = 4 // i: getting distance extra private const val COPY = 5 // o: copying bytes in window, waiting for space private const val LIT = 6 // o: got literal, waiting for output space private const val WASH = 7 // o: got eob, possibly still output waiting private const val END = 8 // x: got eob and all data flushed private const val BADCODE = 9 // x: got error } init { this.s = s } }
apache-2.0
cd2e0f4ee50655580c9003d2944e4a0d
25.191195
77
0.502858
2.812129
false
false
false
false
b95505017/android-architecture-components
PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/ui/RedditPostViewHolder.kt
1
2991
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.paging.pagingwithnetwork.reddit.ui import android.content.Intent import android.net.Uri import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.android.example.paging.pagingwithnetwork.R import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost import com.bumptech.glide.RequestManager import com.bumptech.glide.request.RequestOptions /** * A RecyclerView ViewHolder that displays a reddit post. */ class RedditPostViewHolder(view: View, private val glide: RequestManager) : RecyclerView.ViewHolder(view) { private val title: TextView = view.findViewById(R.id.title) private val subtitle: TextView = view.findViewById(R.id.subtitle) private val score: TextView = view.findViewById(R.id.score) private val thumbnail : ImageView = view.findViewById(R.id.thumbnail) private var post : RedditPost? = null init { view.setOnClickListener { post?.url?.let { url -> val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) view.context.startActivity(intent) } } } fun bind(post: RedditPost?) { this.post = post title.text = post?.title ?: "loading" subtitle.text = itemView.context.resources.getString(R.string.post_subtitle, post?.author ?: "unknown") score.text = "${post?.score ?: 0}" if (post?.thumbnail?.startsWith("http") == true) { thumbnail.visibility = View.VISIBLE glide.load(post.thumbnail).apply(RequestOptions.centerCropTransform() .placeholder(R.drawable.ic_insert_photo_black_48dp)) .into(thumbnail) } else { thumbnail.visibility = View.GONE glide.clear(thumbnail) } } companion object { fun create(parent: ViewGroup, glide: RequestManager): RedditPostViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.reddit_post_item, parent, false) return RedditPostViewHolder(view, glide) } } fun updateScore(item: RedditPost?) { post = item score.text = "${item?.score ?: 0}" } }
apache-2.0
211a16ad3506685286fc69871cfad4ea
35.938272
84
0.6777
4.366423
false
false
false
false
joan-domingo/Podcasts-RAC1-Android
app/src/rac1/java/cat/xojan/random1/data/RemoteProgramRepository.kt
1
1280
package cat.xojan.random1.data import cat.xojan.random1.domain.model.Program import cat.xojan.random1.domain.model.ProgramData import cat.xojan.random1.domain.model.Section import cat.xojan.random1.domain.repository.ProgramRepository import io.reactivex.Observable import io.reactivex.Single class RemoteProgramRepository(private val service: ApiService): ProgramRepository { private var programData: Single<ProgramData>? = null override fun getPrograms(refresh: Boolean): Single<List<Program>> { if (programData == null || refresh) { programData = service.getProgramData().cache() } return programData!!.map { pd: ProgramData -> pd.toPrograms() } } override fun getProgram(programId: String): Single<Program> = getPrograms(false).flatMap { programs -> Observable.fromIterable(programs) .filter { p: Program -> p.id == programId } .firstOrError() } override fun hasSections(programId: String): Single<Boolean> = getProgram(programId).map { p -> p.sections!!.size > 1 } override fun getSections(programId: String): Single<List<Section>> = getProgram(programId) .map { p -> p.sections } }
mit
c57db1a6678fa248d5f8bb7b3c2202de
34.583333
83
0.660156
4.491228
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/util/BitmapFactoryUtils.kt
2
3393
package de.westnordost.streetcomplete.util import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import androidx.exifinterface.media.ExifInterface import java.io.IOException import kotlin.math.min /** Create a bitmap that is not larger than the given desired max width or height and that is * rotated according to its EXIF information */ fun decodeScaledBitmapAndNormalize(imagePath: String, desiredMaxWidth: Int, desiredMaxHeight: Int): Bitmap? { var (width, height) = getImageSize(imagePath) ?: return null val maxWidth = min(width, desiredMaxWidth) val maxHeight = min(height, desiredMaxHeight) // Calculate the correct inSampleSize/resize value. This helps reduce memory use. It should be a power of 2 // from: https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966 var inSampleSize = 1 while (width / 2 > maxWidth || height / 2 > maxHeight) { width /= 2 height /= 2 inSampleSize *= 2 } val desiredScale = maxWidth.toFloat() / width // Decode with inSampleSize val options = BitmapFactory.Options().also { it.inJustDecodeBounds = false it.inDither = false it.inSampleSize = inSampleSize it.inScaled = false it.inPreferredConfig = Bitmap.Config.ARGB_8888 } val sampledSrcBitmap = BitmapFactory.decodeFile(imagePath, options) // Resize & Rotate val matrix = getRotationMatrix(imagePath) matrix.postScale(desiredScale, desiredScale) val result = Bitmap.createBitmap( sampledSrcBitmap, 0, 0, sampledSrcBitmap.width, sampledSrcBitmap.height, matrix, true) if (result != sampledSrcBitmap) { sampledSrcBitmap.recycle() } return result } private fun getImageSize(imagePath: String): Size? { val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(imagePath, options) val width = options.outWidth val height = options.outHeight if (width <= 0 || height <= 0) return null return Size(width, height) } private fun getRotationMatrix(imagePath: String): Matrix = try { ExifInterface(imagePath).rotationMatrix } catch (ignore: IOException) { Matrix() } private data class Size(val width: Int, val height: Int) val ExifInterface.rotationMatrix: Matrix get() { val orientation = getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED ) val matrix = Matrix() when (orientation) { ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f) ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f) ExifInterface.ORIENTATION_FLIP_VERTICAL -> { matrix.setRotate(180f) matrix.postScale(-1f, 1f) } ExifInterface.ORIENTATION_TRANSPOSE -> { matrix.setRotate(90f) matrix.postScale(-1f, 1f) } ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f) ExifInterface.ORIENTATION_TRANSVERSE -> { matrix.setRotate(-90f) matrix.postScale(-1f, 1f) } ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f) } return matrix }
gpl-3.0
120ceeb26fea7c87dd8d209084893ddc
35.095745
124
0.66873
4.705964
false
false
false
false
akvo/akvo-flow-mobile
app/src/main/java/org/akvo/flow/presentation/form/view/groups/CascadeQuestionLayout.kt
1
1855
/* * Copyright (C) 2020 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.presentation.form.view.groups import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.widget.LinearLayout import android.widget.TextView import com.google.android.material.textfield.TextInputEditText import org.akvo.flow.presentation.form.view.groups.entity.ViewQuestionAnswer class CascadeQuestionLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { fun setUpViews(questionAnswer: ViewQuestionAnswer.CascadeViewQuestionAnswer) { for (cascadeLevel in questionAnswer.answers) { val textView = TextView(context) textView.text = cascadeLevel.level textView.setTypeface(null, Typeface.BOLD) textView.textSize = 18.0f addView(textView) val textInputEditText = TextInputEditText(context) textInputEditText.isEnabled = false textInputEditText.setText(cascadeLevel.answer) addView(textInputEditText) } } }
gpl-3.0
3538472dea3b255330d951f9a84cde4d
38.468085
82
0.734232
4.52439
false
false
false
false
pie-flavor/Pieconomy
src/main/kotlin/flavor/pie/pieconomy/PieconomyService.kt
1
2827
package flavor.pie.pieconomy import com.github.benmanes.caffeine.cache.Caffeine import com.github.benmanes.caffeine.cache.LoadingCache import com.google.common.collect.ImmutableList import flavor.pie.kludge.* import org.spongepowered.api.service.context.ContextCalculator import org.spongepowered.api.service.economy.Currency import org.spongepowered.api.service.economy.EconomyService import org.spongepowered.api.service.economy.account.Account import org.spongepowered.api.service.economy.account.UniqueAccount import java.util.Optional import java.util.UUID import java.util.concurrent.TimeUnit class PieconomyService : EconomyService { val cache: LoadingCache<UUID, PieconomyPlayerAccount> = Caffeine.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES).build(::PieconomyPlayerAccount) val serverAccounts: MutableMap<String, PieconomyServerAccount> = HashMap() override fun getOrCreateAccount(uuid: UUID): Optional<UniqueAccount> = cache[uuid].optional override fun getOrCreateAccount(identifier: String): Optional<Account> = (serverAccounts.values.firstOrNull { it.name == identifier } ?: if (config.serverAccounts.dynamicAccounts.enable) { PieconomyServerAccount(identifier, currencies = ImmutableList.copyOf(currencies.filter( if (config.serverAccounts.dynamicAccounts.currencies.type == ServerAccountCurrencyType.BLACKLIST) { { c -> c !in config.serverAccounts.dynamicAccounts.currencies.values } } else { { c -> c in config.serverAccounts.dynamicAccounts.currencies.values } } )), negativeValues = ImmutableList.copyOf(currencies.filter( if (config.serverAccounts.dynamicAccounts.negativeValues.type == ServerAccountCurrencyType.BLACKLIST) { { c -> c !in config.serverAccounts.dynamicAccounts.negativeValues.values } } else { { c -> c in config.serverAccounts.dynamicAccounts.negativeValues.values } } ))) } else { null }).optional override fun registerContextCalculator(calculator: ContextCalculator<Account>?) {} override fun getDefaultCurrency(): Currency = config.defaultCurrency override fun getCurrencies(): Set<Currency> = GameRegistry.getAllOf(Currency::class.java).toSet() override fun hasAccount(uuid: UUID): Boolean = uuid.user() != null override fun hasAccount(identifier: String): Boolean = serverAccounts.values.any { it.name == identifier } }
mit
0cda6b838456cbb5ec3fa14916d8110f
50.4
135
0.655465
5.264432
false
true
false
false
faceofcat/Tesla-Powered-Thingies
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/compoundmaker/CompoundMakerEntity.kt
1
10800
package net.ndrei.teslapoweredthingies.machines.compoundmaker import net.minecraft.entity.player.EntityPlayerMP import net.minecraft.item.EnumDyeColor import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagString import net.minecraft.util.ResourceLocation import net.minecraftforge.common.util.Constants import net.minecraftforge.fluids.IFluidTank import net.minecraftforge.items.IItemHandlerModifiable import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslacorelib.inventory.FluidTankType import net.ndrei.teslacorelib.inventory.SyncProviderLevel import net.ndrei.teslacorelib.netsync.SimpleNBTMessage import net.ndrei.teslapoweredthingies.TeslaThingiesMod import net.ndrei.teslapoweredthingies.common.gui.IMultiTankMachine import net.ndrei.teslapoweredthingies.common.gui.TankInfo import net.ndrei.teslapoweredthingies.machines.BaseThingyMachine import net.ndrei.teslapoweredthingies.render.DualTankEntityRenderer import java.util.function.Consumer import java.util.function.Supplier class CompoundMakerEntity : BaseThingyMachine(CompoundMakerEntity::class.java.name.hashCode()), IMultiTankMachine { private lateinit var leftFluid: IFluidTank private lateinit var rightFluid: IFluidTank private lateinit var topInventory: IItemHandlerModifiable private lateinit var bottomInventory: IItemHandlerModifiable private lateinit var outputInventory: IItemHandlerModifiable //#region inventory & gui override fun initializeInventories() { this.leftFluid = this.addSimpleFluidTank(5000, "Left Tank", EnumDyeColor.BLUE, 52, 25, FluidTankType.INPUT, { fluid -> CompoundMakerRegistry.acceptsLeft(fluid) }) this.topInventory = this.addSimpleInventory(3, "input_top", EnumDyeColor.GREEN, "Top Inputs", BoundingRectangle.slots(70, 22, 3, 1), { stack, _ -> CompoundMakerRegistry.acceptsTop(stack)}, { _, _ -> false }, true) this.bottomInventory = this.addSimpleInventory(3, "input_bottom", EnumDyeColor.BROWN, "Bottom Inputs", BoundingRectangle.slots(70, 64, 3, 1), { stack, _ -> CompoundMakerRegistry.acceptsBottom(stack) }, { _, _ -> false }, true) this.rightFluid = this.addSimpleFluidTank(5000, "Right Tank", EnumDyeColor.PURPLE, 124, 25, FluidTankType.INPUT, { fluid -> CompoundMakerRegistry.acceptsRight(fluid) }) this.outputInventory = this.addSimpleInventory(1, "output", EnumDyeColor.ORANGE, "Output", BoundingRectangle.slots(88, 43, 1, 1), { _, _ -> false }, { _, _ -> true }, false) super.registerSyncStringPart(SYNC_CURRENT_RECIPE, Consumer { this.currentRecipe = if (it.string.isNotEmpty()) CompoundMakerRegistry.getRecipe(ResourceLocation(it.string)) else null }, Supplier { NBTTagString(if (this.currentRecipe != null) this.currentRecipe!!.registryName.toString() else "") }, SyncProviderLevel.GUI) super.registerSyncStringPart(SYNC_LOCKED_RECIPE, Consumer { this.lockedRecipe = if (it.string.isNotEmpty()) CompoundMakerRegistry.getRecipe(ResourceLocation(it.string)) else null }, Supplier { NBTTagString(if (this.lockedRecipe != null) this.lockedRecipe!!.registryName.toString() else "") }, SyncProviderLevel.GUI) super.registerSyncStringPart(SYNC_RECIPE_MODE, Consumer { this.recipeMode = RecipeRunType.valueOf(it.string) }, Supplier { NBTTagString(this.recipeMode.name) }, SyncProviderLevel.GUI) super.initializeInventories() } override fun shouldAddFluidItemsInventory() = false override fun getRenderers() = super.getRenderers().also { it.add(DualTankEntityRenderer) } override fun getTanks() = listOf( TankInfo(4.0, 8.0, this.leftFluid.fluid, this.leftFluid.capacity), TankInfo(22.0, 8.0, this.rightFluid.fluid, this.rightFluid.capacity) ) override fun getGuiContainerPieces(container: BasicTeslaGuiContainer<*>) = super.getGuiContainerPieces(container).also { // it.add(BasicRenderedGuiPiece(70, 40, 54, 24, // ThingiesTexture.MACHINES_TEXTURES.resource, 5, 105)) CompoundMakerIcon.CENTER_BACKGROUND.addStaticPiece(it, 70,40) it.add(CompoundRecipeSelectorPiece(this)) it.add(CompoundRecipeButtonPiece(this, CompoundRecipeButtonPiece.Direction.UP, top = 25)) it.add(CompoundRecipeButtonPiece(this, CompoundRecipeButtonPiece.Direction.DOWN, top = 52)) it.add(CompoundRecipeTriggerPiece(this)) } //#endregion //#region selected recipe methods private var _availableRecipes: List<CompoundMakerRecipe>? = null private var recipeMode = RecipeRunType.PAUSED private var recipeIndex = 0 private var currentRecipe: CompoundMakerRecipe? = null private var lockedRecipe: CompoundMakerRecipe? = null override fun onSyncPartUpdated(key: String) { if (key in arrayOf("input_top", "input_bottom", "fluids")) { this._availableRecipes = null } // TeslaThingiesMod.logger.info("UPDATED: ${key}") } val availableRecipes: List<CompoundMakerRecipe> get() { if (this._availableRecipes == null) this._availableRecipes = CompoundMakerRegistry.findRecipes(this.leftFluid, this.topInventory, this.rightFluid, this.bottomInventory) return this._availableRecipes ?: listOf() } val hasCurrentRecipe get() = (this.currentRecipe != null) || (this.lockedRecipe != null) val selectedRecipe: CompoundMakerRecipe? get() = this.currentRecipe ?: this.lockedRecipe ?: this.availableRecipes.let { if (it.isEmpty()) null else it[this.recipeIndex % it.size] } var selectedRecipeIndex: Int get() = this.availableRecipes.let { if (it.isEmpty()) 0 else (this.recipeIndex % it.size) } set(value) { if (value in this.availableRecipes.indices) { this.recipeIndex = value if (this.world?.isRemote == true) { this.sendToServer(this.setupSpecialNBTMessage("SET_RECIPE_INDEX").also { it.setInteger("recipe_index", this.recipeIndex) }) } } } var selectedRecipeMode: RecipeRunType get() = this.recipeMode set(value) { if (this.recipeMode != value) { this.recipeMode = value if (this.recipeMode != RecipeRunType.PAUSED) { this.setLockedRecipe(this.selectedRecipe) } else { this.setLockedRecipe(null) } if (this.world?.isRemote == true) { this.sendToServer(this.setupSpecialNBTMessage("SET_RECIPE_MODE").also { it.setInteger("recipe_mode", this.recipeMode.ordinal) }) } else { this.partialSync(CompoundMakerEntity.SYNC_RECIPE_MODE) } } } private fun setLockedRecipe(recipe: CompoundMakerRecipe?) { if (this.lockedRecipe?.registryName != recipe?.registryName) { this.lockedRecipe = recipe if (this.world?.isRemote == false) { this.partialSync(CompoundMakerEntity.SYNC_LOCKED_RECIPE) } } } override fun processClientMessage(messageType: String?, player: EntityPlayerMP?, compound: NBTTagCompound): SimpleNBTMessage? { when(messageType) { "SET_RECIPE_INDEX" -> { if (compound.hasKey("recipe_index", Constants.NBT.TAG_INT)) { this.selectedRecipeIndex = compound.getInteger("recipe_index") } return null } "SET_RECIPE_MODE" -> { if (compound.hasKey("recipe_mode", Constants.NBT.TAG_INT)) { this.selectedRecipeMode = RecipeRunType.byOrdinal(compound.getInteger("recipe_mode")) } return null } } return super.processClientMessage(messageType, player, compound) } enum class RecipeRunType(val langKey: String) { PAUSED("Machine Paused"), SINGLE("Make Single Item"), ALL("Make Maximum Items"), LOCK("Lock Recipe"); val next get() = RecipeRunType.values()[(this.ordinal + 1) % RecipeRunType.values().size] companion object { fun byOrdinal(ordinal: Int) = RecipeRunType.values()[ordinal % RecipeRunType.values().size] } } //#endregion override fun getEnergyRequiredForWork(): Long { if (this.recipeMode != RecipeRunType.PAUSED) { if (this.lockedRecipe?.matches(this.leftFluid, this.topInventory, this.rightFluid, this.bottomInventory) == true) { this.currentRecipe = this.lockedRecipe TeslaThingiesMod.logger.info("Current Recipe: ${this.currentRecipe!!.registryName}") this.currentRecipe!!.processInventories(this.leftFluid, this.topInventory, this.rightFluid, this.bottomInventory) return super.getEnergyRequiredForWork() } } return 0L } override fun performWork(): Float { if (this.currentRecipe != null) { val stack = this.currentRecipe!!.output.copy() if (this.outputInventory.insertItem(0, stack, true).isEmpty) { this.outputInventory.insertItem(0, stack, false) when (this.recipeMode) { RecipeRunType.SINGLE -> { this.selectedRecipeMode = RecipeRunType.PAUSED } RecipeRunType.ALL -> { if (!this.currentRecipe!!.matches(this.leftFluid, this.topInventory, this.rightFluid, this.bottomInventory)) { this.selectedRecipeMode = RecipeRunType.PAUSED } } else -> { } } TeslaThingiesMod.logger.info("Current Recipe: [null]; Locked Recipe: ${this.lockedRecipe?.registryName}") this.currentRecipe = null this.partialSync(SYNC_CURRENT_RECIPE) return 1.0f } } return 0.0f } companion object { const val SYNC_CURRENT_RECIPE = "current_recipe" const val SYNC_LOCKED_RECIPE = "locked_recipe" const val SYNC_RECIPE_MODE = "recipe_mode" } }
mit
b97f02cc3ad6ccafd4d1ac20b5e0f6da
41.519685
148
0.633519
4.893521
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/util/AndroidUtility.kt
1
12027
package com.pr0gramm.app.util import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.database.sqlite.SQLiteFullException import android.graphics.Point import android.graphics.drawable.Drawable import android.net.ConnectivityManager import android.os.Build import android.os.Looper import android.text.SpannableStringBuilder import android.text.style.BulletSpan import android.text.style.LeadingMarginSpan import android.util.LruCache import android.view.View import android.view.WindowInsets import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.appcompat.content.res.AppCompatResources import androidx.core.app.TaskStackBuilder import androidx.core.content.getSystemService import androidx.core.content.res.ResourcesCompat import androidx.core.content.res.use import androidx.core.graphics.drawable.DrawableCompat import androidx.core.net.ConnectivityManagerCompat import androidx.core.text.inSpans import androidx.core.view.postDelayed import com.google.firebase.crashlytics.FirebaseCrashlytics import com.pr0gramm.app.BuildConfig import com.pr0gramm.app.Logger import com.pr0gramm.app.R import com.pr0gramm.app.debugConfig import com.pr0gramm.app.ui.PermissionHelperDelegate import com.pr0gramm.app.ui.base.AsyncScope import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.launch import retrofit2.HttpException import java.io.IOException import java.io.PrintWriter import java.io.StringWriter /** * Place to put everything that belongs nowhere. Thanks Obama. */ object AndroidUtility { private val logger = Logger("AndroidUtility") private val EXCEPTION_BLACKLIST = listOf("MediaCodec", "dequeueInputBuffer", "dequeueOutputBuffer", "releaseOutputBuffer", "native_") private val cache = LruCache<Int, Unit>(6) /** * Gets the height of the action bar as definied in the style attribute * [R.attr.actionBarSize] plus the height of the status bar on android * Kitkat and above. * @param context A context to resolve the styled attribute value for */ fun getActionBarContentOffset(context: Context): Int { return getStatusBarHeight(context) + getActionBarHeight(context) } /** * Gets the height of the actionbar. */ private fun getActionBarHeight(context: Context): Int { context.obtainStyledAttributes(intArrayOf(R.attr.actionBarSize)).use { ta -> return ta.getDimensionPixelSize(ta.getIndex(0), -1) } } /** * Gets the height of the statusbar. */ fun getStatusBarHeight(context: Context): Int { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val window = activityFromContext(context)?.window val rootWindowInsets = window?.decorView?.rootWindowInsets if (rootWindowInsets != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // this seems to be always correct on android 11 and better. return rootWindowInsets .getInsetsIgnoringVisibility(WindowInsets.Type.statusBars()) .top } // this works for android 6 and above return rootWindowInsets.stableInsetTop } } // use the old code as fallback in case we have a really old android // or if we don't have a window or decorView var result = 0 val resources = context.resources val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android") if (resourceId > 0) { result = resources.getDimensionPixelSize(resourceId) } return result } fun logToCrashlytics(error: Throwable?, force: Boolean = false) { val causalChain = error?.causalChain ?: return if (causalChain.containsType<CancellationException>()) { return } if (!force) { if (causalChain.containsType<PermissionHelperDelegate.PermissionNotGranted>()) { return } if (causalChain.containsType<IOException>() || causalChain.containsType<HttpException>()) { logger.warn(error) { "Ignoring network exception" } return } if (causalChain.containsType<SQLiteFullException>()) { logger.warn { "Database is full: $error" } return } } try { val trace = StringWriter().also { w -> error.printStackTrace(PrintWriter(w)) }.toString() if (EXCEPTION_BLACKLIST.any { word -> word in trace }) { logger.warn("Ignoring exception", error) return } val errorStr = error.toString() if ("connect timed out" in errorStr) { return } // try to rate limit exceptions. val key = System.identityHashCode(error) if (cache.get(key) != null) { return } else { cache.put(key, Unit) } ignoreAllExceptions { FirebaseCrashlytics.getInstance().recordException(error) } } catch (err: Throwable) { logger.warn(err) { "Could not send error $error to crash tool" } } } fun isOnMobile(context: Context?): Boolean { context ?: return false val cm = context.getSystemService( Context.CONNECTIVITY_SERVICE ) as ConnectivityManager return ConnectivityManagerCompat.isActiveNetworkMetered(cm) } /** * Gets the color tinted hq-icon */ fun getTintedDrawable(context: Context, @DrawableRes drawableId: Int, @ColorRes colorId: Int): Drawable { val resources = context.resources val icon = DrawableCompat.wrap(AppCompatResources.getDrawable(context, drawableId)!!) DrawableCompat.setTint(icon, ResourcesCompat.getColor(resources, colorId, null)) return icon } /** * Returns a CharSequence containing a bulleted and properly indented list. * @param leadingMargin In pixels, the space between the left edge of the bullet and the left edge of the text. * * * @param lines An array of CharSequences. Each CharSequences will be a separate line/bullet-point. */ fun makeBulletList(leadingMargin: Int, lines: List<CharSequence>): CharSequence { return SpannableStringBuilder().apply { for (idx in lines.indices) { inSpans(BulletSpan(leadingMargin / 3)) { inSpans(LeadingMarginSpan.Standard(leadingMargin)) { append(lines[idx]) } } val last = idx == lines.lastIndex append(if (last) "" else "\n") } } } fun buildVersionCode(): Int { return if (BuildConfig.DEBUG) { debugConfig.versionOverride ?: BuildConfig.VERSION_CODE } else { BuildConfig.VERSION_CODE } } fun showSoftKeyboard(view: EditText?) { view?.postDelayed(100) { try { view.requestFocus() val imm = view.context.getSystemService<InputMethodManager>() imm?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT) } catch (err: Exception) { logger.warn(err) { "Failed to show soft keyboard" } } } } fun hideSoftKeyboard(view: View?) { if (view != null) { try { val imm = view.context.getSystemService<InputMethodManager>() imm?.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } catch (err: Exception) { logger.warn(err) { "Failed to hide soft keyboard" } } } } fun recreateActivity(activity: Activity) { val intent = Intent(activity.intent) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK TaskStackBuilder.create(activity) .addNextIntentWithParentStack(intent) .startActivities() } fun applyWindowFullscreen(activity: Activity, fullscreen: Boolean) { var flags = 0 if (fullscreen) { flags = flags or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION flags = flags or (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_FULLSCREEN) flags = flags or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY } val decorView = activity.window.decorView decorView.systemUiVisibility = flags } fun screenSize(activity: Activity): Point { val screenSize = Point() val display = activity.windowManager.defaultDisplay display.getRealSize(screenSize) return screenSize } fun screenIsLandscape(activity: Activity?): Boolean { if (activity == null) { return false } val size = screenSize(activity) return size.x > size.y } /** * Tries to get a basic activity from the given context. Returns an empty observable, * if no activity could be found. */ fun activityFromContext(context: Context): Activity? { if (context is Activity) return context if (context is ContextWrapper) return activityFromContext(context.baseContext) return null } @ColorInt fun resolveColorAttribute(context: Context, attr: Int): Int { val arr = context.obtainStyledAttributes(intArrayOf(attr)) try { return arr.getColor(arr.getIndex(0), 0) } finally { arr.recycle() } } } @Suppress("NOTHING_TO_INLINE") inline fun checkMainThread() = debugOnly { if (Looper.getMainLooper().thread !== Thread.currentThread()) { Logger("AndroidUtility").error { "Expected to be in main thread but was: ${Thread.currentThread().name}" } throw IllegalStateException("Must be called from the main thread.") } } @Suppress("NOTHING_TO_INLINE") inline fun checkNotMainThread(msg: String? = null) = debugOnly { if (Looper.getMainLooper().thread === Thread.currentThread()) { Logger("AndroidUtility").error { "Expected not to be on main thread: $msg" } throw IllegalStateException("Must not be called from the main thread: $msg") } } inline fun <T> doInBackground(crossinline action: suspend () -> T): Job { return AsyncScope.launch { try { action() } catch (thr: Throwable) { // log it AndroidUtility.logToCrashlytics(BackgroundThreadException(thr)) } } } class BackgroundThreadException(cause: Throwable) : RuntimeException(cause) fun Throwable.getMessageWithCauses(): String { val error = this val type = javaClass.name .replaceFirst(".+\\.".toRegex(), "") .replace('$', '.') val cause = error.cause val hasCause = cause != null && error !== cause val message = error.message ?: "" val hasMessage = message.isNotBlank() && ( !hasCause || (cause != null && cause.javaClass.directName !in message)) return if (hasMessage) { if (hasCause && cause != null) { "$type(${error.message}), caused by ${cause.getMessageWithCauses()}" } else { "$type(${error.message})" } } else { if (hasCause && cause != null) { "$type, caused by ${cause.getMessageWithCauses()}" } else { type } } }
mit
d29775c16137ae23ac892a57674073a0
31.953425
115
0.626923
4.853511
false
false
false
false
damien5314/RxReddit
library/src/main/java/rxreddit/model/Link.kt
1
7654
package rxreddit.model import com.google.gson.annotations.SerializedName data class Link( @SerializedName("data") internal val data: Data, ) : Listing(), Votable, Savable, Hideable { override val id: String get() = data.id val domain: String? get() = data.domain val mediaEmbed: MediaEmbed? get() = data.mediaEmbed val subreddit: String? get() = data.subreddit val selftextHtml: String? get() = data.selftextHtml val selftext: String? get() = data.selftext val edited: Boolean get() = when (data.edited) { "true" -> true "0", "false", null, -> false else -> false } override var liked: Boolean? by data::liked val userReports: List<UserReport>? get() = data.userReports val linkFlairText: Any? get() = data.linkFlairText val gilded: Int? get() = data.gilded override val archived: Boolean get() = data.isArchived ?: false val clicked: Boolean get() = data.clicked ?: false val author: String? get() = data.author val numComments: Int? get() = data.numComments var score: Int? by data::score override fun applyVote(direction: Int) { val scoreDiff = direction - likedScore data.liked = when (direction) { 0 -> null 1 -> true -1 -> false else -> null } if (data.score == null) return data.score = data.score?.plus(scoreDiff) ?: 0 } private val likedScore: Int get() = if (liked == null) 0 else if (liked == true) 1 else -1 val approvedBy: Any? get() = data.approvedBy val over18: Boolean get() = data.over18 ?: false override var hidden: Boolean get() = data.hidden ?: false set(value) { data.hidden = value } val thumbnail: String? get() = data.thumbnail val subredditId: String? get() = data.subredditId val isScoreHidden: Boolean get() = data.hideScore ?: false val linkFlairCssClass: Any? get() = data.linkFlairCssClass val authorFlairCssClass: Any? get() = data.authorFlairCssClass val downs: Int? get() = data.downs override var isSaved: Boolean get() = if (data.saved == null) false else data.saved!! set(value) { data.saved = value } val stickied: Boolean get() = data.stickied ?: false val isSelf: Boolean get() = data.isSelf ?: false val permalink: String? get() = data.permalink val created: Double? get() = data.created val url: String? get() = data.url val authorFlairText: Any? get() = data.authorFlairText val title: String? get() = data.title val createdUtc: Double? get() = data.createdUtc val distinguished: String? get() = data.distinguished val media: Media? get() = data.media val modReports: List<ModReport>? get() = data.modReports val visited: Boolean get() = data.visited ?: false val numReports: Any? get() = data.numReports val ups: Int? get() = data.ups val previewImages: List<Image>? get() = if (data.preview == null) null else data.preview.images val isGallery: Boolean get() = data.isGallery ?: false val galleryItems: List<GalleryItem> get() = if (data.isGallery == true) { data.galleryItems.items.mapNotNull { galleryItemJson -> return@mapNotNull data.mediaMetadata[galleryItemJson.mediaId]?.let { media -> GalleryItem( url = media.s.u, ) } } } else emptyList() data class Data( @SerializedName("preview") val preview: Preview? = null, @SerializedName("domain") val domain: String? = null, @SerializedName("banned_by") val bannedBy: String? = null, @SerializedName("media_embed") val mediaEmbed: MediaEmbed? = null, @SerializedName("subreddit") val subreddit: String? = null, @SerializedName("selftext_html") val selftextHtml: String? = null, @SerializedName("selftext") val selftext: String? = null, @SerializedName("edited") val edited: String?, // TODO: Remove mutability here @SerializedName("likes") var liked: Boolean? = null, @SerializedName("user_reports") val userReports: List<UserReport>? = null, @SerializedName("link_flair_text") val linkFlairText: String? = null, @SerializedName("gilded") val gilded: Int? = null, @SerializedName("archived") val isArchived: Boolean? = null, @SerializedName("clicked") val clicked: Boolean? = null, @SerializedName("author") val author: String? = null, @SerializedName("num_comments") val numComments: Int? = null, // TODO: Remove mutability here @SerializedName("score") var score: Int? = null, @SerializedName("approved_by") val approvedBy: String? = null, @SerializedName("over_18") val over18: Boolean? = null, // TODO: Remove mutability here @SerializedName("hidden") var hidden: Boolean? = null, @SerializedName("thumbnail") val thumbnail: String? = null, @SerializedName("subreddit_id") val subredditId: String? = null, @SerializedName("hide_score") val hideScore: Boolean? = null, @SerializedName("link_flair_css_class") val linkFlairCssClass: String? = null, @SerializedName("author_flair_css_class") val authorFlairCssClass: String? = null, @SerializedName("downs") val downs: Int? = null, // TODO: Remove mutability here @SerializedName("saved") var saved: Boolean? = null, @SerializedName("stickied") val stickied: Boolean? = null, @SerializedName("is_self") val isSelf: Boolean? = null, @SerializedName("permalink") val permalink: String? = null, @SerializedName("created") val created: Double? = null, @SerializedName("url") val url: String? = null, @SerializedName("author_flair_text") val authorFlairText: String? = null, @SerializedName("title") val title: String? = null, @SerializedName("created_utc") val createdUtc: Double? = null, @SerializedName("distinguished") val distinguished: String? = null, @SerializedName("media") val media: Media? = null, @SerializedName("mod_reports") val modReports: List<ModReport>? = null, @SerializedName("visited") val visited: Boolean? = null, @SerializedName("num_reports") val numReports: Int? = null, @SerializedName("ups") val ups: Int? = null, @SerializedName("is_gallery") val isGallery: Boolean? = null, @SerializedName("gallery_data") internal val galleryItems: GalleryItems, @SerializedName("media_metadata") internal val mediaMetadata: Map<String, MediaMetadata>, ) : ListingData() data class Preview( @SerializedName("images") val images: List<Image>? = emptyList(), ) }
apache-2.0
af4c7f1805d7bbeffceb2f2621e1a386
23.375796
93
0.565979
4.442252
false
false
false
false
skiedrowski/jvm-project-template
buildSrc/src/main/kotlin/Dependencies.kt
1
1357
// see https://handstandsam.com/2018/02/11/kotlin-buildsrc-for-better-gradle-dependency-management/ // for an explanation of the idea object Ver { const val kotlin = "1.4.31" const val apache_http_core = "4.4.9" const val apache_http_client = "4.5.5" const val junit = "5.7.+" const val mockito_kotlin = "1.6.+" const val hamkrest = "1.8.+" const val hamcrest = "1.3" const val mockito = "2.28.2" } object Deps { const val kt_stdlib_jdk8 = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${Ver.kotlin}" val apache_http_core = "org.apache.httpcomponents:httpcore:${Ver.apache_http_core}" val apache_http_client = "org.apache.httpcomponents:httpclient:${Ver.apache_http_client}" const val kotlin_reflect = "org.jetbrains.kotlin:kotlin-reflect:${Ver.kotlin}" const val junit = "org.junit.jupiter:junit-jupiter-api:${Ver.junit}" const val junit_engine = "org.junit.jupiter:junit-jupiter-engine:${Ver.junit}" const val mockito_kotlin = "com.nhaarman:mockito-kotlin:${Ver.mockito_kotlin}" const val hamkrest = "com.natpryce:hamkrest:${Ver.hamkrest}" const val hamcrest_integration = "org.hamcrest:hamcrest-integration:${Ver.hamcrest}" const val mockito_core = "org.mockito:mockito-core:${Ver.mockito}" const val mockito_junit_jupiter = "org.mockito:mockito-junit-jupiter:${Ver.mockito}" }
mit
5aff3063a53c77cf7f2e5782d88c8177
44.233333
99
0.699337
3.342365
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/providers/NetworkProvider.kt
1
4175
/***************************************************************************** * NetworkProvider.kt ***************************************************************************** * Copyright © 2018 VLC authors and VideoLAN * * 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 2 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 org.videolan.vlc.providers import android.content.Context import android.net.Uri import androidx.lifecycle.Observer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.withContext import org.videolan.libvlc.util.MediaBrowser import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.media.DummyItem import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.tools.NetworkMonitor import org.videolan.tools.livedata.LiveDataset import org.videolan.vlc.R @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi class NetworkProvider(context: Context, dataset: LiveDataset<MediaLibraryItem>, url: String? = null, showHiddenFiles: Boolean): BrowserProvider(context, dataset, url, showHiddenFiles), Observer<List<MediaWrapper>> { override suspend fun browseRootImpl() { dataset.clear() dataset.value = mutableListOf() if (NetworkMonitor.getInstance(context).lanAllowed) browse() } override fun fetch() {} override suspend fun requestBrowsing(url: String?, eventListener: MediaBrowser.EventListener, interact : Boolean) = withContext(Dispatchers.IO) { initBrowser() mediabrowser?.let { it.changeEventListener(eventListener) if (url != null) it.browse(Uri.parse(url), getFlags(interact)) else it.discoverNetworkShares() } } override fun refresh() { val list by lazy(LazyThreadSafetyMode.NONE) { getList(url!!) } when { url == null -> { browseRoot() } list !== null -> { dataset.value = list as MutableList<MediaLibraryItem> removeList(url) parseSubDirectories() computeHeaders(list as MutableList<MediaLibraryItem>) } else -> super.refresh() } } override fun parseSubDirectories(list : List<MediaLibraryItem>?) { if (url != null) super.parseSubDirectories(list) } override fun stop() { if (url == null) clearListener() return super.stop() } override fun onChanged(favs: List<MediaWrapper>?) { val data = dataset.value.toMutableList() data.listIterator().run { while (hasNext()) { val item = next() if (item.hasStateFlags(MediaLibraryItem.FLAG_FAVORITE) || item is DummyItem) remove() } } dataset.value = data.apply { getFavoritesList(favs)?.let { addAll(0, it) } } } private fun getFavoritesList(favs: List<MediaWrapper>?): MutableList<MediaLibraryItem>? { if (favs?.isNotEmpty() == true) { val list = mutableListOf<MediaLibraryItem>() list.add(0, DummyItem(context.getString(R.string.network_favorites))) for ((index, fav) in favs.withIndex()) list.add(index + 1, fav) list.add(DummyItem(context.getString(R.string.network_shared_folders))) return list } return null } }
gpl-2.0
c4b4771527b6e2336089137d620dc220
38.018692
215
0.639674
4.92217
false
false
false
false
andrei-heidelbacher/metanalysis
services/chronolens-java/src/test/kotlin/org/chronolens/java/JavaParserTest.kt
1
1541
/* * Copyright 2018 Andrei Heidelbacher <[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 org.chronolens.java import org.chronolens.core.model.SourceFile import org.chronolens.core.parsing.Parser import org.chronolens.core.parsing.Result import org.chronolens.test.core.model.SourceFileBuilder import org.chronolens.test.core.model.sourceFile import kotlin.test.fail abstract class JavaParserTest { private val defaultPath = "Test.java" protected fun sourceFile(init: SourceFileBuilder.() -> Unit): SourceFile = sourceFile(defaultPath).build(init) protected fun parse( source: String, path: String = defaultPath ): SourceFile { val result = Parser.parse(path, source) return when (result) { is Result.Success -> result.source else -> fail() } } protected fun parseResult( source: String, path: String = defaultPath ): Result = Parser.parse(path, source) ?: fail() }
apache-2.0
0c3deefcf5fb3b13d1e78dcadb98103c
31.787234
78
0.706684
4.304469
false
true
false
false
didi/DoraemonKit
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/oldui/DoKitMcManager.kt
1
1507
package com.didichuxing.doraemonkit.kit.mc.oldui import com.didichuxing.doraemonkit.kit.core.DoKitManager import com.didichuxing.doraemonkit.kit.test.TestMode import com.didichuxing.doraemonkit.kit.test.mock.data.HostInfo import com.didichuxing.doraemonkit.util.SPUtils /** * didi Create on 2022/4/22 . * * Copyright (c) 2022/4/22 by didiglobal.com. * * @author <a href="[email protected]">zhangjun</a> * @version 1.0 * @Date 2022/4/22 12:25 下午 * @Description 用一句话说明文件功能 */ object DoKitMcManager { const val MC_CASE_ID_KEY = "MC_CASE_ID" const val MC_CASE_RECODING_KEY = "MC_CASE_RECODING" const val DOKIT_MC_CONNECT_URL = "dokit_mc_connect_url" const val NAME_DOKIIT_MC_CONFIGALL = "dokiit-mc-config-all" /** * 是否处于录制状态 */ var IS_MC_RECODING = false /** * 主机信息 */ var HOST_INFO: HostInfo? = null var MC_CASE_ID: String = "" var WS_MODE: TestMode = TestMode.UNKNOWN var CONNECT_MODE: TestMode = TestMode.UNKNOWN var sp: SPUtils = SPUtils.getInstance(NAME_DOKIIT_MC_CONFIGALL) private var mode: TestMode = TestMode.UNKNOWN fun getMode(): TestMode { return mode } fun init() { loadConfig() } fun loadConfig() { DoKitManager.MC_CONNECT_URL = sp.getString(DOKIT_MC_CONNECT_URL) } fun saveMcConnectUrl(url: String) { DoKitManager.MC_CONNECT_URL = url sp.put(DOKIT_MC_CONNECT_URL, url) } }
apache-2.0
757fbe170d7d8696d1615d6b2322f124
20.776119
72
0.659356
3.323462
false
true
false
false
liceoArzignano/app_bold
app/src/main/kotlin/it/liceoarzignano/bold/marks/SubjectAdapter.kt
1
2362
package it.liceoarzignano.bold.marks import android.content.Context import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import it.liceoarzignano.bold.R import it.liceoarzignano.bold.utils.HelpToast import it.liceoarzignano.bold.utils.Time import java.util.* internal class SubjectAdapter(private var mMarks: List<Mark>, private val mContext: Context) : androidx.recyclerview.widget.RecyclerView.Adapter<SubjectAdapter.SubjectHolder>() { override fun onCreateViewHolder(parent: ViewGroup, type: Int): SubjectHolder = SubjectHolder(LayoutInflater.from(parent.context) .inflate(R.layout.item_mark, parent, false)) override fun onBindViewHolder(holder: SubjectHolder, position: Int) = holder.setData(mMarks[position]) override fun getItemCount(): Int = mMarks.size fun updateList(marks: List<Mark>) { mMarks = marks notifyDataSetChanged() } internal inner class SubjectHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) { private val mView: View = view.findViewById(R.id.row_mark_root) private val mValue: TextView = view.findViewById(R.id.row_mark_value) private val mDate: TextView = view.findViewById(R.id.row_mark_date) private val mSummary: TextView = view.findViewById(R.id.row_mark_summary) fun setData(mark: Mark) { mDate.text = Time(mark.date).asString(mContext) val value = mark.value.toDouble() / 100 if (value < 6) { mValue.setTextColor(Color.RED) } mValue.text = String.format(Locale.ENGLISH, "%.2f", value) val summary = mark.description val hasSummary = !summary.isEmpty() if (hasSummary) { mSummary.text = summary } mView.setOnClickListener { if (hasSummary) { mSummary.visibility = if (mSummary.visibility == View.VISIBLE) View.GONE else View.VISIBLE } HelpToast(mContext, HelpToast.KEY_MARK_LONG_PRESS) } mView.setOnLongClickListener { (mContext as SubjectActivity).marksAction(mark) } } } }
lgpl-3.0
a7aaee9ec60fecb56c4aeaf67328296d
36.492063
113
0.65072
4.456604
false
false
false
false
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/Account.kt
1
2027
package net.nemerosa.ontrack.model.security import com.fasterxml.jackson.annotation.JsonProperty import net.nemerosa.ontrack.model.structure.Entity import net.nemerosa.ontrack.model.structure.ID import java.io.Serializable data class Account( override val id: ID, val name: String, val fullName: String, val email: String, val authenticationSource: AuthenticationSource, val role: SecurityRole, val disabled: Boolean, val locked: Boolean, ) : Entity, Serializable { companion object { @JvmStatic fun of(name: String, fullName: String, email: String, role: SecurityRole, authenticationSource: AuthenticationSource, disabled: Boolean, locked: Boolean) = Account( ID.NONE, name, fullName, email, authenticationSource, role, disabled = disabled, locked = locked, ) } fun withId(id: ID): Account = Account( id, name, fullName, email, authenticationSource, role, disabled = disabled, locked = locked, ) fun update(input: AccountInput) = Account( id, input.name, input.fullName, input.email, authenticationSource, role, disabled = input.disabled, locked = input.locked, ) /** * Default built-in admin? */ @get:JsonProperty("defaultAdmin") val isDefaultAdmin get() = "admin" == name fun asPermissionTarget() = PermissionTarget( PermissionTargetType.ACCOUNT, id(), name, fullName ) }
mit
dd763c560c7e0a66c34ef7b51f41c6c5
26.391892
163
0.489393
5.662011
false
false
false
false
blakelee/CoinProfits
app/src/main/java/net/blakelee/coinprofits/di/AppModule.kt
1
4472
package net.blakelee.coinprofits.di import android.app.Application import android.arch.persistence.room.Room import android.content.SharedPreferences import android.support.v7.preference.PreferenceManager import com.jakewharton.picasso.OkHttp3Downloader import com.squareup.picasso.Picasso import dagger.Module import dagger.Provides import net.blakelee.coinprofits.repository.* import net.blakelee.coinprofits.repository.db.AppDatabase import net.blakelee.coinprofits.repository.db.CoinDao import net.blakelee.coinprofits.repository.db.HoldingsDao import net.blakelee.coinprofits.repository.db.TransactionDao import net.blakelee.coinprofits.repository.rest.ChartApi import net.blakelee.coinprofits.repository.rest.CoinApi import net.blakelee.coinprofits.repository.rest.ERC20Api import okhttp3.Cache import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.io.File import javax.inject.Singleton @Module class AppModule{ companion object { private const val NAME = "app.db" private const val DISK_CACHE_SIZE: Long = 5 * 1024 * 1024 const val IMAGE_URL = "https://files.coinmarketcap.com/static/img/coins/64x64/" private fun createHttpClient(app: Application): OkHttpClient.Builder { val cacheDir = File(app.cacheDir, "http") val cache = Cache(cacheDir, DISK_CACHE_SIZE) return OkHttpClient.Builder() .cache(cache) } } /** DATABASE COMPONENTS */ @Singleton @Provides fun providePersistentDatabase(app: Application): AppDatabase = Room.databaseBuilder(app, AppDatabase::class.java, NAME) .build() @Provides @Singleton fun provideCoinDao(db: AppDatabase) = db.coinModel() @Provides @Singleton fun provideHoldingsDao(db: AppDatabase) = db.holdingsModel() @Provides @Singleton fun provideTransactionDao(db: AppDatabase) = db.transactionModel() /** IMAGE COMPONENTS*/ @Provides @Singleton fun provideOkHttpClient(app: Application):OkHttpClient = createHttpClient(app).build() @Provides @Singleton fun providePicasso(client: OkHttpClient, app: Application): Picasso = Picasso.Builder(app) .downloader(OkHttp3Downloader(client)) .build() /** NETWORK COMPONENTS */ @Provides @Singleton fun provideCoinMarketCapApi(): CoinApi = Retrofit.Builder() .baseUrl(CoinApi.HTTPS_API_COINMARKETCAP_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(CoinApi::class.java) @Provides @Singleton fun provideChartApi(): ChartApi = Retrofit.Builder() .baseUrl(ChartApi.HTTPS_API_CHART_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(ChartApi::class.java) @Provides @Singleton fun provideERC20Api(): ERC20Api = Retrofit.Builder() .baseUrl(ERC20Api.HTTPS_API_ETHPLORER_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(ERC20Api::class.java) /** SHARED PREFERENCES COMPONENTS */ @Provides @Singleton fun provideSharedPreferences(app: Application): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(app) /** REPOSITORIES */ @Provides @Singleton fun provideChartRepository(api: ChartApi) = ChartRepository(api) @Provides @Singleton fun provideCoinRepository(dao: CoinDao, api: CoinApi) = CoinRepository(dao, api) @Provides @Singleton fun provideHoldingsRepository(hdao: HoldingsDao, cdao: CoinDao, api: CoinApi) = HoldingsRepository(hdao, cdao, api) @Provides @Singleton fun providePreferencesRepository(prefs: SharedPreferences) = PreferencesRepository(prefs) @Provides @Singleton fun provideTransactionRepository(db: TransactionDao, api: ERC20Api) = TransactionRepository(db, api) }
mit
fe997e8a1d26aa9dadcfd97bf4cdef79
31.889706
119
0.687612
4.687631
false
false
false
false
hewking/HUILibrary
app/src/main/java/com/hewking/custom/LoadingView.kt
1
3370
package com.hewking.custom import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View import android.view.animation.BounceInterpolator import com.hewking.custom.util.L import com.hewking.custom.util.dp2px /** * 项目名称:FlowChat * 类的描述: * 创建人员:hewking * 创建时间:2018/11/12 0012 * 修改人员:hewking * 修改时间:2018/11/12 0012 * 修改备注: * Version: 1.0.0 */ open class LoadingView(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) { private val TAG = "LoadingView" var color = Color.BLACK var size = dp2px(10f) var stroke = dp2px(10f) var count = 3 // 一秒三次 var interval = 1 set(value) { field = value postInvalidateOnAnimation() } init { val typedArray = ctx.obtainStyledAttributes(attrs, R.styleable.LoadingView) color = typedArray.getColor(R.styleable.LoadingView_h_color,color) typedArray.recycle() } private val animator = ValueAnimator.ofFloat(0f, 1f).apply { duration = 2000 interpolator = BounceInterpolator() repeatCount = ValueAnimator.INFINITE repeatMode = ValueAnimator.RESTART addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { override fun onAnimationUpdate(animation: ValueAnimator?) { // 1-3 val value = makeValue(animation?.animatedValue as Float) L.d("LoadingView", "value -> ${animation?.animatedValue} value : $value") if (value != interval) { interval = value } } }) } private fun makeValue(value : Float) : Int { val a = 1f.div(3) return (value.div(a) + 1).toInt() } private val mPaint by lazy { Paint().apply { isAntiAlias = true style = Paint.Style.FILL } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { L.d(TAG,"onMeasure") val wMode = MeasureSpec.getMode(widthMeasureSpec) var width = MeasureSpec.getSize(widthMeasureSpec) val hMode = MeasureSpec.getMode(heightMeasureSpec) var height = MeasureSpec.getSize(heightMeasureSpec) if (wMode == MeasureSpec.AT_MOST) { width = paddingStart + paddingEnd + size * count + 2 * stroke } if (hMode == MeasureSpec.AT_MOST) { height = paddingTop + paddingBottom + size } setMeasuredDimension(width, height) } override fun onDraw(canvas: Canvas?) { L.d(TAG,"onDraw") if (canvas == null) return var radius = size / 2 var cy = height / 2 for (i in 1 until interval + 1) { var cx = paddingStart + radius + (size + stroke) * (i - 1) canvas.drawCircle(cx.toFloat(), cy.toFloat(), radius.toFloat(), mPaint) } } override fun onAttachedToWindow() { super.onAttachedToWindow() // start animator animator.start() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() // end animator animator.end() } }
mit
f5f97141c93bf20f083381a20f8b7390
25.556452
89
0.608445
4.485014
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/service/ServiceBaseId.kt
1
827
package com.soywiz.korge.service import com.soywiz.kds.linkedHashMapOf open class ServiceBaseId() { private val map: LinkedHashMap<String, String> = linkedHashMapOf() operator fun set(platform: String, id: String) { map[platform] = id } operator fun get(platform: String) = map[platform] ?: error("Id not set for platform '$platform'") override fun toString(): String = "${this::class.simpleName}($map)" } fun ServiceBaseId.platform(platform: String) = this[platform] fun ServiceBaseId.android() = platform("android") fun ServiceBaseId.ios() = platform("ios") fun <T : ServiceBaseId> T.platform(platform: String, id: String): T = this.apply { this[platform] = id } fun <T : ServiceBaseId> T.android(id: String): T = platform("android", id) fun <T : ServiceBaseId> T.ios(id: String): T = platform("ios", id)
apache-2.0
fc3e233c034270cbceaaab44b756597d
44.944444
104
0.709794
3.725225
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/tiled/TiledMapWriter.kt
1
12926
package com.soywiz.korge.tiled import com.soywiz.kmem.* import com.soywiz.korge.tiled.TiledMap.* import com.soywiz.korim.color.* import com.soywiz.korio.file.* import com.soywiz.korio.lang.* import com.soywiz.korio.serialization.xml.* import com.soywiz.korio.util.* import com.soywiz.korma.geom.* suspend fun VfsFile.writeTiledMap(map: TiledMap) { writeString(map.toXml().toString()) } fun TiledMap.toXml(): Xml { val map = this val mapData = map.data return buildXml( "map", "version" to 1.2, "tiledversion" to "1.3.1", "orientation" to mapData.orientation.value, "renderorder" to mapData.renderOrder.value, "compressionlevel" to mapData.compressionLevel, "width" to mapData.width, "height" to mapData.height, "tilewidth" to mapData.tilewidth, "tileheight" to mapData.tileheight, "hexsidelength" to mapData.hexSideLength, "staggeraxis" to mapData.staggerAxis, "staggerindex" to mapData.staggerIndex, "backgroundcolor" to mapData.backgroundColor?.toStringARGB(), "infinite" to mapData.infinite.toInt(), "nextlayerid" to mapData.nextLayerId, "nextobjectid" to mapData.nextObjectId ) { propertiesToXml(mapData.properties) for (tileset in map.tilesets) { val tilesetData = tileset.data if (tilesetData.tilesetSource != null) { node("tileset", "firstgid" to tilesetData.firstgid, "source" to tilesetData.tilesetSource) } else { node(tilesetData.toXml()) } } for (layer in map.allLayers) { when (layer) { is Layer.Tiles -> tileLayerToXml( layer, mapData.infinite, mapData.editorSettings?.chunkWidth ?: 16, mapData.editorSettings?.chunkHeight ?: 16 ) is Layer.Objects -> objectLayerToXml(layer) is Layer.Image -> imageLayerToXml(layer) is Layer.Group -> groupLayerToXml( layer, mapData.infinite, mapData.editorSettings?.chunkWidth ?: 16, mapData.editorSettings?.chunkHeight ?: 16 ) } } val editorSettings = mapData.editorSettings if (editorSettings != null && (editorSettings.chunkWidth != 16 || editorSettings.chunkHeight != 16)) { node("editorsettings") { node( "chunksize", "width" to editorSettings.chunkWidth, "height" to editorSettings.chunkHeight ) } } } } private fun TileSetData.toXml(): Xml { return buildXml( "tileset", "firstgid" to firstgid, "name" to name, "tilewidth" to tileWidth, "tileheight" to tileHeight, "spacing" to spacing.takeIf { it > 0 }, "margin" to margin.takeIf { it > 0 }, "tilecount" to tileCount, "columns" to columns, "objectalignment" to objectAlignment.takeIf { it != ObjectAlignment.UNSPECIFIED }?.value ) { imageToXml(image) if (tileOffsetX != 0 || tileOffsetY != 0) { node("tileoffset", "x" to tileOffsetX, "y" to tileOffsetY) } grid?.let { grid -> node( "grid", "orientation" to grid.orientation.value, "width" to grid.cellWidth, "height" to grid.cellHeight ) } propertiesToXml(properties) if (terrains.isNotEmpty()) { node("terraintypes") { for (terrain in terrains) { node("terrain", "name" to terrain.name, "tile" to terrain.tile) { propertiesToXml(terrain.properties) } } } } if (tiles.isNotEmpty()) { for (tile in tiles) { node(tile.toXml()) } } if (wangsets.isNotEmpty()) { node("wangsets") { for (wangset in wangsets) node(wangset.toXml()) } } } } private fun WangSet.toXml(): Xml { return buildXml("wangset", "name" to name, "tile" to tileId) { propertiesToXml(properties) if (cornerColors.isNotEmpty()) { for (color in cornerColors) { node( "wangcornercolor", "name" to color.name, "color" to color.color, "tile" to color.tileId, "probability" to color.probability.takeIf { it != 0.0 }?.niceStr ) } } if (edgeColors.isNotEmpty()) { for (color in edgeColors) { node( "wangedgecolor", "name" to color.name, "color" to color.color.toStringARGB(), "tile" to color.tileId, "probability" to color.probability.takeIf { it != 0.0 }?.niceStr ) } } if (wangtiles.isNotEmpty()) { for (wangtile in wangtiles) { node( "wangtile", "tileid" to wangtile.tileId, "wangid" to wangtile.wangId.toUInt().toString(16).toUpperCase(), "hflip" to wangtile.hflip.takeIf { it }, "vflip" to wangtile.vflip.takeIf { it }, "dflip" to wangtile.dflip.takeIf { it } ) } } } } private fun TileData.toXml(): Xml { return buildXml("tile", "id" to id, "type" to type, "terrain" to terrain?.joinToString(",") { it?.toString() ?: "" }, "probability" to probability.takeIf { it != 0.0 }?.niceStr ) { propertiesToXml(properties) imageToXml(image) objectLayerToXml(objectGroup) if (frames != null && frames.isNotEmpty()) { node("animation") { for (frame in frames) { node("frame", "tileid" to frame.tileId, "duration" to frame.duration) } } } } } private class Chunk(val x: Int, val y: Int, val ids: IntArray) private fun XmlBuilder.tileLayerToXml( layer: Layer.Tiles, infinite: Boolean, chunkWidth: Int, chunkHeight: Int ) { node( "layer", "id" to layer.id, "name" to layer.name.takeIf { it.isNotEmpty() }, "width" to layer.width, "height" to layer.height, "opacity" to layer.opacity.takeIf { it != 1.0 }, "visible" to layer.visible.toInt().takeIf { it != 1 }, "locked" to layer.locked.toInt().takeIf { it != 0 }, "tintcolor" to layer.tintColor, "offsetx" to layer.offsetx.takeIf { it != 0.0 }, "offsety" to layer.offsety.takeIf { it != 0.0 } ) { propertiesToXml(layer.properties) node("data", "encoding" to layer.encoding.value, "compression" to layer.compression.value) { if (infinite) { val chunks = divideIntoChunks(layer.map.data.ints, chunkWidth, chunkHeight, layer.width) chunks.forEach { chunk -> node( "chunk", "x" to chunk.x, "y" to chunk.y, "width" to chunkWidth, "height" to chunkHeight ) { when (layer.encoding) { Encoding.XML -> { chunk.ids.forEach { gid -> node("tile", "gid" to gid.toUInt().takeIf { it != 0u }) } } Encoding.CSV -> { text(buildString(chunkWidth * chunkHeight * 4) { append("\n") for (y in 0 until chunkHeight) { for (x in 0 until chunkWidth) { append(chunk.ids[x + y * chunkWidth].toUInt()) if (y != chunkHeight - 1 || x != chunkWidth - 1) append(',') } append("\n") } }) } Encoding.BASE64 -> { //TODO: convert int array of gids into compressed string } } } } } else { when (layer.encoding) { Encoding.XML -> { layer.map.data.ints.forEach { gid -> node("tile", "gid" to gid.toUInt().takeIf { it != 0u }) } } Encoding.CSV -> { text(buildString(layer.area * 4) { append("\n") for (y in 0 until layer.height) { for (x in 0 until layer.width) { append(layer.map[x, y].value.toUInt()) if (y != layer.height - 1 || x != layer.width - 1) append(',') } append("\n") } }) } Encoding.BASE64 -> { //TODO: convert int array of gids into compressed string } } } } } } private fun divideIntoChunks(array: IntArray, width: Int, height: Int, totalWidth: Int): Array<Chunk> { val columns = totalWidth / width val rows = array.size / columns return Array(rows * columns) { i -> val cx = i % rows val cy = i / rows Chunk(cx * width, cy * height, IntArray(width * height) { j -> val tx = j % width val ty = j / width array[(cx * width + tx) + (cy * height + ty) * totalWidth] }) } } private fun XmlBuilder.objectLayerToXml(layer: Layer.Objects?) { if (layer == null) return node( "objectgroup", "draworder" to layer.drawOrder.value, "id" to layer.id, "name" to layer.name.takeIf { it.isNotEmpty() }, "color" to layer.color.toStringARGB().takeIf { it != "#a0a0a4" }, "opacity" to layer.opacity.takeIf { it != 1.0 }, "visible" to layer.visible.toInt().takeIf { it != 1 }, "locked" to layer.locked.toInt().takeIf { it != 0 }, "tintcolor" to layer.tintColor, "offsetx" to layer.offsetx.takeIf { it != 0.0 }, "offsety" to layer.offsety.takeIf { it != 0.0 } ) { propertiesToXml(layer.properties) layer.objects.forEach { obj -> node( "object", "id" to obj.id, "gid" to obj.gid, "name" to obj.name.takeIf { it.isNotEmpty() }, "type" to obj.type.takeIf { it.isNotEmpty() }, "x" to obj.bounds.x.takeIf { it != 0.0 }, "y" to obj.bounds.y.takeIf { it != 0.0 }, "width" to obj.bounds.width.takeIf { it != 0.0 }, "height" to obj.bounds.height.takeIf { it != 0.0 }, "rotation" to obj.rotation.takeIf { it != 0.0 }, "visible" to obj.visible.toInt().takeIf { it != 1 } //TODO: support object template //"template" to obj.template ) { propertiesToXml(obj.properties) fun List<Point>.toXml() = joinToString(" ") { p -> "${p.x.niceStr},${p.y.niceStr}" } when (val type = obj.objectShape) { is Object.Shape.Rectangle -> Unit is Object.Shape.Ellipse -> node("ellipse") is Object.Shape.PPoint -> node("point") is Object.Shape.Polygon -> node("polygon", "points" to type.points.toXml()) is Object.Shape.Polyline -> node("polyline", "points" to type.points.toXml()) is Object.Shape.Text -> node( "text", "fontfamily" to type.fontFamily, "pixelsize" to type.pixelSize.takeIf { it != 16 }, "wrap" to type.wordWrap.toInt().takeIf { it != 0 }, "color" to type.color.toStringARGB(), "bold" to type.bold.toInt().takeIf { it != 0 }, "italic" to type.italic.toInt().takeIf { it != 0 }, "underline" to type.underline.toInt().takeIf { it != 0 }, "strikeout" to type.strikeout.toInt().takeIf { it != 0 }, "kerning" to type.kerning.toInt().takeIf { it != 1 }, "halign" to type.hAlign.value, "valign" to type.vAlign.value ) } } } } } private fun XmlBuilder.imageLayerToXml(layer: Layer.Image) { node( "imagelayer", "id" to layer.id, "name" to layer.name.takeIf { it.isNotEmpty() }, "opacity" to layer.opacity.takeIf { it != 1.0 }, "visible" to layer.visible.toInt().takeIf { it != 1 }, "locked" to layer.locked.toInt().takeIf { it != 0 }, "tintcolor" to layer.tintColor, "offsetx" to layer.offsetx.takeIf { it != 0.0 }, "offsety" to layer.offsety.takeIf { it != 0.0 } ) { propertiesToXml(layer.properties) imageToXml(layer.image) } } private fun XmlBuilder.groupLayerToXml(layer: Layer.Group, infinite: Boolean, chunkWidth: Int, chunkHeight: Int) { node( "group", "id" to layer.id, "name" to layer.name.takeIf { it.isNotEmpty() }, "opacity" to layer.opacity.takeIf { it != 1.0 }, "visible" to layer.visible.toInt().takeIf { it != 1 }, "locked" to layer.locked.toInt().takeIf { it != 0 }, "tintcolor" to layer.tintColor, "offsetx" to layer.offsetx.takeIf { it != 0.0 }, "offsety" to layer.offsety.takeIf { it != 0.0 } ) { propertiesToXml(layer.properties) layer.layers.forEach { when (it) { is Layer.Tiles -> tileLayerToXml(it, infinite, chunkWidth, chunkHeight) is Layer.Objects -> objectLayerToXml(it) is Layer.Image -> imageLayerToXml(it) is Layer.Group -> groupLayerToXml(it, infinite, chunkWidth, chunkHeight) } } } } private fun XmlBuilder.imageToXml(image: Image?) { if (image == null) return node( "image", when (image) { is Image.Embedded -> "format" to image.format is Image.External -> "source" to image.source }, "width" to image.width, "height" to image.height, "transparent" to image.transparent ) { if (image is Image.Embedded) { node( "data", "encoding" to image.encoding.value, "compression" to image.compression.value ) { //TODO: encode and compress image text(image.toString()) } } } } private fun XmlBuilder.propertiesToXml(properties: Map<String, Property>) { if (properties.isEmpty()) return fun property(name: String, type: String, value: Any) = node("property", "name" to name, "type" to type, "value" to value) node("properties") { properties.forEach { (name, prop) -> when (prop) { is Property.StringT -> property(name, "string", prop.value) is Property.IntT -> property(name, "int", prop.value) is Property.FloatT -> property(name, "float", prop.value) is Property.BoolT -> property(name, "bool", prop.value.toString()) is Property.ColorT -> property(name, "color", prop.value.toStringARGB()) is Property.FileT -> property(name, "file", prop.path) is Property.ObjectT -> property(name, "object", prop.id) } } } } //TODO: move to korim private fun RGBA.toStringARGB(): String { if (a == 0xFF) { return "#%02x%02x%02x".format(r, g, b) } else { return "#%02x%02x%02x%02x".format(a, r, g, b) } }
apache-2.0
b80875ccea23505a127ced34e34ec1a1
28.310658
114
0.626025
3.117704
false
false
false
false
samtstern/quickstart-android
firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/RestaurantDetailActivity.kt
1
7805
package com.google.firebase.example.fireeats.kotlin import android.content.Context import android.os.Bundle import android.util.Log import android.view.View import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.google.android.gms.tasks.Task import com.google.android.material.snackbar.Snackbar import com.google.firebase.example.fireeats.R import com.google.firebase.example.fireeats.databinding.ActivityRestaurantDetailBinding import com.google.firebase.example.fireeats.kotlin.adapter.RatingAdapter import com.google.firebase.example.fireeats.kotlin.model.Rating import com.google.firebase.example.fireeats.kotlin.model.Restaurant import com.google.firebase.example.fireeats.kotlin.util.RestaurantUtil import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.EventListener import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.Query import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.ktx.toObject import com.google.firebase.ktx.Firebase class RestaurantDetailActivity : AppCompatActivity(), EventListener<DocumentSnapshot>, RatingDialogFragment.RatingListener { private var ratingDialog: RatingDialogFragment? = null private lateinit var binding: ActivityRestaurantDetailBinding private lateinit var firestore: FirebaseFirestore private lateinit var restaurantRef: DocumentReference private lateinit var ratingAdapter: RatingAdapter private var restaurantRegistration: ListenerRegistration? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRestaurantDetailBinding.inflate(layoutInflater) setContentView(binding.root) // Get restaurant ID from extras val restaurantId = intent.extras?.getString(KEY_RESTAURANT_ID) ?: throw IllegalArgumentException("Must pass extra $KEY_RESTAURANT_ID") // Initialize Firestore firestore = Firebase.firestore // Get reference to the restaurant restaurantRef = firestore.collection("restaurants").document(restaurantId) // Get ratings val ratingsQuery = restaurantRef .collection("ratings") .orderBy("timestamp", Query.Direction.DESCENDING) .limit(50) // RecyclerView ratingAdapter = object : RatingAdapter(ratingsQuery) { override fun onDataChanged() { if (itemCount == 0) { binding.recyclerRatings.visibility = View.GONE binding.viewEmptyRatings.visibility = View.VISIBLE } else { binding.recyclerRatings.visibility = View.VISIBLE binding.viewEmptyRatings.visibility = View.GONE } } } binding.recyclerRatings.layoutManager = LinearLayoutManager(this) binding.recyclerRatings.adapter = ratingAdapter ratingDialog = RatingDialogFragment() binding.restaurantButtonBack.setOnClickListener { onBackArrowClicked() } binding.fabShowRatingDialog.setOnClickListener { onAddRatingClicked() } } public override fun onStart() { super.onStart() ratingAdapter.startListening() restaurantRegistration = restaurantRef.addSnapshotListener(this) } public override fun onStop() { super.onStop() ratingAdapter.stopListening() restaurantRegistration?.remove() restaurantRegistration = null } override fun finish() { super.finish() overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right) } /** * Listener for the Restaurant document ([.restaurantRef]). */ override fun onEvent(snapshot: DocumentSnapshot?, e: FirebaseFirestoreException?) { if (e != null) { Log.w(TAG, "restaurant:onEvent", e) return } snapshot?.let { val restaurant = snapshot.toObject<Restaurant>() if (restaurant != null) { onRestaurantLoaded(restaurant) } } } private fun onRestaurantLoaded(restaurant: Restaurant) { binding.restaurantName.text = restaurant.name binding.restaurantRating.rating = restaurant.avgRating.toFloat() binding.restaurantNumRatings.text = getString(R.string.fmt_num_ratings, restaurant.numRatings) binding.restaurantCity.text = restaurant.city binding.restaurantCategory.text = restaurant.category binding.restaurantPrice.text = RestaurantUtil.getPriceString(restaurant) // Background image Glide.with(binding.restaurantImage.context) .load(restaurant.photo) .into(binding.restaurantImage) } private fun onBackArrowClicked() { onBackPressed() } private fun onAddRatingClicked() { ratingDialog?.show(supportFragmentManager, RatingDialogFragment.TAG) } override fun onRating(rating: Rating) { // In a transaction, add the new rating and update the aggregate totals addRating(restaurantRef, rating) .addOnSuccessListener(this) { Log.d(TAG, "Rating added") // Hide keyboard and scroll to top hideKeyboard() binding.recyclerRatings.smoothScrollToPosition(0) } .addOnFailureListener(this) { e -> Log.w(TAG, "Add rating failed", e) // Show failure message and hide keyboard hideKeyboard() Snackbar.make(findViewById(android.R.id.content), "Failed to add rating", Snackbar.LENGTH_SHORT).show() } } private fun addRating(restaurantRef: DocumentReference, rating: Rating): Task<Void> { // Create reference for new rating, for use inside the transaction val ratingRef = restaurantRef.collection("ratings").document() // In a transaction, add the new rating and update the aggregate totals return firestore.runTransaction { transaction -> val restaurant = transaction.get(restaurantRef).toObject<Restaurant>() if (restaurant == null) { throw Exception("Resraurant not found at ${restaurantRef.path}") } // Compute new number of ratings val newNumRatings = restaurant.numRatings + 1 // Compute new average rating val oldRatingTotal = restaurant.avgRating * restaurant.numRatings val newAvgRating = (oldRatingTotal + rating.rating) / newNumRatings // Set new restaurant info restaurant.numRatings = newNumRatings restaurant.avgRating = newAvgRating // Commit to Firestore transaction.set(restaurantRef, restaurant) transaction.set(ratingRef, rating) null } } private fun hideKeyboard() { val view = currentFocus if (view != null) { (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(view.windowToken, 0) } } companion object { private const val TAG = "RestaurantDetail" const val KEY_RESTAURANT_ID = "key_restaurant_id" } }
apache-2.0
2545d2841d59208d9a52e53f0223c3d0
36.344498
102
0.670852
5.266532
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/LaundrySettingsFragment.kt
1
6292
package com.pennapps.labs.pennmobile import android.content.Context import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.view.* import android.widget.Button import android.widget.RelativeLayout import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import com.google.firebase.analytics.FirebaseAnalytics import com.pennapps.labs.pennmobile.adapters.LaundrySettingsAdapter import com.pennapps.labs.pennmobile.api.StudentLife import com.pennapps.labs.pennmobile.classes.LaundryRoomSimple import kotlinx.android.synthetic.main.fragment_laundry_settings.* import kotlinx.android.synthetic.main.fragment_laundry_settings.view.* import kotlinx.android.synthetic.main.include_main.* import kotlinx.android.synthetic.main.loading_panel.* import kotlinx.android.synthetic.main.no_results.* import java.util.ArrayList import java.util.HashMap class LaundrySettingsFragment : Fragment() { private lateinit var mActivity: MainActivity private lateinit var mStudentLife: StudentLife private lateinit var mContext: Context internal var mHelpLayout: RelativeLayout? = null private var sp: SharedPreferences? = null private var mButton: Button? = null private var numRooms: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mStudentLife = MainActivity.studentLifeInstance mActivity = activity as MainActivity mContext = mActivity mActivity.closeKeyboard() setHasOptionsMenu(true) mActivity.toolbar.visibility = View.VISIBLE mActivity.expandable_bottom_bar.visibility = View.GONE val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "12") bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Laundry Settings") bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "App Feature") FirebaseAnalytics.getInstance(mContext).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_laundry_settings, container, false) // set up shared preferences sp = PreferenceManager.getDefaultSharedPreferences(mContext) // reset laundry rooms button mButton = view.laundry_room_reset mButton?.setOnClickListener { // remove shared preferences val editor = sp?.edit() editor?.putInt(getString(R.string.num_rooms_selected_pref), 0) editor?.apply() for (i in 0 until numRooms) { editor?.remove(Integer.toString(i))?.apply() } //view.laundry_building_expandable_list?.setAdapter(mAdapter) } // set up back button mActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true) getHalls() return view } private fun getHalls() { mStudentLife.laundryRooms() .subscribe({ rooms -> mActivity.runOnUiThread { numRooms = rooms.size // save number of rooms val editor = sp?.edit() editor?.putInt(getString(R.string.num_rooms_pref), numRooms) editor?.apply() val hashMap = HashMap<String, List<LaundryRoomSimple>>() val hallList = ArrayList<String>() var i = 0 // go through all the rooms while (i < numRooms) { // new list for the rooms in the hall var roomList: MutableList<LaundryRoomSimple> = ArrayList() // if hall name already exists, get the list of rooms and add to that var hallName = rooms[i].location ?: "" if (hallList.contains(hallName)) { roomList = hashMap[hallName] as MutableList<LaundryRoomSimple> hashMap.remove(hallName) hallList.remove(hallName) } while (hallName == rooms[i].location) { roomList.add(rooms[i]) i += 1 if (i >= rooms.size) { break } } // name formatting for consistency if (hallName == "Lauder College House") { hallName = "Lauder" } // add the hall name to the list hallList.add(hallName) hashMap[hallName] = roomList } val mAdapter = LaundrySettingsAdapter(mContext, hashMap, hallList) laundry_building_expandable_list?.setAdapter(mAdapter) loadingPanel?.visibility = View.GONE no_results?.visibility = View.GONE } }, { mActivity.runOnUiThread { loadingPanel?.visibility = View.GONE no_results?.visibility = View.VISIBLE mHelpLayout?.visibility = View.GONE } }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { mActivity.toolbar.visibility = View.GONE mActivity.onBackPressed() return true } override fun onResume() { super.onResume() mActivity.removeTabs() mActivity.setTitle(R.string.laundry) if (Build.VERSION.SDK_INT > 17){ mActivity.setSelectedTab(MainActivity.LAUNDRY) } } override fun onDestroyView() { mActivity.toolbar.visibility = View.GONE mActivity.supportActionBar?.setDisplayHomeAsUpEnabled(false) super.onDestroyView() } }
mit
02aab1fe0825e3aa6e56a2403081f4cb
37.371951
116
0.578036
5.563218
false
false
false
false
numa08/Gochisou
app/src/main/java/net/numa08/gochisou/presentation/widget/BottomBarBehavior.kt
1
1013
package net.numa08.gochisou.presentation.widget import android.content.Context import android.support.design.widget.AppBarLayout import android.support.design.widget.CoordinatorLayout import android.support.design.widget.TabLayout import android.support.v4.view.ViewCompat import android.util.AttributeSet import android.view.View @Suppress("unused") class BottomBarBehavior(context: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<TabLayout>(context, attrs) { var defaultDependencyTop = -1 override fun layoutDependsOn(parent: CoordinatorLayout?, child: TabLayout?, dependency: View?): Boolean = dependency is AppBarLayout override fun onDependentViewChanged(parent: CoordinatorLayout?, child: TabLayout?, dependency: View?): Boolean { if (defaultDependencyTop == -1) { defaultDependencyTop = dependency?.top ?: 0 } ViewCompat.setTranslationY(child, defaultDependencyTop.toFloat() - (dependency?.y ?: 0.0f)) return true } }
mit
866d4cd285104e910c07f23d11cfe2b3
36.555556
120
0.753208
4.689815
false
false
false
false
lasalazarr/fastdev
vertx-microservices-workshop/solution/compulsive-traders/src/main/kotlin/io/vertx/workshop/trader/impl/KotlinCompulsiveTraderVerticle.kt
2
1800
package io.vertx.workshop.trader.impl import io.vertx.core.CompositeFuture import io.vertx.core.Future import io.vertx.core.eventbus.MessageConsumer import io.vertx.core.json.JsonObject import io.vertx.servicediscovery.ServiceDiscovery import io.vertx.servicediscovery.types.EventBusService import io.vertx.servicediscovery.types.MessageSource import io.vertx.workshop.portfolio.PortfolioService class KotlinCompulsiveTraderVerticle : io.vertx.core.AbstractVerticle() { override fun start() { val company = TraderUtils.pickACompany() val numberOfShares = TraderUtils.pickANumber() System.out.println("Groovy compulsive trader configured for company $company and shares: $numberOfShares"); // We create the discovery service object. val discovery = ServiceDiscovery.create(vertx) val marketFuture: Future<MessageConsumer<JsonObject>> = Future.future() val portfolioFuture: Future<PortfolioService> = Future.future() MessageSource.getConsumer<JsonObject>(discovery, JsonObject().put("name", "market-data"), marketFuture) EventBusService.getProxy<PortfolioService>(discovery, PortfolioService::class.java, portfolioFuture) // When done (both services retrieved), execute the handler CompositeFuture.all(marketFuture, portfolioFuture).setHandler { ar -> if (ar.failed()) { System.err.println("One of the required service cannot be retrieved: ${ar.cause().message}"); } else { // Our services: val portfolio = portfolioFuture.result(); val marketConsumer = marketFuture.result(); // Listen the market... marketConsumer.handler { message -> val quote = message.body(); TraderUtils.dumbTradingLogic(company, numberOfShares, portfolio, quote) } } } } }
apache-2.0
69fb406bd2792b68c96e56e94331142a
38.130435
111
0.736111
4.316547
false
false
false
false
RomanBelkov/TrikKotlin
src/Buttons.kt
1
2447
import rx.Subscriber import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.* import java.util.concurrent.Semaphore import kotlin.concurrent.thread /** * Created by Roman Belkov on 14.10.15. */ class ButtonEvent(val button: ButtonEventCode, val isPressed: Boolean) { constructor(code: Int, isPressed: Boolean) : this( when(code) { 0 -> ButtonEventCode.Sync 1 -> ButtonEventCode.Escape 28 -> ButtonEventCode.Enter 116 -> ButtonEventCode.Power 103 -> ButtonEventCode.Up 105 -> ButtonEventCode.Left 106 -> ButtonEventCode.Right 108 -> ButtonEventCode.Down else -> throw Exception("Received unknown code") }, isPressed) fun asPair() = Pair(button, isPressed) override fun toString() = "${button.toString()} ${isPressed.toString()}" } class Buttons(deviceFilePath: String) : BinaryFifoSensor<ButtonEvent>(deviceFilePath, 16, 1024) { constructor() : this("/dev/input/event0") var clicksOnly = true override fun parse(bytes: ByteArray, offset: Int): Optional<ButtonEvent> { if (bytes.size < 16) return Optional.empty() val evType = intFromTwoBytes(bytes[offset + 9], bytes[offset + 8]) //println("evType: $evType ") val evCode = intFromTwoBytes(bytes[offset + 11], bytes[offset + 10]) //println("evCode: $evCode ") val evValue = ByteBuffer.wrap(bytes, offset + 12, 4).order(ByteOrder.LITTLE_ENDIAN).int when { evType == 1 && (evValue == 1 || !clicksOnly) -> return Optional.of(ButtonEvent(evCode, evValue == 1)) else -> return Optional.empty() } } // fun checkPressing(button: ButtonEventCode): Boolean { // var isPressed = false // //val semaphore = Semaphore(0) //TODO to monitor // // thread { // this.toObservable().subscribe(object : Subscriber<ButtonEvent>() { // override fun onNext(p0: ButtonEvent) { // if (p0.button == button) { // this.unsubscribe() // //semaphore.release() // } // } // // override fun onCompleted() = Unit // // override fun onError(p0: Throwable) = throw p0 // // }) // } // // return isPressed // } }
apache-2.0
001fb304a648e0a9ff479e3c2b7cddaf
31.210526
113
0.567225
4.263066
false
false
false
false
ejeinc/VR-MultiView-UDP
common-messaging/src/main/java/com/eje_c/multilink/data/Message.kt
1
686
package com.eje_c.multilink.data import com.eje_c.multilink.json.JSON /** * JSON object which is sent between VR devices and controller. * @param type Must be one of Message.TYPE_** values. * @param data Optional data. */ class Message(val type: Int, val data: Any? = null) { init { check(type == TYPE_PING || type == TYPE_CONTROL_MESSAGE) { "Illegal value for type: $type" } } /** * Convert to byte array for sending on network. */ fun serialize(): ByteArray { return JSON.stringify(this).toByteArray() } companion object { const val TYPE_PING = 0 const val TYPE_CONTROL_MESSAGE = 1 } }
apache-2.0
2ae77bcc30594f3bf1ae86f1f27b77ff
22.689655
66
0.609329
3.853933
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/StripeImageActivity.kt
1
3390
package com.stripe.example.activity import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.Column import androidx.compose.material.MaterialTheme import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.text.PlaceholderVerticalAlign import com.stripe.android.ui.core.R import com.stripe.android.uicore.image.StripeImageLoader import com.stripe.android.uicore.text.EmbeddableImage import com.stripe.android.uicore.text.Html class StripeImageActivity : AppCompatActivity() { private val LocalStripeImageLoader = staticCompositionLocalOf<StripeImageLoader> { error("No ImageLoader provided") } private val imageLoader by lazy { StripeImageLoader( context = this, memoryCache = null, diskCache = null ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CompositionLocalProvider(LocalStripeImageLoader provides imageLoader) { Column { Html( imageLoader = mapOf( "affirm" to EmbeddableImage.Drawable( R.drawable.stripe_ic_affirm_logo, R.string.stripe_paymentsheet_payment_method_affirm ) ), html = """ HTML with single local image <br/> Local image <img src="affirm"/>. <br/> """.trimIndent(), color = MaterialTheme.colors.onSurface, style = MaterialTheme.typography.body1 ) Html( imageLoader = mapOf( "affirm" to EmbeddableImage.Drawable( R.drawable.stripe_ic_affirm_logo, R.string.stripe_paymentsheet_payment_method_affirm ) ), html = """ HTML with local and remote images <br/> Local image <img src="affirm"/>. <br/> Unknown remote image <img src="https://qa-b.stripecdn.com/unknown_image.png"/> <br/> Remote images <img src="https://qa-b.stripecdn.com/payment-method-messaging-statics-srv/assets/afterpay_logo_black.png"/> <img src="https://qa-b.stripecdn.com/payment-method-messaging-statics-srv/assets/klarna_logo_black.png"/> <br/> Paragraph text <b>bold text</b>. ⓘ """.trimIndent(), color = MaterialTheme.colors.onSurface, style = MaterialTheme.typography.body1, imageAlign = PlaceholderVerticalAlign.TextCenter ) } } } } }
mit
5bbe470208dd8bb9650ae611c08a034f
42.435897
135
0.510626
5.80137
false
false
false
false
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/AppTheme.kt
1
10281
package org.softeg.slartus.forpdaplus import android.content.SharedPreferences import android.graphics.Color import android.os.Environment import org.softeg.slartus.forpdaplus.classes.common.ArrayUtils import org.softeg.slartus.forpdaplus.core.AppPreferences import java.io.File object AppTheme { private const val THEME_LIGHT = 0 private const val THEME_DARK = 1 private const val THEME_BLACK = 6 private const val THEME_MATERIAL_LIGHT = 2 private const val THEME_MATERIAL_DARK = 3 private const val THEME_MATERIAL_BLACK = 5 private const val THEME_LIGHT_OLD_HD = 4 private const val THEME_CUSTOM_CSS = 99 const val THEME_TYPE_LIGHT = 0 const val THEME_TYPE_DARK = 2 private const val THEME_TYPE_BLACK = 3 private val LIGHT_THEMES = arrayOf(THEME_LIGHT, THEME_LIGHT_OLD_HD, THEME_MATERIAL_LIGHT) private val DARK_THEMES = arrayOf(THEME_MATERIAL_DARK, THEME_DARK) @JvmStatic val webViewFont: String? get() = preferences.getString("webViewFontName", "") @JvmStatic fun getColorAccent(type: String?): Int { var color = 0 when (type) { "Accent" -> color = preferences.getInt("accentColor", Color.rgb(2, 119, 189)) "Pressed" -> color = preferences.getInt("accentColorPressed", Color.rgb(0, 89, 159)) } return color } @JvmStatic val mainAccentColor: Int get() { var color = R.color.accentPink when (preferences.getString("mainAccentColor", "pink")) { AppPreferences.ACCENT_COLOR_PINK_NAME -> color = R.color.accentPink AppPreferences.ACCENT_COLOR_BLUE_NAME -> color = R.color.accentBlue AppPreferences.ACCENT_COLOR_GRAY_NAME -> color = R.color.accentGray } return color } @JvmStatic val themeStyleResID: Int get() { var theme = R.style.ThemeLight val color = preferences.getString("mainAccentColor", "pink") when (themeType) { THEME_TYPE_LIGHT -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.MainPinkLight AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.MainBlueLight AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.MainGrayLight } } THEME_TYPE_DARK -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.MainPinkDark AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.MainBlueDark AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.MainGrayDark } } else -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.MainPinkBlack AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.MainBlueBlack AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.MainGrayBlack } } } return theme } @JvmStatic val prefsThemeStyleResID: Int get() { var theme = R.style.ThemePrefsLightPink val color = preferences.getString("mainAccentColor", "pink") when (themeType) { THEME_TYPE_LIGHT -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.ThemePrefsLightPink AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.ThemePrefsLightBlue AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.ThemePrefsLightGray } } THEME_TYPE_DARK -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.ThemePrefsDarkPink AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.ThemePrefsDarkBlue AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.ThemePrefsDarkGray } } else -> { when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> theme = R.style.ThemePrefsBlackPink AppPreferences.ACCENT_COLOR_BLUE_NAME -> theme = R.style.ThemePrefsBlackBlue AppPreferences.ACCENT_COLOR_GRAY_NAME -> theme = R.style.ThemePrefsBlackGray } } } return theme } @JvmStatic val themeType: Int get() { var themeType = THEME_TYPE_LIGHT val themeStr = currentTheme if (themeStr.length < 3) { val theme = themeStr.toInt() themeType = if (ArrayUtils.indexOf(theme, LIGHT_THEMES) != -1) THEME_TYPE_LIGHT else if (ArrayUtils.indexOf(theme, DARK_THEMES) != -1) THEME_TYPE_DARK else THEME_TYPE_BLACK } else { if (themeStr.contains("/dark/")) themeType = THEME_TYPE_DARK else if (themeStr.contains("/black/")) themeType = THEME_TYPE_BLACK } return themeType } @JvmStatic val themeBackgroundColorRes: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) R.color.app_background_light else if (themeType == THEME_TYPE_DARK) R.color.app_background_dark else R.color.app_background_black } @JvmStatic val themeTextColorRes: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) android.R.color.black else if (themeType == THEME_TYPE_DARK) android.R.color.white else android.R.color.white } @JvmStatic val swipeRefreshBackground: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) R.color.swipe_background_light else if (themeType == THEME_TYPE_DARK) R.color.swipe_background_dark else R.color.swipe_background_black } @JvmStatic val navBarColor: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) R.color.navBar_light else if (themeType == THEME_TYPE_DARK) R.color.navBar_dark else R.color.navBar_black } @JvmStatic val drawerMenuText: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) R.color.drawer_menu_text_light else if (themeType == THEME_TYPE_DARK) R.color.drawer_menu_text_dark else R.color.drawer_menu_text_dark } @JvmStatic val themeStyleWebViewBackground: Int get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) Color.parseColor("#eeeeee") else if (themeType == THEME_TYPE_DARK) Color.parseColor("#1a1a1a") else Color.parseColor("#000000") } @JvmStatic val currentBackgroundColorHtml: String get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) "#eeeeee" else if (themeType == THEME_TYPE_DARK) "#1a1a1a" else "#000000" } @JvmStatic val currentTheme: String get() = preferences.getString("appstyle", THEME_LIGHT.toString())?:THEME_LIGHT.toString() @JvmStatic val currentThemeName: String get() { val themeType = themeType return if (themeType == THEME_TYPE_LIGHT) "white" else if (themeType == THEME_TYPE_DARK) "dark" else "black" } private fun checkThemeFile(themePath: String): String { return try { if (!File(themePath).exists()) { // Toast.makeText(INSTANCE,"не найден файл темы: "+themePath,Toast.LENGTH_LONG).show(); defaultCssTheme() } else themePath } catch (ex: Throwable) { defaultCssTheme() } } private fun defaultCssTheme(): String { return "/android_asset/forum/css/4pda_light_blue.css" } @JvmStatic val themeCssFileName: String get() { val themeStr = currentTheme return getThemeCssFileName(themeStr) } @JvmStatic fun getThemeCssFileName(themeStr: String): String { if (themeStr.length > 3) return checkThemeFile(themeStr) val path = "/android_asset/forum/css/" var cssFile = "4pda_light_blue.css" val theme = themeStr.toInt() if (theme == -1) return themeStr val color = preferences.getString("mainAccentColor", "pink") when (theme) { THEME_LIGHT -> when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> cssFile = "4pda_light_blue.css" AppPreferences.ACCENT_COLOR_BLUE_NAME -> cssFile = "4pda_light_pink.css" AppPreferences.ACCENT_COLOR_GRAY_NAME -> cssFile = "4pda_light_gray.css" } THEME_DARK -> when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> cssFile = "4pda_dark_blue.css" AppPreferences.ACCENT_COLOR_BLUE_NAME -> cssFile = "4pda_dark_pink.css" AppPreferences.ACCENT_COLOR_GRAY_NAME -> cssFile = "4pda_dark_gray.css" } THEME_BLACK -> when (color) { AppPreferences.ACCENT_COLOR_PINK_NAME -> cssFile = "4pda_black_blue.css" AppPreferences.ACCENT_COLOR_BLUE_NAME -> cssFile = "4pda_black_pink.css" AppPreferences.ACCENT_COLOR_GRAY_NAME -> cssFile = "4pda_black_gray.css" } THEME_MATERIAL_LIGHT -> cssFile = "material_light.css" THEME_MATERIAL_DARK -> cssFile = "material_dark.css" THEME_MATERIAL_BLACK -> cssFile = "material_black.css" THEME_LIGHT_OLD_HD -> cssFile = "standart_4PDA.css" THEME_CUSTOM_CSS -> return Environment.getExternalStorageDirectory().path + "/style.css" } return path + cssFile } private val preferences: SharedPreferences get() = App.getInstance().preferences }
apache-2.0
dcbe3ce58bd44b9e95d17349a0a48399
41.775
189
0.585485
4.476668
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/actions/runAnything/wasmpack/RunAnythingWasmPackItem.kt
3
2394
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.actions.runAnything.wasmpack import org.rust.ide.actions.runAnything.RsRunAnythingItem import javax.swing.Icon class RunAnythingWasmPackItem(command: String, icon: Icon) : RsRunAnythingItem(command, icon) { override val helpCommand: String = "wasm-pack" override val commandDescriptions: Map<String, String> = hashMapOf( "new" to "Create a new RustWasm project", "build" to "Build and pack the project into pkg directory", "test" to "Run tests using the wasm-bindgen test runner", "pack" to "(npm) Create a tarball from pkg directory", "publish" to "(npm) Create a tarball and publish to the NPM registry" ) override fun getOptionsDescriptionsForCommand(commandName: String): Map<String, String>? = when (commandName) { "build" -> buildOptionsDescriptions "test" -> testOptionsDescriptions "publish" -> publishOptionsDescriptions else -> null } companion object { private val buildOptionsDescriptions: Map<String, String> = hashMapOf( "--target" to "Output target environment: bundler (default), nodejs, web, no-modules", "--dev" to "Development profile: debug info, no optimizations", "--profiling" to "Profiling profile: optimizations and debug info", "--release" to "Release profile: optimizations, no debug info", "--out-dir" to "Output directory", "--out-name" to "Generated file names", "--scope" to "The npm scope to use" ) private val testOptionsDescriptions: Map<String, String> = hashMapOf( "--release" to "Build with release profile", "--headless" to "Test in headless browser mode", "--node" to "Run the tests in Node.js", "--firefox" to "Run the tests in Firefox", "--chrome" to "Run the tests in Chrome", "--safari" to "Run the tests in Safari" ) private val publishOptionsDescriptions: Map<String, String> = hashMapOf( "--tag" to "NPM tag to publish with" ) } }
mit
e2ea8b3a92d92a03deccdab373a19260
39.576271
102
0.593985
4.721893
false
true
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/commands/model/CommandAssistResponse.kt
1
1062
package com.github.jk1.ytplugin.commands.model import com.google.gson.JsonElement import com.google.gson.JsonParser import java.io.InputStream import java.io.InputStreamReader /** * Main wrapper around youtrack command assist response response. It delegates further parsing * to CommandHighlightRange, CommandSuggestion and CommandPreview classes */ class CommandAssistResponse(element: JsonElement) { val highlightRanges: List<CommandHighlightRange> val suggestions: List<CommandSuggestion> val previews: List<CommandPreview> val timestamp = System.currentTimeMillis() init { val root = element.asJsonObject val ranges = root.asJsonObject.getAsJsonArray("styleRanges") val suggests = root.asJsonObject.getAsJsonArray("suggestions") val commands = root.asJsonObject.getAsJsonArray("commands") highlightRanges = ranges.map { CommandHighlightRange(it) } suggestions = suggests.map { CommandSuggestion(it) } previews = commands.map { CommandPreview(it) } } }
apache-2.0
8dcbeb7fe8e0c250a124e12cb33a1458
34.433333
94
0.73823
4.827273
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/lang/core/completion/RsCompletionFilteringTest.kt
2
9735
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import org.rust.ProjectDescriptor import org.rust.WithStdlibRustProjectDescriptor class RsCompletionFilteringTest: RsCompletionTestBase() { fun `test unsatisfied bound filtered 1`() = doSingleCompletion(""" trait Bound {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound> Trait1 for T {} impl<T> Trait2 for T {} struct S; fn main() { S./*caret*/ } """, """ trait Bound {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound> Trait1 for T {} impl<T> Trait2 for T {} struct S; fn main() { S.bar()/*caret*/ } """) fun `test unsatisfied bound filtered 2`() = doSingleCompletion(""" trait Bound1 {} trait Bound2 {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound1> Trait1 for T {} impl<T: Bound2> Trait2 for T {} struct S; impl Bound1 for S {} fn main() { S./*caret*/ } """, """ trait Bound1 {} trait Bound2 {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound1> Trait1 for T {} impl<T: Bound2> Trait2 for T {} struct S; impl Bound1 for S {} fn main() { S.foo()/*caret*/ } """) fun `test unsatisfied bound filtered 3`() = doSingleCompletion(""" trait Bound1 {} trait Bound2 {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound1> Trait1 for T {} impl<T: Bound2> Trait2 for T {} struct S; impl Bound1 for S {} fn foo(a: &S) { a./*caret*/ } """, """ trait Bound1 {} trait Bound2 {} trait Trait1 { fn foo(&self) {} } trait Trait2 { fn bar(&self) {} } impl<T: Bound1> Trait1 for T {} impl<T: Bound2> Trait2 for T {} struct S; impl Bound1 for S {} fn foo(a: &S) { a.foo()/*caret*/ } """) fun `test unsatisfied bound not filtered for unknown type`() = doSingleCompletion(""" trait Bound {} trait Trait { fn foo(&self) {} } impl<T: Bound> Trait for S1<T> {} struct S1<T>(T); fn main() { S1(SomeUnknownType).f/*caret*/ } """, """ trait Bound {} trait Trait { fn foo(&self) {} } impl<T: Bound> Trait for S1<T> {} struct S1<T>(T); fn main() { S1(SomeUnknownType).foo()/*caret*/ } """) fun `test unsatisfied bound not filtered for unconstrained type var`() = doSingleCompletion(""" trait Bound {} trait Trait { fn foo(&self) {} } impl<T: Bound> Trait for S1<T> {} struct S1<T>(T); fn ty_var<T>() -> T { unimplemented!() } fn main() { S1(ty_var()).f/*caret*/ } """, """ trait Bound {} trait Trait { fn foo(&self) {} } impl<T: Bound> Trait for S1<T> {} struct S1<T>(T); fn ty_var<T>() -> T { unimplemented!() } fn main() { S1(ty_var()).foo()/*caret*/ } """) fun `test unsatisfied bound path filtering`() = doSingleCompletion(""" trait Bound {} trait Trait1 { fn foo(){} } trait Trait2 { fn bar() {} } impl<T: Bound> Trait1 for T {} impl<T> Trait2 for T {} struct S; fn main() { S::/*caret*/ } """, """ trait Bound {} trait Trait1 { fn foo(){} } trait Trait2 { fn bar() {} } impl<T: Bound> Trait1 for T {} impl<T> Trait2 for T {} struct S; fn main() { S::bar()/*caret*/ } """) @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test method is not filtered by Sync+Send bounds`() = doSingleCompletion(""" struct S; trait Trait { fn foo(&self) {} } impl<T: Sync + Send> Trait for T {} fn main() { S.fo/*caret*/ } """, """ struct S; trait Trait { fn foo(&self) {} } impl<T: Sync + Send> Trait for T {} fn main() { S.foo()/*caret*/ } """) fun `test private function`() = checkNoCompletion(""" mod foo { fn bar() {} } fn main() { foo::ba/*caret*/ } """) fun `test private mod`() = checkNoCompletion(""" mod foo { mod bar {} } fn main() { foo::ba/*caret*/ } """) fun `test private enum`() = checkNoCompletion(""" mod foo { enum MyEnum {} } fn main() { foo::MyEn/*caret*/ } """) fun `test private method 1`() = checkNoCompletion(""" mod foo { pub struct S; impl S { fn bar(&self) {} } } fn main() { foo::S.b/*caret*/() } """) fun `test private method 2`() = checkNoCompletion(""" mod foo { pub struct S; impl S { fn bar(&self) {} } } fn main() { foo::S.b/*caret*/ } """) fun `test private field`() = checkNoCompletion(""" mod foo { pub struct S { field: i32 } } fn bar(s: S) { s.f/*caret*/ } """) fun `test public item reexported with restricted visibility 1`() = checkNoCompletion(""" pub mod inner1 { pub mod inner2 { pub fn foo() {} pub(in crate::inner1) use foo as bar; } } fn main() { crate::inner1::inner2::ba/*caret*/ } """) fun `test public item reexported with restricted visibility 2`() = checkContainsCompletion("bar2", """ pub mod inner1 { pub mod inner2 { pub fn bar1() {} pub(in crate::inner1) use bar1 as bar2; } fn main() { crate::inner1::inner2::ba/*caret*/ } } """) fun `test private reexport of public function`() = checkNoCompletion(""" mod mod1 { pub fn foo() {} } mod mod2 { use crate::mod1::foo as bar; } fn main() { mod2::b/*caret*/ } """) // there was error in new resolve when legacy textual macros are always completed fun `test no completion on empty mod 1`() = checkNoCompletion(""" macro_rules! empty { () => {}; } mod foo {} pub use foo::empt/*caret*/ """) @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test no completion on empty mod 2`() = checkNoCompletion(""" mod foo {} pub use foo::asser/*caret*/ """) // Issue https://github.com/intellij-rust/intellij-rust/issues/3694 fun `test issue 3694`() = doSingleCompletion(""" mod foo { pub struct S { field: i32 } fn bar(s: S) { s./*caret*/ } } """, """ mod foo { pub struct S { field: i32 } fn bar(s: S) { s.field/*caret*/ } } """) fun `test doc(hidden) item`() = checkNoCompletion(""" mod foo { #[doc(hidden)] pub struct MyStruct; } fn main() { foo::My/*caret*/ } """) fun `test doc(hidden) item from the same module isn't filtered`() = doSingleCompletion(""" #[doc(hidden)] struct MyStruct; fn main() { My/*caret*/ } """, """ #[doc(hidden)] struct MyStruct; fn main() { MyStruct/*caret*/ } """) fun `test derived method is not completed if the derived trait is not implemented to type argument`() = checkNoCompletion(""" #[lang = "clone"] pub trait Clone { fn clone(&self) -> Self; } struct X; // Not `Clone` #[derive(Clone)] struct S<T>(T); fn main() { S(X).cl/*caret*/; } """) fun `test derived method is not completed UFCS if the derived trait is not implemented to type argument`() = checkNoCompletion(""" #[lang = "clone"] pub trait Clone { fn clone(&self) -> Self; } struct X; // Not `Clone` #[derive(Clone)] struct S<T>(T); fn main() { <S<X>>::cl/*caret*/; } """) fun `test trait implementation on multiple dereference levels`() = doSingleCompletion(""" struct S; trait T { fn foo(&self); } impl T for S { fn foo(&self) {} } impl T for &S { fn foo(&self) {} } fn main(a: &S) { a.f/*caret*/ } """, """ struct S; trait T { fn foo(&self); } impl T for S { fn foo(&self) {} } impl T for &S { fn foo(&self) {} } fn main(a: &S) { a.foo()/*caret*/ } """) fun `test filter by a bound unsatisfied because of a negative impl`() = doSingleCompletion(""" auto trait Sync {} struct S<T> { value: T } impl<T: Sync> S<T> { fn foo1(&self) {} } impl<T> S<T> { fn foo2(&self) {} } struct S0; impl !Sync for S0 {} fn main1(v: S<S0>) { v.fo/*caret*/ } """, """ auto trait Sync {} struct S<T> { value: T } impl<T: Sync> S<T> { fn foo1(&self) {} } impl<T> S<T> { fn foo2(&self) {} } struct S0; impl !Sync for S0 {} fn main1(v: S<S0>) { v.foo2()/*caret*/ } """) }
mit
087651a3f8903365dfd111c75fd27914
27.548387
134
0.471495
4.016089
false
true
false
false
foreverigor/TumCampusApp
app/src/test/java/de/tum/in/tumcampusapp/activities/KinoActivityTest.kt
1
4126
package de.tum.`in`.tumcampusapp.activities import android.support.v4.view.ViewPager import android.view.View import de.tum.`in`.tumcampusapp.BuildConfig import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.TestApp import de.tum.`in`.tumcampusapp.component.ui.news.KinoViewModel import de.tum.`in`.tumcampusapp.component.ui.news.repository.KinoLocalRepository import de.tum.`in`.tumcampusapp.component.ui.news.repository.KinoRemoteRepository import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoActivity import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoAdapter import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoDao import de.tum.`in`.tumcampusapp.component.ui.tufilm.model.Kino import de.tum.`in`.tumcampusapp.database.TcaDb import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.disposables.CompositeDisposable import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.Schedulers import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @Ignore @RunWith(RobolectricTestRunner::class) @Config(constants = BuildConfig::class, application = TestApp::class) class KinoActivityTest { private var kinoActivity: KinoActivity? = null private lateinit var dao: KinoDao private lateinit var viewModel: KinoViewModel @Before fun setUp() { val db = TcaDb.getInstance(RuntimeEnvironment.application) KinoLocalRepository.db = db viewModel = KinoViewModel(KinoLocalRepository, KinoRemoteRepository, CompositeDisposable()) RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setSingleSchedulerHandler { Schedulers.trampoline() } RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() } dao = db.kinoDao() dao.flush() } @After fun tearDown() { TcaDb.getInstance(RuntimeEnvironment.application).close() RxJavaPlugins.reset() RxAndroidPlugins.reset() } /** * Default usage - there are some movies * Expected output: default Kino activity layout */ @Test fun mainComponentDisplayedTest() { dao.insert(Kino()) kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() assertThat(kinoActivity!!.findViewById<View>(R.id.drawer_layout).visibility).isEqualTo(View.VISIBLE) } /** * There are no movies to display * Expected output: no movies layout displayed */ @Test fun mainComponentNoMoviesDisplayedTest() { kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() //For some reason the ui needs a while until it's been updated. Thread.sleep(100) assertThat(kinoActivity!!.findViewById<View>(R.id.error_layout).visibility).isEqualTo(View.VISIBLE) } /** * There are movies available * Expected output: KinoAdapter is used for pager. */ @Test fun kinoAdapterUsedTest() { dao.insert(Kino()) kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() Thread.sleep(100) assertThat((kinoActivity!!.findViewById<View>(R.id.pager) as ViewPager).adapter!!.javaClass).isEqualTo(KinoAdapter::class.java) } /** * Since we have an immediate scheduler which runs on the same thread and thus can only execute actions sequentially, this will * make the test wait until any previous tasks (like the activity waiting for kinos) are done. */ private fun waitForUI(){ viewModel.getAllKinos().blockingFirst() } }
gpl-3.0
6bd69d349794e0a3f2a940d800cf709c
37.924528
135
0.73364
4.524123
false
true
false
false
Soya93/Extract-Refactoring
platform/built-in-server/src/org/jetbrains/builtInWebServer/SingleConnectionNetService.kt
5
2194
package org.jetbrains.builtInWebServer import com.intellij.execution.process.OSProcessHandler import com.intellij.openapi.project.Project import com.intellij.util.Consumer import com.intellij.util.net.loopbackSocketAddress import io.netty.bootstrap.Bootstrap import io.netty.channel.Channel import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.catchError import org.jetbrains.concurrency.resolvedPromise import org.jetbrains.io.* import java.util.concurrent.atomic.AtomicReference abstract class SingleConnectionNetService(project: Project) : NetService(project) { protected val processChannel = AtomicReference<Channel>() private @Volatile var port = -1 private @Volatile var bootstrap: Bootstrap? = null protected abstract fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>) override final fun connectToProcess(promise: AsyncPromise<OSProcessHandler>, port: Int, processHandler: OSProcessHandler, errorOutputConsumer: Consumer<String>) { val bootstrap = oioClientBootstrap() configureBootstrap(bootstrap, errorOutputConsumer) this.bootstrap = bootstrap this.port = port bootstrap.connect(loopbackSocketAddress(port), promise)?.let { promise.catchError { processChannel.set(it) addCloseListener(it) promise.setResult(processHandler) } } } protected fun connectAgain(): Promise<Channel> { val channel = processChannel.get() if (channel != null) { return resolvedPromise(channel) } val promise = AsyncPromise<Channel>() bootstrap!!.connect(loopbackSocketAddress(port), promise)?.let { promise.catchError { processChannel.set(it) addCloseListener(it) promise.setResult(it) } } return promise } private fun addCloseListener(it: Channel) { it.closeFuture().addChannelListener { val channel = it.channel() processChannel.compareAndSet(channel, null) channel.eventLoop().shutdownIfOio() } } override fun closeProcessConnections() { processChannel.getAndSet(null)?.let { it.closeAndShutdownEventLoop() } } }
apache-2.0
e11b09c01988669793fbd1afc8dbaf71
31.279412
164
0.749772
4.843267
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/typing/ElmBackspaceHandler.kt
1
2138
package org.elm.ide.typing import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.psi.PsiFile import org.elm.lang.core.psi.ElmFile import org.elm.lang.core.psi.elements.ElmStringConstantExpr // A BackspaceHandlerDelegate is called during character deletion. // We use this to delete triple quotes, since the QuoteHandler can only delete single characters. class ElmBackspaceHandler : BackspaceHandlerDelegate() { private var rangeMarker: RangeMarker? = null // Called when a character is about to be deleted. There's no return value, so you can't affect behavior // here. override fun beforeCharDeleted(c: Char, file: PsiFile, editor: Editor) { rangeMarker = null // If we didn't insert the matching quote, don't do anything if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE) return if (file !is ElmFile) return val offset = editor.caretModel.offset val psiElement = file.findElementAt(offset) ?: return // We need to save the element range now, because the PSI will be changed by the time charDeleted is // called val parent = psiElement.parent ?: return if (parent is ElmStringConstantExpr && parent.text == "\"\"\"\"\"\"" && editor.caretModel.offset == parent.textOffset + 3) { rangeMarker = editor.document.createRangeMarker(parent.textRange) } } // Called immediately after a character is deleted. If this returns true, no automatic quote or brace // deletion will happen. override fun charDeleted(c: Char, file: PsiFile, editor: Editor): Boolean { // The range marker is automatically adjusted with the deleted character, so we can just delete the // whole thing. rangeMarker?.let { editor.document.deleteString(it.startOffset, it.endOffset) rangeMarker = null return true } return false } }
mit
3507ff69e05cd8825ab2618615415a2d
40.921569
108
0.69551
4.826185
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/chat/prv/LocalMessage.kt
1
1147
package me.proxer.app.chat.prv import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import me.proxer.app.ui.view.bbcode.toSimpleBBTree import me.proxer.app.util.extension.toDate import me.proxer.library.entity.messenger.Message import me.proxer.library.enums.Device import me.proxer.library.enums.MessageAction import org.threeten.bp.Instant /** * @author Ruben Gees */ @Entity( tableName = "messages", foreignKeys = [ForeignKey( entity = LocalConference::class, parentColumns = ["id"], childColumns = ["conferenceId"] )], indices = [Index("conferenceId")] ) data class LocalMessage( @PrimaryKey(autoGenerate = true) val id: Long, val conferenceId: Long, val userId: String, val username: String, val message: String, val action: MessageAction, val date: Instant, val device: Device ) { @Transient val styledMessage = message.toSimpleBBTree() fun toNonLocalMessage() = Message( id.toString(), conferenceId.toString(), userId, username, message, action, date.toDate(), device ) }
gpl-3.0
52d9195b50209332ae5c496dbadd1cd0
25.674419
104
0.710549
4.067376
false
false
false
false
ImXico/punk
image/src/main/kotlin/cyberpunk/image/ImageManager.kt
2
2681
package cyberpunk.image import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.graphics.g2d.TextureRegion object ImageManager { /** * Key for the default [TextureAtlas]. * It's not unusual to use just one texture atlas. If that's the case, change this field to the desired name, * via [load], and [take] can be called without supplying an atlas key. */ @JvmStatic var DEFAULT_ATLAS_KEY: String? = null private set /** * Data structure that will hold all loaded [TextureAtlas]. * When [load] is called, all [TextureAtlas] will be stored here. */ private val atlases: MutableMap<String, TextureAtlas> = mutableMapOf() /** * Loads a [TextureAtlas] stored in the assets folder under [path] and stores it * into [atlases] with the given key. * @param key key that will identify this [TextureAtlas] in the [atlases] structure. * @param path path of the atlas, under the assets folder. * @param setAsDefault whether or not this [TextureAtlas] should be set as the [DEFAULT_ATLAS_KEY]. */ @JvmStatic @JvmOverloads fun load(key: String, path: String, setAsDefault: Boolean = false) { val atlas = TextureAtlas(Gdx.files.internal(path)) atlases[key] = atlas if (setAsDefault) { DEFAULT_ATLAS_KEY = key } } /** * Returns the [TextureAtlas] identified by the given key. * @param key key that identifies the [TextureAtlas] in the [atlases] structure. * @return the correct [TextureAtlas] or null, in case of failure. */ @JvmStatic fun getAtlas(key: String): TextureAtlas? = atlases[key] /** * Disposes the given [TextureAtlas]. If none matches the supplied [key], this * action has no effect at all. * This releases all the textures backing all [TextureRegion] and sprites, * which should no longer be used after calling this method. * @param key key that identifies the [TextureAtlas] in the [atlases] structure. */ @JvmStatic fun disposeAtlas(key: String) = atlases[key]?.dispose() /** * Fetches a [TextureRegion] identified by the given [region] name from a [TextureAtlas] * identified by the given [key]. * If no atlas key is supplied, then [DEFAULT_ATLAS_KEY] will be used - which can be null! * @param region region that identifies the [TextureRegion] wanted. * @param key key that identifies the [TextureAtlas] in the [atlases] structure. * @return the [TextureRegion] wanted, or null, in case it was not found. */ @JvmStatic @JvmOverloads fun take(region: String, key: String? = DEFAULT_ATLAS_KEY): TextureRegion? = atlases[key]?.findRegion(region) }
mit
c52e81c19e1d5f299370e56c10050562
36.774648
111
0.695636
4.043741
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/debugger/remote/value/LuaRTable.kt
2
3823
/* * Copyright (c) 2017. tangzx([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.tang.intellij.lua.debugger.remote.value import com.intellij.icons.AllIcons import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.* import com.intellij.xdebugger.impl.XDebugSessionImpl import com.tang.intellij.lua.debugger.remote.LuaMobDebugProcess import org.luaj.vm2.LuaTable import org.luaj.vm2.LuaValue import java.util.* /** * * Created by tangzx on 2017/4/16. */ class LuaRTable(name: String) : LuaRValue(name) { private var list: XValueChildrenList? = null private val desc = "table" private var data: LuaValue? = null override fun parse(data: LuaValue, desc: String) { this.data = data } override fun computePresentation(xValueNode: XValueNode, xValuePlace: XValuePlace) { xValueNode.setPresentation(AllIcons.Json.Object, "table", desc, true) } private val evalExpr: String get() { var name = name val properties = ArrayList<String>() var parent = this.parent while (parent != null) { val parentName = parent.name properties.add(name) name = parentName parent = parent.parent } return buildString { append(name) for (i in properties.indices.reversed()) { val parentName = properties[i] when { parentName.startsWith("[") -> append(parentName) parentName.matches("[0-9]+".toRegex()) -> append("[$parentName]") else -> append(String.format("[\"%s\"]", parentName)) } } } } override fun computeChildren(node: XCompositeNode) { if (list == null) { val process = session.debugProcess as LuaMobDebugProcess process.evaluator?.evaluate(evalExpr, object : XDebuggerEvaluator.XEvaluationCallback { override fun errorOccurred(err: String) { node.setErrorMessage(err) } override fun evaluated(tableValue: XValue) { //////////tmp solution,非栈顶帧处理 var tableValue = tableValue if (data != null && !(process.session as XDebugSessionImpl).isTopFrameSelected) tableValue = LuaRValue.create(myName, data as LuaValue, myName, process.session) ////////// val list = XValueChildrenList() val tbl = tableValue as? LuaRTable ?: return val table = tbl.data?.checktable() if (table != null) for (key in table.keys()) { val value = LuaRValue.create(key.toString(), table.get(key), "", session) value.parent = this@LuaRTable list.add(value) } node.addChildren(list, true) [email protected] = list } }, null) } else node.addChildren(list!!, true) } }
apache-2.0
84779b10a2df72182a0241098c3503cb
36.742574
104
0.570192
4.84244
false
false
false
false
lehvolk/xodus-entity-browser
entity-browser-app/src/main/kotlin/jetbrains/xodus/browser/web/EmbeddableMain.kt
1
1000
package jetbrains.xodus.browser.web import io.ktor.server.engine.embeddedServer import io.ktor.server.jetty.Jetty import jetbrains.exodus.entitystore.PersistentEntityStoreImpl import jetbrains.exodus.entitystore.PersistentEntityStores import jetbrains.exodus.env.Environments fun main() { Home.setup() val appPort = Integer.getInteger("server.port", 18080) val appHost = System.getProperty("server.host", "localhost") val context = System.getProperty("server.context", "/") val store = PersistentEntityStores.newInstance(Environments.newInstance("some path to app"), "teamsysstore") val server = embeddedServer(Jetty, port = appPort, host = appHost) { val webApplication = object : EmbeddableWebApplication(lookup = { listOf(store) }) { override fun PersistentEntityStoreImpl.isForcedlyReadonly() = true } HttpServer(webApplication, context).setup(this) } server.start(false) OS.launchBrowser(appHost, appPort, context) }
apache-2.0
2b32aa217480f77d7f03d12033216897
36.037037
112
0.741
4.366812
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/refactoring/LuaRefactoringUtil.kt
2
2284
/* * Copyright (c) 2017. tangzx([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.tang.intellij.lua.refactoring import com.intellij.codeInsight.PsiEquivalenceUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil.isJavaIdentifierPart import com.intellij.openapi.util.text.StringUtil.isJavaIdentifierStart import com.intellij.psi.PsiElement import com.tang.intellij.lua.psi.LuaVisitor import java.util.* /** * RefactoringUtil * Created by tangzx on 2017/4/30. */ object LuaRefactoringUtil { fun getOccurrences(pattern: PsiElement, context: PsiElement?): List<PsiElement> { if (context == null) { return emptyList() } val occurrences = ArrayList<PsiElement>() val visitor = object : LuaVisitor() { override fun visitElement(element: PsiElement) { if (PsiEquivalenceUtil.areElementsEquivalent(element, pattern)) { occurrences.add(element) return } element.acceptChildren(this) } } context.acceptChildren(visitor) return occurrences } fun isLuaIdentifier(name: String): Boolean { return StringUtil.isJavaIdentifier(name) } fun isLuaTypeIdentifier(text: String): Boolean { val len = text.length if (len == 0) { return false } else if (!isJavaIdentifierStart(text[0])) { return false } else { for (i in 1 until len) { val c = text[i] if (!isJavaIdentifierPart(c) && c != '.') { return false } } return true } } }
apache-2.0
192597f5b8c8b427d028913d835cfe46
31.628571
85
0.633538
4.604839
false
false
false
false
arnaudroger/SimpleFlatMapper
sfm-test-kotlin/src/test/kotlin/test/JdbcCsvTest.kt
1
2106
import org.junit.Test import org.simpleflatmapper.jdbc.JdbcMapperFactory import org.simpleflatmapper.util.TypeReference import test.CsvLine import java.sql.DriverManager import kotlin.test.assertEquals class JdbcCsvTest { @Test fun test() { val connection = DriverManager.getConnection("jdbc:h2:mem:"); connection.use { it.createStatement().use { val rs = it.executeQuery("SELECT 1 as elt0,2 as elt1") rs.use { val pair = JdbcMapperFactory .newInstance() .newMapper(object : TypeReference<Pair<Int, Int>>() {}) .iterator(rs).next() println(pair) assertEquals(1, pair.first) assertEquals(2, pair.second) } val rs2 = it.executeQuery("SELECT 1 as elt0,2 as elt1, 3 as elt2") rs2.use { val triple = JdbcMapperFactory .newInstance() .newMapper(object : TypeReference<Triple<Int, Int, Int>>() {}) .iterator(rs2).next() println(triple) assertEquals(1, triple.first) assertEquals(2, triple.second) assertEquals(3, triple.third) } } } } @Test fun test538() { val connection = DriverManager.getConnection("jdbc:h2:mem:"); connection.use { it.createStatement().use { val rs = it.executeQuery("SELECT 1 as field1,2 as field2") rs.use { val item = JdbcMapperFactory .newInstance() .newMapper(CsvLine::class.java) .iterator(rs).next() println(item) assertEquals("1", item.field1) assertEquals("2", item.field2) } } } } }
mit
fd29fdcba0bbb44094a9321dc5963cab
32.428571
90
0.465337
5.124088
false
true
false
false
czyzby/ktx
app/src/main/kotlin/ktx/app/Platform.kt
2
6695
package ktx.app import com.badlogic.gdx.Application.ApplicationType import com.badlogic.gdx.Gdx import com.badlogic.gdx.utils.GdxRuntimeException import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * Contains utilities for platform-specific code. Allows to easily determine current application platform * and its version. Can execute given actions only on specific platforms. */ object Platform { /** * The [ApplicationType] reported by the current libGDX application. Throws [GdxRuntimeException] when unable to * determine the platform. */ val currentPlatform: ApplicationType get() = Gdx.app?.type ?: throw GdxRuntimeException("Gdx.app is not defined or is missing the application type.") /** * True if [ApplicationType.Applet] is the [currentPlatform]. * * Deprecated. Since Applets are deprecated since Java 9 in 2017, developers are encouraged to use other technologies * to target the web platforms such as the WebGL backend. */ @Deprecated( message = "Java Applets are deprecated since Java 9 in 2017.", replaceWith = ReplaceWith("isWeb") ) val isApplet: Boolean get() = currentPlatform === ApplicationType.Applet /** * True if [ApplicationType.Android] is the [currentPlatform]. */ val isAndroid: Boolean get() = currentPlatform === ApplicationType.Android /** * True if [ApplicationType.Desktop] with a graphical application is the [currentPlatform]. */ val isDesktop: Boolean get() = currentPlatform === ApplicationType.Desktop /** * True if [ApplicationType.HeadlessDesktop] without a graphical application is the [currentPlatform]. */ val isHeadless: Boolean get() = currentPlatform === ApplicationType.HeadlessDesktop /** * True if [ApplicationType.iOS] is the [currentPlatform]. */ val isiOS: Boolean get() = currentPlatform === ApplicationType.iOS /** * True if [ApplicationType.Android] or [ApplicationType.iOS] are the [currentPlatform]. */ val isMobile: Boolean get() = isAndroid || isiOS /** * True if [ApplicationType.WebGL] is the [currentPlatform]. To determine if the application is running in an Applet, * use [isApplet] instead. */ val isWeb: Boolean get() = currentPlatform == ApplicationType.WebGL /** * Android API version on Android, major OS version on iOS, 0 on most other platforms, or -1 if unable to read. */ val version: Int get() = Gdx.app?.version ?: -1 /** * Executes [action] if the [currentPlatform] is [ApplicationType.Applet]. Returns [action] result or null. * @see isApplet */ @Deprecated( message = "Java Applets are deprecated since Java 9 in 2017.", replaceWith = ReplaceWith("runOnWeb") ) @Suppress("DEPRECATION") @OptIn(ExperimentalContracts::class) inline fun <T> runOnApplet(action: () -> T?): T? { contract { callsInPlace(action, InvocationKind.AT_MOST_ONCE) } return if (isApplet) action() else null } /** * Executes [action] if the [currentPlatform] is [ApplicationType.Android]. Returns [action] result or null. * @see isAndroid */ @OptIn(ExperimentalContracts::class) inline fun <T> runOnAndroid(action: () -> T?): T? { contract { callsInPlace(action, InvocationKind.AT_MOST_ONCE) } return if (isAndroid) action() else null } /** * Executes [action] if the [currentPlatform] is [ApplicationType.Desktop]. Returns [action] result or null. * @see isDesktop */ @OptIn(ExperimentalContracts::class) inline fun <T> runOnDesktop(action: () -> T?): T? { contract { callsInPlace(action, InvocationKind.AT_MOST_ONCE) } return if (isDesktop) action() else null } /** * Executes [action] if the [currentPlatform] is [ApplicationType.HeadlessDesktop]. Returns [action] result or null. * @see isHeadless */ @OptIn(ExperimentalContracts::class) inline fun <T> runOnHeadless(action: () -> T?): T? { contract { callsInPlace(action, InvocationKind.AT_MOST_ONCE) } return if (isHeadless) action() else null } /** * Executes [action] if the [currentPlatform] is [ApplicationType.iOS]. Returns [action] result or null. * @see isiOS */ @OptIn(ExperimentalContracts::class) inline fun <T> runOniOS(action: () -> T?): T? { contract { callsInPlace(action, InvocationKind.AT_MOST_ONCE) } return if (isiOS) action() else null } /** * Executes [action] if the [currentPlatform] is [ApplicationType.Android] or [ApplicationType.iOS]. * Returns [action] result or null. * @see isMobile */ @OptIn(ExperimentalContracts::class) inline fun <T> runOnMobile(action: () -> T?): T? { contract { callsInPlace(action, InvocationKind.AT_MOST_ONCE) } return if (isMobile) action() else null } /** * Executes [action] if the [currentPlatform] is [ApplicationType.WebGL]. Returns [action] result or null. * Not that the [action] will not be executed in an Applet - use [runOnApplet] instead. * @see isWeb */ @OptIn(ExperimentalContracts::class) inline fun <T> runOnWeb(action: () -> T?): T? { contract { callsInPlace(action, InvocationKind.AT_MOST_ONCE) } return if (isWeb) action() else null } /** * Executes [action] is the current platform [version] (such as Android API version or iOS major OS version) * is equal to or higher than [minVersion] and equal to or lower than [maxVersion]. If a [platform] is given, * the [currentPlatform] must also be the same in order to execute the [action]. * * All parameters are optional; if a parameter is not given, the associated condition does not have to be met * to execute [action]. For example, if [minVersion] is given, but [maxVersion] is not, the current application * [version] has to be the same as or above [minVersion], but there is no upper bound. Similarly, if a [platform] * is not given, the [action] will be executed on any platform that meets the [version] criteria. * * Returns [action] result if it was executed or null otherwise. * * @see version */ @OptIn(ExperimentalContracts::class) inline fun <T> runOnVersion( minVersion: Int? = null, maxVersion: Int? = null, platform: ApplicationType? = null, action: () -> T? ): T? { contract { callsInPlace(action, InvocationKind.AT_MOST_ONCE) } val matchesMinVersion = minVersion === null || minVersion <= version val matchesMaxVersion = maxVersion === null || version <= maxVersion val matchesPlatform = platform === null || currentPlatform === platform return if (matchesMinVersion && matchesMaxVersion && matchesPlatform) action() else null } }
cc0-1.0
ccf96ebab96110b9defa0e7ed4d2492b
35.785714
119
0.693503
4.264331
false
false
false
false
Polidea/RxAndroidBle
sample-kotlin/src/main/kotlin/com/polidea/rxandroidble2/samplekotlin/example2_connection/ConnectionExampleActivity.kt
1
4590
package com.polidea.rxandroidble2.samplekotlin.example2_connection import android.annotation.TargetApi import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.polidea.rxandroidble2.RxBleConnection import com.polidea.rxandroidble2.RxBleDevice import com.polidea.rxandroidble2.samplekotlin.R import com.polidea.rxandroidble2.samplekotlin.SampleApplication import com.polidea.rxandroidble2.samplekotlin.util.isConnected import com.polidea.rxandroidble2.samplekotlin.util.showSnackbarShort import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.activity_example2.autoconnect import kotlinx.android.synthetic.main.activity_example2.connect_toggle import kotlinx.android.synthetic.main.activity_example2.connection_state import kotlinx.android.synthetic.main.activity_example2.newMtu import kotlinx.android.synthetic.main.activity_example2.set_mtu private const val EXTRA_MAC_ADDRESS = "extra_mac_address" class ConnectionExampleActivity : AppCompatActivity() { companion object { fun newInstance(context: Context, macAddress: String) = Intent(context, ConnectionExampleActivity::class.java).apply { putExtra(EXTRA_MAC_ADDRESS, macAddress) } } private lateinit var bleDevice: RxBleDevice private var connectionDisposable: Disposable? = null private var stateDisposable: Disposable? = null private val mtuDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_example2) connect_toggle.setOnClickListener { onConnectToggleClick() } set_mtu.setOnClickListener { onSetMtu() } val macAddress = intent.getStringExtra(EXTRA_MAC_ADDRESS) title = getString(R.string.mac_address, macAddress) bleDevice = SampleApplication.rxBleClient.getBleDevice(macAddress!!) // How to listen for connection state changes // Note: it is meant for UI updates only — one should not observeConnectionStateChanges() with BLE connection logic bleDevice.observeConnectionStateChanges() .observeOn(AndroidSchedulers.mainThread()) .subscribe { onConnectionStateChange(it) } .let { stateDisposable = it } } private fun onConnectToggleClick() { if (bleDevice.isConnected) { triggerDisconnect() } else { bleDevice.establishConnection(autoconnect.isChecked) .observeOn(AndroidSchedulers.mainThread()) .doFinally { dispose() } .subscribe({ onConnectionReceived() }, { onConnectionFailure(it) }) .let { connectionDisposable = it } } } @TargetApi(21 /* Build.VERSION_CODES.LOLLIPOP */) private fun onSetMtu() { newMtu.text.toString().toIntOrNull()?.let { mtu -> bleDevice.establishConnection(false) .flatMapSingle { rxBleConnection -> rxBleConnection.requestMtu(mtu) } .take(1) // Disconnect automatically after discovery .observeOn(AndroidSchedulers.mainThread()) .doFinally { updateUI() } .subscribe({ onMtuReceived(it) }, { onConnectionFailure(it) }) .let { mtuDisposable.add(it) } } } private fun onConnectionFailure(throwable: Throwable) = showSnackbarShort("Connection error: $throwable") private fun onConnectionReceived() = showSnackbarShort("Connection received") private fun onConnectionStateChange(newState: RxBleConnection.RxBleConnectionState) { connection_state.text = newState.toString() updateUI() } private fun onMtuReceived(mtu: Int) = showSnackbarShort("MTU received: $mtu") private fun dispose() { connectionDisposable = null updateUI() } private fun triggerDisconnect() = connectionDisposable?.dispose() private fun updateUI() { connect_toggle.setText(if (bleDevice.isConnected) R.string.button_disconnect else R.string.button_connect) autoconnect.isEnabled = !bleDevice.isConnected } override fun onPause() { super.onPause() triggerDisconnect() mtuDisposable.clear() } override fun onDestroy() { super.onDestroy() stateDisposable?.dispose() } }
apache-2.0
5320f4890e1b53cf172a066f3ceda9b9
37.554622
123
0.70837
4.912206
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/AImageListQuestAnswerFragment.kt
1
4316
package de.westnordost.streetcomplete.quests import android.content.Context import android.os.Bundle import android.preference.PreferenceManager import androidx.recyclerview.widget.GridLayoutManager import android.view.View import java.util.ArrayList import java.util.LinkedList import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.view.ImageSelectAdapter import de.westnordost.streetcomplete.view.Item import kotlinx.android.synthetic.main.quest_generic_list.* /** * Abstract class for quests with a list of images and one or several to select. */ abstract class AImageListQuestAnswerFragment<I,T> : AbstractQuestFormAnswerFragment<T>() { override val contentLayoutResId = R.layout.quest_generic_list protected lateinit var imageSelector: ImageSelectAdapter<I> private lateinit var favs: LastPickedValuesStore<I> protected open val itemsPerRow = 4 /** return -1 for any number. Default: 1 */ protected open val maxSelectableItems = 1 /** return -1 for showing all items at once. Default: -1 */ protected open val maxNumberOfInitiallyShownItems = -1 protected abstract val items: List<Item<I>> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) imageSelector = ImageSelectAdapter(maxSelectableItems) } override fun onAttach(ctx: Context) { super.onAttach(ctx) favs = LastPickedValuesStore(PreferenceManager.getDefaultSharedPreferences(ctx.applicationContext)) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) list.layoutManager = GridLayoutManager(activity, itemsPerRow) list.isNestedScrollingEnabled = false selectHintLabel.setText(if (maxSelectableItems == 1) R.string.quest_roofShape_select_one else R.string.quest_select_hint) imageSelector.listeners.add(object : ImageSelectAdapter.OnItemSelectionListener { override fun onIndexSelected(index: Int) { checkIsFormComplete() } override fun onIndexDeselected(index: Int) { checkIsFormComplete() } }) showMoreButton.setOnClickListener { imageSelector.items = items.favouritesMovedToFront() showMoreButton.visibility = View.GONE } var initiallyShow = maxNumberOfInitiallyShownItems if (savedInstanceState != null) { if (savedInstanceState.getBoolean(EXPANDED)) initiallyShow = -1 showItems(initiallyShow) val selectedIndices = savedInstanceState.getIntegerArrayList(SELECTED_INDICES)!! imageSelector.select(selectedIndices) } else { showItems(initiallyShow) } list.adapter = imageSelector } override fun onClickOk() { val values = imageSelector.selectedItems if (values.isNotEmpty()) { favs.add(javaClass.simpleName, values) onClickOk(values) } } abstract protected fun onClickOk(selectedItems: List<I>) override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putIntegerArrayList(SELECTED_INDICES, ArrayList(imageSelector.selectedIndices)) outState.putBoolean(EXPANDED, showMoreButton.visibility == View.GONE) } override fun isFormComplete() = imageSelector.selectedIndices.isNotEmpty() private fun showItems(initiallyShow: Int) { val allItems = items val showAll = initiallyShow == -1 || initiallyShow >= allItems.size showMoreButton.visibility = if(showAll) View.GONE else View.VISIBLE val sortedItems = allItems.favouritesMovedToFront() imageSelector.items = if(showAll) sortedItems else sortedItems.subList(0, initiallyShow) } private fun List<Item<I>>.favouritesMovedToFront(): List<Item<I>> { val result: LinkedList<Item<I>> = LinkedList(this) if (result.size > itemsPerRow) { favs.moveLastPickedToFront(javaClass.simpleName, result, this) } return result } companion object { private const val SELECTED_INDICES = "selected_indices" private const val EXPANDED = "expanded" } }
gpl-3.0
298ee4e20b694ee72c258e9748077b4e
34.377049
129
0.702271
5.077647
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/latex/ui/widget/ProgressableWebViewClient.kt
2
854
package org.stepik.android.view.latex.ui.widget import android.content.Context import android.graphics.Bitmap import android.view.View import android.webkit.WebView import androidx.core.view.isVisible import org.stepik.android.view.base.ui.extension.ExternalLinkWebViewClient class ProgressableWebViewClient( private val progressView: View, private val webView: View, context: Context = progressView.context ) : ExternalLinkWebViewClient(context) { override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { super.onPageStarted(view, url, favicon) progressView.isVisible = true webView.isVisible = false } override fun onPageFinished(view: WebView?, url: String?) { progressView.isVisible = false webView.isVisible = true super.onPageFinished(view, url) } }
apache-2.0
808d0c4b4bae5859e7a7af9c38717d5b
31.884615
80
0.740047
4.471204
false
false
false
false
michalfaber/android-drawer-template
app/src/main/kotlin/views/adapters/ViewHolderProvider.kt
1
1457
package com.michalfaber.drawertemplate.views.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlin.reflect.KClass /** Provides specific implementation of view holder based on registered class Holds a map where key is a ViewHolder hashCode and value is a pair: layout id and function which creates specific implementation of ViewHolder. */ class ViewHolderProvider { private val viewHolderFactories = hashMapOf<Int, Pair<Int, Any>>() [suppress("UNCHECKED_CAST")] fun provideViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val value = viewHolderFactories.get(viewType) if (value == null) { throw RuntimeException("Not found ViewHolder factory for viewType:$viewType") } // get the layout id and factory function val (layoutId: Int, f: Any) = value val viewHolderFactory = f as (View) -> RecyclerView.ViewHolder // inflate a view based on the layout ud val view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutId, viewGroup, false) // create specific view holder return viewHolderFactory(view) } fun registerViewHolderFactory<T>(key: KClass<T>, layoutId: Int, viewHolderFactory: (View) -> T) { viewHolderFactories.put(key.hashCode(), Pair(layoutId, viewHolderFactory)) } }
apache-2.0
0fa9ec0c344b792c9c4e535d875c3d65
37.368421
101
0.717227
4.792763
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/track/anilist/AnilistModels.kt
1
3420
package eu.kanade.tachiyomi.data.track.anilist import eu.kanade.domain.track.service.TrackPreferences import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.Locale data class ALManga( val media_id: Long, val title_user_pref: String, val image_url_lge: String, val description: String?, val format: String, val publishing_status: String, val start_date_fuzzy: Long, val total_chapters: Int, ) { fun toTrack() = TrackSearch.create(TrackManager.ANILIST).apply { media_id = [email protected]_id title = title_user_pref total_chapters = [email protected]_chapters cover_url = image_url_lge summary = description ?: "" tracking_url = AnilistApi.mangaUrl(media_id) publishing_status = [email protected]_status publishing_type = format if (start_date_fuzzy != 0L) { start_date = try { val outputDf = SimpleDateFormat("yyyy-MM-dd", Locale.US) outputDf.format(start_date_fuzzy) } catch (e: Exception) { "" } } } } data class ALUserManga( val library_id: Long, val list_status: String, val score_raw: Int, val chapters_read: Int, val start_date_fuzzy: Long, val completed_date_fuzzy: Long, val manga: ALManga, ) { fun toTrack() = Track.create(TrackManager.ANILIST).apply { media_id = manga.media_id title = manga.title_user_pref status = toTrackStatus() score = score_raw.toFloat() started_reading_date = start_date_fuzzy finished_reading_date = completed_date_fuzzy last_chapter_read = chapters_read.toFloat() library_id = [email protected]_id total_chapters = manga.total_chapters } fun toTrackStatus() = when (list_status) { "CURRENT" -> Anilist.READING "COMPLETED" -> Anilist.COMPLETED "PAUSED" -> Anilist.ON_HOLD "DROPPED" -> Anilist.DROPPED "PLANNING" -> Anilist.PLAN_TO_READ "REPEATING" -> Anilist.REREADING else -> throw NotImplementedError("Unknown status: $list_status") } } fun Track.toAnilistStatus() = when (status) { Anilist.READING -> "CURRENT" Anilist.COMPLETED -> "COMPLETED" Anilist.ON_HOLD -> "PAUSED" Anilist.DROPPED -> "DROPPED" Anilist.PLAN_TO_READ -> "PLANNING" Anilist.REREADING -> "REPEATING" else -> throw NotImplementedError("Unknown status: $status") } private val preferences: TrackPreferences by injectLazy() fun Track.toAnilistScore(): String = when (preferences.anilistScoreType().get()) { // 10 point "POINT_10" -> (score.toInt() / 10).toString() // 100 point "POINT_100" -> score.toInt().toString() // 5 stars "POINT_5" -> when { score == 0f -> "0" score < 30 -> "1" score < 50 -> "2" score < 70 -> "3" score < 90 -> "4" else -> "5" } // Smiley "POINT_3" -> when { score == 0f -> "0" score <= 35 -> ":(" score <= 60 -> ":|" else -> ":)" } // 10 point decimal "POINT_10_DECIMAL" -> (score / 10).toString() else -> throw NotImplementedError("Unknown score type") }
apache-2.0
9a421b05505779235cd9fe306e020427
29.810811
82
0.615789
3.779006
false
false
false
false
Maccimo/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/src/WorkspaceImplObsoleteInspection.kt
4
3569
// 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.devkit.workspaceModel import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.LocalQuickFixOnPsiElement import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.workspaceModel.storage.CodeGeneratorVersions import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.stubindex.KotlinClassShortNameIndex import org.jetbrains.kotlin.parsing.parseNumericLiteral import org.jetbrains.kotlin.psi.* private val LOG = logger<WorkspaceImplObsoleteInspection>() class WorkspaceImplObsoleteInspection: LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() { override fun visitClass(klass: KtClass) { if (!klass.isWorkspaceEntity()) return val targetApiVersion = calculateTargetApiVersion(klass.project) if (targetApiVersion == null) { LOG.info("Can't evaluate target API version") return } if (klass.name == "Builder") return val foundImplClasses = KotlinClassShortNameIndex.get("${klass.name}Impl", klass.project, GlobalSearchScope.allScope(klass.project)) if (foundImplClasses.isEmpty()) return val implClass = foundImplClasses.first() val apiVersion = (implClass as? KtClass)?.getApiVersion() if (apiVersion == targetApiVersion) return holder.registerProblem(klass.nameIdentifier!!, DevKitWorkspaceModelBundle.message("inspection.workspace.msg.obsolete.implementation"), RegenerateWorkspaceModelFix(klass.nameIdentifier!!)) } } private fun calculateTargetApiVersion(project: Project): Int? { val generatorVersions = CodeGeneratorVersions::class.simpleName val foundClasses = KotlinClassShortNameIndex.get(generatorVersions!!, project, GlobalSearchScope.allScope(project)) if (foundClasses.isEmpty()) { error("Can't find $generatorVersions") } val ktClassOrObject = foundClasses.first() val fieldName = "API_VERSION" val ktDeclaration = ktClassOrObject.declarations.first { it.name == fieldName } if (ktDeclaration !is KtProperty) { error("Unexpected declaration type for field $fieldName") } val propertyExpression = ktDeclaration.initializer as? KtConstantExpression if (propertyExpression == null) { error("Property value should be int constant") } val elementType = propertyExpression.node.elementType if (elementType == KtNodeTypes.INTEGER_CONSTANT) { return parseNumericLiteral(propertyExpression.text, elementType)?.toInt() } return null } } private class RegenerateWorkspaceModelFix(psiElement: PsiElement) : LocalQuickFixOnPsiElement(psiElement) { override fun getText() = DevKitWorkspaceModelBundle.message("inspection.workspace.msg.regenerate.implementation") override fun getFamilyName() = name override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex val module = projectFileIndex.getModuleForFile(file.virtualFile) WorkspaceModelGenerator.generate(project, module!!) } }
apache-2.0
55cc56d1167b6c428198815fb9c93048
45.363636
140
0.770524
5.00561
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/compiler-plugins/sam-with-receiver/common/src/org/jetbrains/kotlin/idea/compilerPlugin/samWithReceiver/IdeSamWithReceiverComponentContributor.kt
2
3057
// 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.compilerPlugin.samWithReceiver import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootModificationTracker import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.container.StorageComponentContainer import org.jetbrains.kotlin.container.useInstance import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptDependenciesInfo import org.jetbrains.kotlin.idea.base.scripting.projectStructure.ScriptModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleProductionSourceInfo import org.jetbrains.kotlin.idea.compilerPlugin.getSpecialAnnotations import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor.Companion.ANNOTATION_OPTION import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor.Companion.PLUGIN_ID import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverResolverExtension class IdeSamWithReceiverComponentContributor(val project: Project) : StorageComponentContainerContributor { private companion object { val ANNOTATION_OPTION_PREFIX = "plugin:$PLUGIN_ID:${ANNOTATION_OPTION.optionName}=" } private val cache = CachedValuesManager.getManager(project).createCachedValue({ Result.create( ContainerUtil.createConcurrentWeakMap<Module, List<String>>(), ProjectRootModificationTracker.getInstance( project ) ) }, /* trackValue = */ false) private fun getAnnotationsForModule(module: Module): List<String> { return cache.value.getOrPut(module) { module.getSpecialAnnotations(ANNOTATION_OPTION_PREFIX) } } override fun registerModuleComponents( container: StorageComponentContainer, platform: TargetPlatform, moduleDescriptor: ModuleDescriptor ) { if (!platform.isJvm()) return val annotations = when (val moduleInfo = moduleDescriptor.getCapability(ModuleInfo.Capability)) { is ScriptModuleInfo -> moduleInfo.scriptDefinition.annotationsForSamWithReceivers is ScriptDependenciesInfo.ForFile -> moduleInfo.scriptDefinition.annotationsForSamWithReceivers is ModuleProductionSourceInfo -> getAnnotationsForModule(moduleInfo.module) else -> null } ?: return container.useInstance(SamWithReceiverResolverExtension(annotations)) } }
apache-2.0
09a2a183d46cdd60025c583943b28b1f
48.322581
158
0.785738
5.468694
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/arrays/AugmentedArrayExtensions.kt
1
1383
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * 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 com.kotlinnlp.simplednn.core.arrays import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceUtils import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * Get the errors of the input of the unit. The errors of the output must be already set. * * @param w the weights * * @return the errors of the input of this unit */ fun AugmentedArray<DenseNDArray>.getInputErrors(w: NDArray<*>): DenseNDArray = this.errors.t.dot(w) /** * Get the relevance of the input of the unit. The relevance of the output must be already set. * * @param x the input of the unit * @param cw the weights-contribution of the input to calculate the output * * @return the relevance of the input of the unit */ fun AugmentedArray<DenseNDArray>.getInputRelevance(x: DenseNDArray, cw: DenseNDArray): DenseNDArray = RelevanceUtils.calculateRelevanceOfArray( x = x, y = this.valuesNotActivated, yRelevance = this.relevance, contributions = cw )
mpl-2.0
f9320490e5657f6de000009c27cfda8f
36.378378
101
0.711497
4.153153
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/feedforward/batchnorm/BatchNormLayer.kt
1
3635
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * 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 com.kotlinnlp.simplednn.core.layers.models.feedforward.batchnorm import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.Layer import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.layers.helpers.RelevanceHelper import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.Shape import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory /** * The batch normalization layer structure. * * @property inputArrays the input arrays of the layer * @property inputType the type of the input arrays * @property params the parameters which connect the input to the output */ internal class BatchNormLayer<InputNDArrayType : NDArray<InputNDArrayType>>( val inputArrays: List<AugmentedArray<InputNDArrayType>>, inputType: LayerType.Input, override val params: BatchNormLayerParameters ) : Layer<InputNDArrayType>( inputArray = AugmentedArray(params.inputSize), // empty array (it should not be used) inputType = inputType, outputArray = AugmentedArray(1), params = params, activationFunction = null, dropout = 0.0 ) { /** * The size of the input arrays. */ val inputSize: Int = this.inputArrays.first().values.length /** * The list containing the layer output. */ val outputArrays: List<AugmentedArray<DenseNDArray>> = List(this.inputArrays.size) { AugmentedArray(DenseNDArrayFactory.zeros(Shape(this.inputSize))) } /** * Support vector for the mean of the input arrays. */ internal val mean: DenseNDArray = DenseNDArrayFactory.zeros(Shape(this.inputSize)) /** * Support vector for the standard deviation of the input arrays. */ internal val stdDev: DenseNDArray = DenseNDArrayFactory.zeros(Shape(this.inputSize)) /** * The helper which executes the forward. */ override val forwardHelper = BatchNormForwardHelper(layer = this) /** * The helper which executes the backward. */ override val backwardHelper = BatchNormBackwardHelper(layer = this) /** * The helper which calculates the relevance. */ override val relevanceHelper: RelevanceHelper? = null /** * Check the size of the input arrays. */ init { require(this.inputArrays.all { it.size == this.inputSize }) { "All the input arrays must have the same size." } } /** * Set the values of the input arrays. * * @param inputs the values of the input arrays */ fun setInputs(inputs: List<InputNDArrayType>) { this.inputArrays.zip(inputs).forEach { (array, values) -> array.assignValues(values) } } /** * Set the errors of the output arrays. * * @param outputErrors the errors of each output array */ fun setErrors(outputErrors: List<DenseNDArray>) { this.outputArrays.zip(outputErrors).forEach { (array, error) -> array.assignErrors(error) } } /** * @param copy whether the returned errors must be a copy or a reference * * @return the errors of the input arrays */ fun getInputErrors(copy: Boolean = true): List<DenseNDArray> = this.inputArrays.map { if (copy) it.errors.copy() else it.errors } }
mpl-2.0
7f801c8690520e2111d34e53f66597fe
29.805085
87
0.709216
4.342891
false
false
false
false
nicopico-dev/HappyBirthday
app/src/main/java/fr/nicopico/happybirthday/ui/home/MainActivity.kt
1
3917
/* * Copyright 2016 Nicolas Picon <[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 fr.nicopico.happybirthday.ui.home import android.Manifest.permission.READ_CONTACTS import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.Menu import android.view.MenuItem import android.view.View import fr.nicopico.happybirthday.R import fr.nicopico.happybirthday.data.repository.ContactRepository import fr.nicopico.happybirthday.domain.model.Contact import fr.nicopico.happybirthday.domain.model.nextBirthdaySorter import fr.nicopico.happybirthday.extensions.ensurePermissions import fr.nicopico.happybirthday.extensions.ifElse import fr.nicopico.happybirthday.extensions.toast import fr.nicopico.happybirthday.inject.AppComponent import fr.nicopico.happybirthday.ui.BaseActivity import kotlinx.android.synthetic.main.activity_main.* import rx.Observable import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import timber.log.Timber import java.util.concurrent.TimeUnit import javax.inject.Inject class MainActivity : BaseActivity() { @Inject lateinit var contactRepository: ContactRepository lateinit private var contactAdapter: ContactAdapter private var subscription: Subscription? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) contactAdapter = ContactAdapter(this) rvContacts.apply { layoutManager = LinearLayoutManager(this@MainActivity) adapter = contactAdapter } loadContacts() } override fun onDestroy() { subscription?.unsubscribe() super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.menu_reload) { loadContacts(delay = true) return true } else { return super.onOptionsItemSelected(item) } } override fun inject(component: AppComponent) { component.inject(this) } private fun loadContacts(delay: Boolean = false) { subscription?.unsubscribe() val contactObservable: Observable<List<Contact>> = ensurePermissions(READ_CONTACTS) { contactRepository .list(sorter = nextBirthdaySorter()) .ifElse(delay, ifTrue = { delay(1, TimeUnit.SECONDS) }) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { progressBar.visibility = View.VISIBLE } } subscription = contactObservable.subscribe(subscriber) } private val subscriber = object : Subscriber<List<Contact>>() { override fun onNext(contacts: List<Contact>?) { progressBar.visibility = View.GONE contactAdapter.data = contacts } override fun onCompleted() { // No-op } override fun onError(e: Throwable?) { progressBar.visibility = View.GONE toast("Error $e") Timber.e(e, "Unable to retrieve contact") } } }
apache-2.0
3640de7a3539db53d1f0482a3e529d98
32.194915
93
0.689558
4.817958
false
false
false
false
MER-GROUP/intellij-community
platform/script-debugger/backend/src/org/jetbrains/debugger/ValueModifierUtil.kt
3
2605
/* * 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.debugger import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.then import org.jetbrains.concurrency.thenAsyncAccept import org.jetbrains.debugger.values.Value import org.jetbrains.io.JsonUtil import java.util.* import java.util.regex.Pattern private val KEY_NOTATION_PROPERTY_NAME_PATTERN = Pattern.compile("[\\p{L}_$]+[\\d\\p{L}_$]*") object ValueModifierUtil { fun setValue(variable: Variable, newValue: String, evaluateContext: EvaluateContext, modifier: ValueModifier) = evaluateContext.evaluate(newValue) .thenAsyncAccept { modifier.setValue(variable, it.value, evaluateContext) } fun evaluateGet(variable: Variable, host: Any, evaluateContext: EvaluateContext, selfName: String): Promise<Value> { val builder = StringBuilder(selfName) appendUnquotedName(builder, variable.name) return evaluateContext.evaluate(builder.toString(), Collections.singletonMap(selfName, host), false) .then { variable.value = it.value it.value } } fun propertyNamesToString(list: List<String>, quotedAware: Boolean): String { val builder = StringBuilder() for (i in list.indices.reversed()) { val name = list[i] doAppendName(builder, name, quotedAware && (name[0] == '"' || name[0] == '\'')) } return builder.toString() } fun appendUnquotedName(builder: StringBuilder, name: String) { doAppendName(builder, name, false) } } private fun doAppendName(builder: StringBuilder, name: String, quoted: Boolean) { val useKeyNotation = !quoted && KEY_NOTATION_PROPERTY_NAME_PATTERN.matcher(name).matches() if (builder.length != 0) { builder.append(if (useKeyNotation) '.' else '[') } if (useKeyNotation) { builder.append(name) } else { if (quoted) { builder.append(name) } else { JsonUtil.escape(name, builder) } builder.append(']') } }
apache-2.0
b34e60e4bb9461a7db8a9a9c7f2ad37b
31.987342
104
0.685988
4.18138
false
false
false
false
mdaniel/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ProjectModuleOperationProvider.kt
2
6240
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.extensibility import com.intellij.buildsystem.model.DeclaredDependency import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.OperationItem import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.jetbrains.packagesearch.intellij.plugin.intentions.PackageSearchDependencyUpgradeQuickFix import com.jetbrains.packagesearch.intellij.plugin.util.asCoroutine /** * Extension point that allows to modify the dependencies of a specific project. */ @Deprecated( "Use async version. Either AsyncProjectModuleOperationProvider or CoroutineProjectModuleOperationProvider." + " Remember to change the extension point type in the xml", ReplaceWith( "ProjectAsyncModuleOperationProvider", "com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectAsyncModuleOperationProvider" ), DeprecationLevel.WARNING ) interface ProjectModuleOperationProvider { companion object { private val extensionPointName get() = ExtensionPointName.create<ProjectModuleOperationProvider>("com.intellij.packagesearch.projectModuleOperationProvider") internal val extensions get() = extensionPointName.extensions.map { it.asCoroutine() } } /** * Returns whether the implementation of the interface uses the shared "packages update available" * inspection and quickfix. This is `false` by default; override this property and return `true` * to opt in to [PackageUpdateInspection]. * * @return `true` opt in to [PackageUpdateInspection], false otherwise. * @see PackageUpdateInspection * @see PackageSearchDependencyUpgradeQuickFix */ fun usesSharedPackageUpdateInspection(): Boolean = false /** * Checks if current implementation has support in the given [project] for the current [psiFile]. * @return `true` if the [project] and [psiFile] are supported. */ fun hasSupportFor(project: Project, psiFile: PsiFile?): Boolean /** * Checks if current implementation has support in the given [projectModuleType]. * @return `true` if the [projectModuleType] is supported. */ fun hasSupportFor(projectModuleType: ProjectModuleType): Boolean /** * Adds a dependency to the given [module] using [operationMetadata]. * @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful. */ fun addDependencyToModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): Collection<OperationFailure<out OperationItem>> = emptyList() /** * Removes a dependency from the given [module] using [operationMetadata]. * @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful. */ fun removeDependencyFromModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): Collection<OperationFailure<out OperationItem>> = emptyList() /** * Modify a dependency in the given [module] using [operationMetadata]. * @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful. */ fun updateDependencyInModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): Collection<OperationFailure<out OperationItem>> = emptyList() /** * Lists all dependencies declared in the given [module]. A declared dependency * have to be explicitly written in the build file. * @return A [Collection]<[UnifiedDependency]> found in the project. */ fun declaredDependenciesInModule( module: ProjectModule ): Collection<DeclaredDependency> = emptyList() /** * Lists all resolved dependencies in the given [module]. * @return A [Collection]<[UnifiedDependency]> found in the project. */ fun resolvedDependenciesInModule( module: ProjectModule, scopes: Set<String> = emptySet() ): Collection<UnifiedDependency> = emptyList() /** * Adds the [repository] to the given [module]. * @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful. */ fun addRepositoryToModule( repository: UnifiedDependencyRepository, module: ProjectModule ): Collection<OperationFailure<out OperationItem>> = emptyList() /** * Removes the [repository] from the given [module]. * @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful. */ fun removeRepositoryFromModule( repository: UnifiedDependencyRepository, module: ProjectModule ): Collection<OperationFailure<out OperationItem>> = emptyList() /** * Lists all repositories in the given [module]. * @return A [Collection]<[UnifiedDependencyRepository]> found the project. */ fun listRepositoriesInModule( module: ProjectModule ): Collection<UnifiedDependencyRepository> = emptyList() }
apache-2.0
9ba433086a10a9e7ef66e107ad741981
41.44898
138
0.713782
5.512367
false
false
false
false
austinv11/D4JBot
src/main/kotlin/com/austinv11/d4j/bot/command/impl/TagCommand.kt
1
3070
package com.austinv11.d4j.bot.command.impl import com.austinv11.d4j.bot.CLIENT import com.austinv11.d4j.bot.command.* import com.austinv11.d4j.bot.db.Tag import com.austinv11.d4j.bot.db.TagTable import com.austinv11.d4j.bot.extensions.embed import com.austinv11.d4j.bot.extensions.formattedName import com.austinv11.d4j.bot.extensions.isBotOwner class TagCommand : CommandExecutor() { override val name: String = "tag" override val aliases: Array<String> = arrayOf("tags") @Executor("Gets a list of tags.") fun execute() = context.embed.apply { withTitle("Available tags:") withDesc(buildString { TagTable.tags.forEachIndexed { i, tag -> appendln("${i+1}. ${tag.name}") } }) } @Executor("Gets a specific tag.") fun execute(@Parameter("The tag to get.") tag: String) = context.embed.apply { val tag = TagTable.getTag(tag) if (tag == null) { throw CommandException("Tag not found!") } else { withTitle(tag.name) withDesc(tag.content) val user = CLIENT.getUserByID(tag.author) if (user != null) { withAuthorIcon(user.avatarURL) withAuthorName(user.formattedName(context.guild)) withTimestamp(tag.timestamp) } } } @Executor("Performs a an action on the tag list.") fun execute(@Parameter("The action to perform.") action: OneArgActions, @Parameter("The tag to perform the action on.") tag: String): Any { when (action) { OneArgActions.REMOVE -> { val currTag = TagTable.getTag(tag) if (currTag != null) { if (!!context.author.isBotOwner && context.author.longID != currTag.author) throw CommandException("You can't modify another user's tag!") } TagTable.removeTag(tag) return true } OneArgActions.GET -> { return@execute execute(tag) } } } @Executor("Sets a tag's content.") fun execute(@Parameter("The action to perform.") action: TwoArgActions, @Parameter("The tag to perform the action on.") tag: String, @Parameter("The content to associate with the tag.") content: String): Boolean { when (action) { TwoArgActions.PUT -> { val currTag = TagTable.getTag(tag) if (currTag != null) { if (!!context.author.isBotOwner && context.author.longID != currTag.author) throw CommandException("You can't modify another user's tag!") } TagTable.addTag(Tag(tag, context.author.longID, content, System.currentTimeMillis())) } } return true } enum class OneArgActions { REMOVE, GET } enum class TwoArgActions { PUT } }
gpl-3.0
e5f932553599379ecc0cb570457c1ead
34.287356
101
0.559283
4.41092
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/sdk/PyTargetsRemoteSourcesRefresher.kt
4
8102
// 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.sdk import com.google.gson.Gson import com.google.gson.annotations.SerializedName import com.intellij.execution.ExecutionException import com.intellij.execution.target.TargetEnvironment import com.intellij.execution.target.TargetEnvironment.TargetPath import com.intellij.execution.target.TargetEnvironmentRequest import com.intellij.execution.target.TargetProgressIndicatorAdapter import com.intellij.execution.target.value.getRelativeTargetPath import com.intellij.execution.target.value.getTargetDownloadPath import com.intellij.execution.target.value.getTargetUploadPath import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.project.modules import com.intellij.openapi.project.rootManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.remote.RemoteSdkProperties import com.intellij.util.PathMappingSettings import com.intellij.util.PathUtil import com.intellij.util.io.ZipUtil import com.intellij.util.io.deleteWithParentsIfEmpty import com.jetbrains.python.PythonHelper import com.jetbrains.python.run.* import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest import com.jetbrains.python.target.PyTargetAwareAdditionalData import com.jetbrains.python.target.PyTargetAwareAdditionalData.Companion.pathsAddedByUser import com.jetbrains.python.target.PyTargetAwareAdditionalData.Companion.pathsRemovedByUser import java.nio.file.Files import java.nio.file.attribute.FileTime import java.time.Instant import kotlin.io.path.deleteExisting import kotlin.io.path.div private const val STATE_FILE = ".state.json" class PyTargetsRemoteSourcesRefresher(val sdk: Sdk, private val project: Project) { private val pyRequest: HelpersAwareTargetEnvironmentRequest = checkNotNull(PythonInterpreterTargetEnvironmentFactory.findPythonTargetInterpreter(sdk, project)) private val targetEnvRequest: TargetEnvironmentRequest get() = pyRequest.targetEnvironmentRequest init { assert(sdk !is Disposable || !Disposer.isDisposed(sdk)) } @Throws(ExecutionException::class) fun run(indicator: ProgressIndicator) { val localRemoteSourcesRoot = Files.createDirectories(sdk.remoteSourcesLocalPath) val localUploadDir = Files.createTempDirectory("remote_sync") val uploadVolume = TargetEnvironment.UploadRoot(localRootPath = localUploadDir, targetRootPath = TargetPath.Temporary()) targetEnvRequest.uploadVolumes += uploadVolume val downloadVolume = TargetEnvironment.DownloadRoot(localRootPath = localRemoteSourcesRoot, targetRootPath = TargetPath.Temporary()) targetEnvRequest.downloadVolumes += downloadVolume pyRequest.targetEnvironmentRequest.ensureProjectSdkAndModuleDirsAreOnTarget(project) val execution = prepareHelperScriptExecution(helperPackage = PythonHelper.REMOTE_SYNC, helpersAwareTargetRequest = pyRequest) val stateFilePath = localRemoteSourcesRoot / STATE_FILE val stateFilePrevTimestamp: FileTime if (Files.exists(stateFilePath)) { stateFilePrevTimestamp = Files.getLastModifiedTime(stateFilePath) Files.copy(stateFilePath, localUploadDir / STATE_FILE) execution.addParameter("--state-file") execution.addParameter(uploadVolume.getTargetUploadPath().getRelativeTargetPath(STATE_FILE)) } else { stateFilePrevTimestamp = FileTime.from(Instant.MIN) } execution.addParameter(downloadVolume.getTargetDownloadPath()) val targetWithVfs = sdk.targetEnvConfiguration?.let { PythonInterpreterTargetEnvironmentFactory.getTargetWithMappedLocalVfs(it) } if (targetWithVfs != null) { // If sdk is target that supports local VFS, there is no reason to copy editable packages to remote_sources // since their paths should be available locally (to be edited) // Such packages are in user content roots, so we report them to remote_sync script val moduleRoots = project.modules.flatMap { it.rootManager.contentRoots.asList() }.mapNotNull { targetWithVfs.getTargetPathFromVfs(it) } if (moduleRoots.isNotEmpty()) { execution.addParameter("--project-roots") for (root in moduleRoots) { execution.addParameter(root) } } } val targetIndicator = TargetProgressIndicatorAdapter(indicator) val environment = targetEnvRequest.prepareEnvironment(targetIndicator) try { // XXX Make it automatic environment.uploadVolumes.values.forEach { it.upload(".", targetIndicator) } val cmd = execution.buildTargetedCommandLine(environment, sdk, emptyList()) cmd.execute(environment, indicator) // XXX Make it automatic environment.downloadVolumes.values.forEach { it.download(".", indicator) } } finally { environment.shutdown() } if (!Files.exists(stateFilePath)) { throw IllegalStateException("$stateFilePath is missing") } if (Files.getLastModifiedTime(stateFilePath) <= stateFilePrevTimestamp) { throw IllegalStateException("$stateFilePath has not been updated") } val stateFile: StateFile Files.newBufferedReader(stateFilePath).use { stateFile = Gson().fromJson(it, StateFile::class.java) } val pathMappings = PathMappingSettings() // Preserve mappings for paths added by user and explicitly excluded by user // We may lose these mappings otherwise (sdk.sdkAdditionalData as? PyTargetAwareAdditionalData)?.let { pyData -> (pyData.pathsAddedByUser + pyData.pathsRemovedByUser).forEach { (localPath, remotePath) -> pathMappings.add(PathMappingSettings.PathMapping(localPath.toString(), remotePath)) } } for (root in stateFile.roots) { val remoteRootPath = root.path val localRootName = remoteRootPath.hashCode().toString() val localRoot = Files.createDirectories(localRemoteSourcesRoot / localRootName) pathMappings.addMappingCheckUnique(localRoot.toString(), remoteRootPath) val rootZip = localRemoteSourcesRoot / root.zipName ZipUtil.extract(rootZip, localRoot, null, true) for (invalidEntryRelPath in root.invalidEntries) { val localInvalidEntry = localRoot / PathUtil.toSystemDependentName(invalidEntryRelPath) LOG.debug("Removing the mapped file $invalidEntryRelPath from $remoteRootPath") localInvalidEntry.deleteWithParentsIfEmpty(localRemoteSourcesRoot) } rootZip.deleteExisting() } if (targetWithVfs != null) { // If target has local VFS, we map locally available roots to VFS instead of copying them to remote_sources // See how ``updateSdkPaths`` is used for (remoteRoot in stateFile.skippedRoots) { val localPath = targetWithVfs.getVfsFromTargetPath(remoteRoot)?.path ?: continue pathMappings.add(PathMappingSettings.PathMapping(localPath, remoteRoot)) } } (sdk.sdkAdditionalData as? RemoteSdkProperties)?.setPathMappings(pathMappings) val fs = LocalFileSystem.getInstance() // "remote_sources" folder may now contain new packages // since we copied them there not via VFS, we must refresh it, so Intellij knows about them pathMappings.pathMappings.mapNotNull { fs.findFileByPath(it.localRoot) }.forEach { it.refresh(false, true) } } private class StateFile { var roots: List<RootInfo> = emptyList() @SerializedName("skipped_roots") var skippedRoots: List<String> = emptyList() } private class RootInfo { var path: String = "" @SerializedName("zip_name") var zipName: String = "" @SerializedName("invalid_entries") var invalidEntries: List<String> = emptyList() override fun toString(): String = path } companion object { val LOG = logger<PyTargetsRemoteSourcesRefresher>() } }
apache-2.0
54b87946fd26413c290de2f673bd496c
42.55914
140
0.767465
4.834129
false
false
false
false
WataruSuzuki/Now-Slack-Android
mobile/src/main/java/jp/co/devjchankchan/now_slack_android/fragments/content/SlackContent.kt
1
1395
package jp.co.devjchankchan.now_slack_android.fragments.content import android.content.Context import java.util.ArrayList import java.util.HashMap class SlackContent(context: Context) { private var myContext = context val ITEMS: MutableList<SlackMenuItem> = ArrayList() val ITEM_MAP: MutableMap<SlackMenus, SlackMenuItem> = HashMap() private val COUNT = SlackMenus.values().size init { for (i in 0 until COUNT) { addItem(createItem(i)) } } private fun addItem(item: SlackMenuItem) { ITEMS.add(item) ITEM_MAP.put(item.id, item) } private fun createItem(position: Int): SlackMenuItem = SlackMenuItem(SlackMenus.values().get(position), makeDetails(position)) private fun makeDetails(position: Int): String { val menu = SlackMenus.values().get(position) return myContext.getString(menu.stringId) } class SlackMenuItem(val id: SlackMenus, val content: String) { override fun toString(): String = content } enum class SlackMenus(val stringId: Int) { AUTH(jp.co.devjchankchan.physicalbotlibrary.R.string.authentication), EMOJI_LIST(jp.co.devjchankchan.physicalbotlibrary.R.string.emoji_list), SET_EMOJI(jp.co.devjchankchan.physicalbotlibrary.R.string.set_emoji), LOG_OUT(jp.co.devjchankchan.physicalbotlibrary.R.string.log_out) } }
apache-2.0
fed7321aec1f55357466ae9f76162ccb
31.44186
130
0.696057
3.985714
false
false
false
false
RayBa82/DVBViewerController
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/base/BaseListFragment.kt
1
15836
/* * Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.base import android.annotation.SuppressLint import android.graphics.PorterDuff import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.* import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.ContextCompat import org.dvbviewer.controller.R import org.dvbviewer.controller.data.api.io.exception.AuthenticationException import org.dvbviewer.controller.data.api.io.exception.DefaultHttpException import org.xml.sax.SAXException /** * Class to mimic API of ListActivity for Fragments * * @author RayBa */ /** * Instantiates a new base list fragment. */ open class BaseListFragment : BaseFragment() { private val mHandler = Handler() private val mRequestFocus = Runnable { mList!!.focusableViewAvailable(mList) } private val mOnClickListener = AdapterView.OnItemClickListener { parent, v, position, id -> onListItemClick(parent as ListView, v, position, id) } private var mAdapter: ListAdapter? = null private var mList: ListView? = null private var mEmptyView: View? = null private var mStandardEmptyView: AppCompatTextView? = null private var mProgressContainer: View? = null private var mListContainer: View? = null private var mEmptyText: CharSequence? = null private var mListShown: Boolean = false private val handler: Handler = Handler(Looper.getMainLooper()) /** * Get the activity's list view widget. * * @return the list view */ val listView: ListView? get() { ensureList() return mList } /** * Get the ListAdapter associated with this activity's ListView. * * @return the list adapter */ /** * Provide the mCursor for the list view. * * @param adapter the new list adapter */ // The list was hidden, and previously didn't have an // adapter. It is now time to show it. var listAdapter: ListAdapter? get() = mAdapter set(adapter) { val hadAdapter = mAdapter != null mAdapter = adapter if (mList != null) { mList?.adapter = adapter if (!mListShown && !hadAdapter) { setListShown(true, view != null && view!!.windowToken != null) } } } /** * Possibility for sublasses to provide a custom layout ressource. * * @return the layout resource id */ protected open val layoutRessource: Int get() = -1 /** * Gets the checked item count. * * @return the checked item count */ val checkedItemCount: Int get() { var count = 0 val checkedPositions = listView!!.checkedItemPositions if (checkedPositions != null) { val size = checkedPositions.size() if (size > 0) { for (i in 0 until size) { if (checkedPositions.valueAt(i)) { count++ } } } } return count } /** * Provide default implementation to return a simple list view. Subclasses * can override to replace with their own layout. If doing so, the * returned view hierarchy *must* have a ListView whose id * is [android.R.id.list] and can optionally * have a sibling view id [android.R.id.empty] * that is to be shown when the list is empty. * * * If you are overriding this method with your own custom content, * consider including the standard layout [android.R.layout.list_content] * in your layout file, so that you continue to retain all of the standard * behavior of ListFragment. In particular, this is currently the only * way to have the built-in indeterminant progress state be shown. * * @param inflater the inflater * @param container the container * @param savedInstanceState the saved instance state * @return the view© */ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val layoutRes = layoutRessource if (layoutRes > 0) { return inflater.inflate(layoutRes, container, false) } else { val context = context val root = FrameLayout(context!!) // ------------------------------------------------------------------ val pframe = LinearLayout(context) pframe.id = INTERNAL_PROGRESS_CONTAINER_ID pframe.orientation = LinearLayout.VERTICAL pframe.visibility = View.GONE pframe.gravity = Gravity.CENTER val progress = ProgressBar(context) getContext()?.let { ContextCompat.getColor(it, R.color.colorControlActivated) }?.let { progress.indeterminateDrawable .setColorFilter(it, PorterDuff.Mode.SRC_IN) } pframe.addView(progress, FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)) root.addView(pframe, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) // ------------------------------------------------------------------ val lframe = FrameLayout(context) lframe.id = INTERNAL_LIST_CONTAINER_ID val tv = AppCompatTextView(context) tv.id = INTERNAL_EMPTY_ID tv.gravity = Gravity.CENTER tv.setPadding(15, 0, 15, 0) lframe.addView(tv, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) val lv = ListView(context) lv.id = android.R.id.list lv.isDrawSelectorOnTop = false lframe.addView(lv, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) root.addView(lframe, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) // ------------------------------------------------------------------ root.layoutParams = FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) return root } } /** * Attach to list view once the view hierarchy has been created. * * @param view the view * @param savedInstanceState the saved instance state */ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ensureList() } /** * Detach from list view. */ override fun onDestroyView() { mHandler.removeCallbacks(mRequestFocus) mList = null mListShown = false mListContainer = null mProgressContainer = mListContainer mEmptyView = mProgressContainer mStandardEmptyView = null super.onDestroyView() } /** * This method will be called when an item in the list is selected. * Subclasses should override. Subclasses can call * getListView().getItemAtPosition(position) if they need to access the * data associated with the selected item. * * @param l The ListView where the click happened * @param v The view that was clicked within the ListView * @param position The position of the view in the list * @param id The row id of the item that was clicked */ open fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {} /** * Set the currently selected list item to the specified * position with the adapter's data. * * @param position the new selection */ @SuppressLint("NewApi") open fun setSelection(position: Int) { try { ensureList() } catch (e: Exception) { return } mList?.setSelection(position) } /** * The default content for a ListFragment has a TextView that can * be shown when the list is empty. If you would like to have it * shown, call this method to supply the text it should use. * * @param text the new empty text */ fun setEmptyText(text: CharSequence?) { if (text == null) { return } ensureList() if (mStandardEmptyView != null) { mStandardEmptyView!!.text = text if (mEmptyText == null) { mList!!.emptyView = mStandardEmptyView } } mEmptyText = text } /** * Control whether the list is being displayed. You can make it not * displayed if you are waiting for the initial data to show in it. During * this time an indeterminant progress indicator will be shown instead. * * * Applications do not normally need to use this themselves. The default * behavior of ListFragment is to start with the list not being shown, only * showing it once an adapter is given with [.setListAdapter]. * If the list at that point had not been shown, when it does get shown * it will be do without the user ever seeing the hidden state. * * @param shown If true, the list view is shown; if false, the progress * indicator. The initial value is true. */ fun setListShown(shown: Boolean) { setListShown(shown, true) } /** * Control whether the list is being displayed. You can make it not * displayed if you are waiting for the initial data to show in it. During * this time an indeterminant progress indicator will be shown instead. * * @param shown If true, the list view is shown; if false, the progress * indicator. The initial value is true. * @param animate If true, an animation will be used to transition to the * new state. */ private fun setListShown(shown: Boolean, animate: Boolean) { try { ensureList() } catch (e: Exception) { return } if (mProgressContainer == null) { throw IllegalStateException("Can't be used with a custom content view") } if (mListShown == shown) { return } mListShown = shown if (shown) { if (animate) { mProgressContainer!!.startAnimation(AnimationUtils.loadAnimation( context, android.R.anim.fade_out)) mListContainer!!.startAnimation(AnimationUtils.loadAnimation( context, android.R.anim.fade_in)) } else { mProgressContainer!!.clearAnimation() mListContainer!!.clearAnimation() } mProgressContainer!!.visibility = View.GONE mListContainer!!.visibility = View.VISIBLE } else { if (animate) { mProgressContainer!!.startAnimation(AnimationUtils.loadAnimation( context, android.R.anim.fade_in)) mListContainer!!.startAnimation(AnimationUtils.loadAnimation( context, android.R.anim.fade_out)) } else { mProgressContainer!!.clearAnimation() mListContainer!!.clearAnimation() } mProgressContainer!!.visibility = View.VISIBLE mListContainer!!.visibility = View.GONE } } /** * Ensure list. * */ private fun ensureList() { if (mList != null) { return } val root = view ?: throw IllegalStateException("Content view not yet created") if (root is ListView) { mList = root } else { mStandardEmptyView = root.findViewById<View>(INTERNAL_EMPTY_ID) as AppCompatTextView if (mStandardEmptyView == null) { mEmptyView = root.findViewById(android.R.id.empty) } else { mStandardEmptyView!!.visibility = View.GONE } mProgressContainer = root.findViewById(INTERNAL_PROGRESS_CONTAINER_ID) mListContainer = root.findViewById(INTERNAL_LIST_CONTAINER_ID) val rawListView = root.findViewById<View>(android.R.id.list) if (rawListView !is ListView) { if (rawListView == null) { throw RuntimeException( "Your content must have a ListView whose id attribute is " + "'android.R.id.list'") } throw RuntimeException( "Content has view with id attribute 'android.R.id.list' " + "that is not a ListView class") } mList = rawListView if (mEmptyView != null) { mList!!.emptyView = mEmptyView } else if (mEmptyText != null) { mStandardEmptyView!!.text = mEmptyText mList!!.emptyView = mStandardEmptyView } } mListShown = true mList!!.onItemClickListener = mOnClickListener if (mAdapter != null) { val adapter = mAdapter mAdapter = null listAdapter = adapter } else { // We are starting without an adapter, so assume we won't // have our data right away and start with the progress indicator. if (mProgressContainer != null) { setListShown(shown = false, animate = false) } } mHandler.post(mRequestFocus) } /** * Generic method to catch an Exception. * It shows a toast to inform the user. * This method is safe to be called from non UI threads. * * @param tag for logging * @param e the Excetpion to catch */ override fun catchException(tag: String, e: Throwable?) { if (context == null || isDetached) { return } Log.e(tag, "Error loading ListData", e) val message = when (e) { is AuthenticationException -> getString(R.string.error_invalid_credentials) is DefaultHttpException -> e.message is SAXException -> getString(R.string.error_parsing_xml) else -> getStringSafely(R.string.error_common) + "\n\n" + if (e?.message != null) e.message else e?.javaClass?.name } handler.post { message?.let { setEmptyText(it) } } } companion object { private const val INTERNAL_EMPTY_ID = android.R.id.empty private const val INTERNAL_PROGRESS_CONTAINER_ID = android.R.id.progress private const val INTERNAL_LIST_CONTAINER_ID = android.R.id.content } }
apache-2.0
a4c827e0f56db66a86c7ae54d7eee663
35.152968
150
0.597006
5.052329
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/ClangIndex.kt
4
210835
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package llvm.templates import llvm.* import org.lwjgl.generator.* val ClangIndex = "ClangIndex".nativeClass( Module.LLVM, prefixConstant = "CX", prefixMethod = "clang_", binding = CLANG_BINDING ) { nativeImport("clang-c/Index.h") IntConstant( "", "CINDEX_VERSION_MAJOR".."0", "CINDEX_VERSION_MINOR".."62", "CINDEX_VERSION".."CINDEX_VERSION_MAJOR*10000 + CINDEX_VERSION_MINOR" ).noPrefix() StringConstant( "", "CINDEX_VERSION_STRING".."0.62" ).noPrefix() EnumConstant( """ Error codes returned by libclang routines. ({@code enum CXErrorCode}) Zero ({@code CXError_Success}) is the only error code indicating success. Other error codes, including not yet assigned non-zero values, indicate errors. """, "Error_Success".enum("No error.", "0"), "Error_Failure".enum( """ A generic error code, no further details are available. Errors of this kind can get their own specific error codes in future libclang versions. """ ), "Error_Crashed".enum("libclang crashed while performing the requested operation."), "Error_InvalidArguments".enum("The function detected that the arguments violate the function contract."), "Error_ASTReadError".enum("An AST deserialization error has occurred.") ) EnumConstant( """ Describes the availability of a particular entity, which indicates whether the use of this entity will result in a warning or error due to it being deprecated or unavailable. ({@code enum CXAvailabilityKind}) """, "Availability_Available".enum("The entity is available.", "0"), "Availability_Deprecated".enum("The entity is available, but has been deprecated (and its use is not recommended)."), "Availability_NotAvailable".enum("The entity is not available; any use of it will be an error."), "Availability_NotAccessible".enum("The entity is available, but not accessible; any use of it will be an error.") ) EnumConstant( """ Describes the exception specification of a cursor. ({@code enum CXCursor_ExceptionSpecificationKind}) A negative value indicates that the cursor is not a function declaration. """, "Cursor_ExceptionSpecificationKind_None".enum("The cursor has no exception specification.", "0"), "Cursor_ExceptionSpecificationKind_DynamicNone".enum("The cursor has exception specification throw()"), "Cursor_ExceptionSpecificationKind_Dynamic".enum("The cursor has exception specification throw(T1, T2)"), "Cursor_ExceptionSpecificationKind_MSAny".enum("The cursor has exception specification throw(...)."), "Cursor_ExceptionSpecificationKind_BasicNoexcept".enum("The cursor has exception specification basic noexcept."), "Cursor_ExceptionSpecificationKind_ComputedNoexcept".enum("The cursor has exception specification computed noexcept."), "Cursor_ExceptionSpecificationKind_Unevaluated".enum("The exception specification has not yet been evaluated."), "Cursor_ExceptionSpecificationKind_Uninstantiated".enum("The exception specification has not yet been instantiated."), "Cursor_ExceptionSpecificationKind_Unparsed".enum("The exception specification has not been parsed yet."), "Cursor_ExceptionSpecificationKind_NoThrow".enum("The cursor has a {@code __declspec(nothrow)} exception specification.") ) EnumConstant( "{@code CXGlobalOptFlags}", "GlobalOpt_None".enum("Used to indicate that no special CXIndex options are needed.", "0x0"), "GlobalOpt_ThreadBackgroundPriorityForIndexing".enum( """ Used to indicate that threads that libclang creates for indexing purposes should use background priority. Affects #indexSourceFile(), #indexTranslationUnit(), #parseTranslationUnit(), #saveTranslationUnit(). """, "0x1" ), "GlobalOpt_ThreadBackgroundPriorityForEditing".enum( """ Used to indicate that threads that libclang creates for editing purposes should use background priority. Affects #reparseTranslationUnit(), #codeCompleteAt(), #annotateTokens() """, "0x2" ), "GlobalOpt_ThreadBackgroundPriorityForAll".enum( "Used to indicate that all threads that libclang creates should use background priority.", "CXGlobalOpt_ThreadBackgroundPriorityForIndexing | CXGlobalOpt_ThreadBackgroundPriorityForEditing" ) ) EnumConstant( """ Describes the severity of a particular diagnostic. ({@code enum CXDiagnosticSeverity}) """, "Diagnostic_Ignored".enum("A diagnostic that has been suppressed, e.g., by a command-line option.", "0"), "Diagnostic_Note".enum("This diagnostic is a note that should be attached to the previous (non-note) diagnostic."), "Diagnostic_Warning".enum("This diagnostic indicates suspicious code that may not be wrong."), "Diagnostic_Error".enum("This diagnostic indicates that the code is ill-formed."), "Diagnostic_Fatal".enum( "This diagnostic indicates that the code is ill-formed such that future parser recovery is unlikely to produce useful results." ) ) EnumConstant( """ Describes the kind of error that occurred (if any) in a call to {@code clang_loadDiagnostics}. ({@code enum CXLoadDiag_Error}) """, "LoadDiag_None".enum("Indicates that no error occurred.", "0"), "LoadDiag_Unknown".enum("Indicates that an unknown error occurred while attempting to deserialize diagnostics."), "LoadDiag_CannotLoad".enum("Indicates that the file containing the serialized diagnostics could not be opened."), "LoadDiag_InvalidFile".enum("Indicates that the serialized diagnostics file is invalid or corrupt.") ) EnumConstant( """ Options to control the display of diagnostics. ({@code enum CXDiagnosticDisplayOptions}) The values in this enum are meant to be combined to customize the behavior of {@code clang_formatDiagnostic()}. """, "Diagnostic_DisplaySourceLocation".enum( """ Display the source-location information where the diagnostic was located. When set, diagnostics will be prefixed by the file, line, and (optionally) column to which the diagnostic refers. For example, ${codeBlock(""" test.c:28: warning: extra tokens at end of \#endif directive""")} This option corresponds to the clang flag {@code -fshow-source-location}. """, "0x01" ), "Diagnostic_DisplayColumn".enum( """ If displaying the source-location information of the diagnostic, also include the column number. This option corresponds to the clang flag {@code -fshow-column}. """, "0x02" ), "Diagnostic_DisplaySourceRanges".enum( """ If displaying the source-location information of the diagnostic, also include information about source ranges in a machine-parsable format. This option corresponds to the clang flag {@code -fdiagnostics-print-source-range-info}. """, "0x04" ), "Diagnostic_DisplayOption".enum( """ Display the option name associated with this diagnostic, if any. The option name displayed (e.g., -Wconversion) will be placed in brackets after the diagnostic text. This option corresponds to the clang flag {@code -fdiagnostics-show-option}. """, "0x08" ), "Diagnostic_DisplayCategoryId".enum( """ Display the category number associated with this diagnostic, if any. The category number is displayed within brackets after the diagnostic text. This option corresponds to the clang flag {@code -fdiagnostics-show-category=id}. """, "0x10" ), "Diagnostic_DisplayCategoryName".enum( """ Display the category name associated with this diagnostic, if any. The category name is displayed within brackets after the diagnostic text. This option corresponds to the clang flag {@code -fdiagnostics-show-category=name}. """, "0x20" ) ) EnumConstant( """ Flags that control the creation of translation units. ({@code enum CXTranslationUnit_Flags}) The enumerators in this enumeration type are meant to be bitwise ORed together to specify which options should be used when constructing the translation unit. """, "TranslationUnit_None".enum("Used to indicate that no special translation-unit options are needed.", "0x0"), "TranslationUnit_DetailedPreprocessingRecord".enum( """ Used to indicate that the parser should construct a "detailed" preprocessing record, including all macro definitions and instantiations. Constructing a detailed preprocessing record requires more memory and time to parse, since the information contained in the record is usually not retained. However, it can be useful for applications that require more detailed information about the behavior of the preprocessor. """, "0x01" ), "TranslationUnit_Incomplete".enum( """ Used to indicate that the translation unit is incomplete. When a translation unit is considered "incomplete", semantic analysis that is typically performed at the end of the translation unit will be suppressed. For example, this suppresses the completion of tentative declarations in C and of instantiation of implicitly-instantiation function templates in C++. This option is typically used when parsing a header with the intent of producing a precompiled header. """, "0x02" ), "TranslationUnit_PrecompiledPreamble".enum( """ Used to indicate that the translation unit should be built with an implicit precompiled header for the preamble. An implicit precompiled header is used as an optimization when a particular translation unit is likely to be reparsed many times when the sources aren't changing that often. In this case, an implicit precompiled header will be built containing all of the initial includes at the top of the main file (what we refer to as the "preamble" of the file). In subsequent parses, if the preamble or the files in it have not changed, {@code clang_reparseTranslationUnit()} will re-use the implicit precompiled header to improve parsing performance. """, "0x04" ), "TranslationUnit_CacheCompletionResults".enum( """ Used to indicate that the translation unit should cache some code-completion results with each reparse of the source file. Caching of code-completion results is a performance optimization that introduces some overhead to reparsing but improves the performance of code-completion operations. """, "0x08" ), "TranslationUnit_ForSerialization".enum( """ Used to indicate that the translation unit will be serialized with {@code clang_saveTranslationUnit}. This option is typically used when parsing a header with the intent of producing a precompiled header. """, "0x10" ), "TranslationUnit_CXXChainedPCH".enum( """ DEPRECATED: Enabled chained precompiled preambles in C++. Note: this is a *temporary* option that is available only while we are testing C++ precompiled preamble support. It is deprecated. """, "0x20" ), "TranslationUnit_SkipFunctionBodies".enum( """ Used to indicate that function/method bodies should be skipped while parsing. This option can be used to search for declarations/definitions while ignoring the usages. """, "0x40" ), "TranslationUnit_IncludeBriefCommentsInCodeCompletion".enum( "Used to indicate that brief documentation comments should be included into the set of code completions returned from this translation unit.", "0x80" ), "TranslationUnit_CreatePreambleOnFirstParse".enum( """ Used to indicate that the precompiled preamble should be created on the first parse. Otherwise it will be created on the first reparse. This trades runtime on the first parse (serializing the preamble takes time) for reduced runtime on the second parse (can now reuse the preamble). """, "0x100" ), "TranslationUnit_KeepGoing".enum( """ Do not stop processing when fatal errors are encountered. When fatal errors are encountered while parsing a translation unit, semantic analysis is typically stopped early when compiling code. A common source for fatal errors are unresolvable include files. For the purposes of an IDE, this is undesirable behavior and as much information as possible should be reported. Use this flag to enable this behavior. """, "0x200" ), "TranslationUnit_SingleFileParse".enum("Sets the preprocessor in a mode for parsing a single file only.", "0x400"), "TranslationUnit_LimitSkipFunctionBodiesToPreamble".enum( """ Used in combination with CXTranslationUnit_SkipFunctionBodies to constrain the skipping of function bodies to the preamble. The function bodies of the main file are not skipped. """, "0x800" ), "TranslationUnit_IncludeAttributedTypes".enum("Used to indicate that attributed types should be included in CXType.", "0x1000"), "TranslationUnit_VisitImplicitAttributes".enum("Used to indicate that implicit attributes should be visited.", "0x2000"), "TranslationUnit_IgnoreNonErrorsFromIncludedFiles".enum( """ Used to indicate that non-errors from included files should be ignored. If set, #getDiagnosticSetFromTU() will not report e.g. warnings from included files anymore. This speeds up {@code clang_getDiagnosticSetFromTU()} for the case where these warnings are not of interest, as for an IDE for example, which typically shows only the diagnostics in the main file. """, "0x4000" ), "TranslationUnit_RetainExcludedConditionalBlocks".enum("Tells the preprocessor not to skip excluded conditional blocks.", "0x8000") ) EnumConstant( """ Flags that control how translation units are saved. ({@code enum CXSaveTranslationUnit_Flags}) The enumerators in this enumeration type are meant to be bitwise ORed together to specify which options should be used when saving the translation unit. """, "SaveTranslationUnit_None".enum("Used to indicate that no special saving options are needed.", "0x0") ) EnumConstant( """ Describes the kind of error that occurred (if any) in a call to {@code clang_saveTranslationUnit()}. ({@code enum CXSaveError}) """, "SaveError_None".enum("Indicates that no error occurred while saving a translation unit.", "0"), "SaveError_Unknown".enum( """ Indicates that an unknown error occurred while attempting to save the file. This error typically indicates that file I/O failed when attempting to write the file. """ ), "SaveError_TranslationErrors".enum( """ Indicates that errors during translation prevented this attempt to save the translation unit. Errors that prevent the translation unit from being saved can be extracted using {@code clang_getNumDiagnostics()} and {@code clang_getDiagnostic()}. """ ), "SaveError_InvalidTU".enum("Indicates that the translation unit to be saved was somehow invalid (e.g., #NULL).") ) EnumConstant( """ Flags that control the reparsing of translation units. ({@code enum CXReparse_Flags}) The enumerators in this enumeration type are meant to be bitwise ORed together to specify which options should be used when reparsing the translation unit. """, "Reparse_None".enum("Used to indicate that no special reparsing options are needed.", "0x0") ) EnumConstant( """ Categorizes how memory is being used by a translation unit. ({@code enum CXTUResourceUsageKind}) """, "TUResourceUsage_AST".enum("", "1"), "TUResourceUsage_Identifiers".enum, "TUResourceUsage_Selectors".enum, "TUResourceUsage_GlobalCompletionResults".enum, "TUResourceUsage_SourceManagerContentCache".enum, "TUResourceUsage_AST_SideTables".enum, "TUResourceUsage_SourceManager_Membuffer_Malloc".enum, "TUResourceUsage_SourceManager_Membuffer_MMap".enum, "TUResourceUsage_ExternalASTSource_Membuffer_Malloc".enum, "TUResourceUsage_ExternalASTSource_Membuffer_MMap".enum, "TUResourceUsage_Preprocessor".enum, "TUResourceUsage_PreprocessingRecord".enum, "TUResourceUsage_SourceManager_DataStructures".enum, "TUResourceUsage_Preprocessor_HeaderSearch".enum, "TUResourceUsage_MEMORY_IN_BYTES_BEGIN".enum("", "CXTUResourceUsage_AST"), "TUResourceUsage_MEMORY_IN_BYTES_END".enum("", "CXTUResourceUsage_Preprocessor_HeaderSearch"), "TUResourceUsage_First".enum("", "CXTUResourceUsage_AST"), "TUResourceUsage_Last".enum("", "CXTUResourceUsage_Preprocessor_HeaderSearch") ) EnumConstant( """ Describes the kind of entity that a cursor refers to. ({@code enum CXCursorKind}) """, "Cursor_UnexposedDecl".enum( """ Declarations A declaration whose specific kind is not exposed via this interface. Unexposed declarations have the same operations as any other kind of declaration; one can extract their location information, spelling, find their definitions, etc. However, the specific kind of the declaration is not reported. """, "1" ), "Cursor_StructDecl".enum("A C or C++ struct."), "Cursor_UnionDecl".enum("A C or C++ union."), "Cursor_ClassDecl".enum("A C++ class."), "Cursor_EnumDecl".enum("An enumeration."), "Cursor_FieldDecl".enum("A field (in C) or non-static data member (in C++) in a struct, union, or C++ class."), "Cursor_EnumConstantDecl".enum("An enumerator constant."), "Cursor_FunctionDecl".enum("A function."), "Cursor_VarDecl".enum("A variable."), "Cursor_ParmDecl".enum("A function or method parameter."), "Cursor_ObjCInterfaceDecl".enum("An Objective-C @ interface."), "Cursor_ObjCCategoryDecl".enum("An Objective-C @ interface for a category."), "Cursor_ObjCProtocolDecl".enum("An Objective-C @ protocol declaration."), "Cursor_ObjCPropertyDecl".enum("An Objective-C @ property declaration."), "Cursor_ObjCIvarDecl".enum("An Objective-C instance variable."), "Cursor_ObjCInstanceMethodDecl".enum("An Objective-C instance method."), "Cursor_ObjCClassMethodDecl".enum("An Objective-C class method."), "Cursor_ObjCImplementationDecl".enum("An Objective-C @ implementation."), "Cursor_ObjCCategoryImplDecl".enum("An Objective-C @ implementation for a category."), "Cursor_TypedefDecl".enum("A typedef."), "Cursor_CXXMethod".enum("A C++ class method."), "Cursor_Namespace".enum("A C++ namespace."), "Cursor_LinkageSpec".enum("A linkage specification, e.g. 'extern \"C\"'."), "Cursor_Constructor".enum("A C++ constructor."), "Cursor_Destructor".enum("A C++ destructor."), "Cursor_ConversionFunction".enum("A C++ conversion function."), "Cursor_TemplateTypeParameter".enum("A C++ template type parameter."), "Cursor_NonTypeTemplateParameter".enum("A C++ non-type template parameter."), "Cursor_TemplateTemplateParameter".enum("A C++ template template parameter."), "Cursor_FunctionTemplate".enum("A C++ function template."), "Cursor_ClassTemplate".enum("A C++ class template."), "Cursor_ClassTemplatePartialSpecialization".enum("A C++ class template partial specialization."), "Cursor_NamespaceAlias".enum("A C++ namespace alias declaration."), "Cursor_UsingDirective".enum("A C++ using directive."), "Cursor_UsingDeclaration".enum("A C++ using declaration."), "Cursor_TypeAliasDecl".enum("A C++ alias declaration"), "Cursor_ObjCSynthesizeDecl".enum("An Objective-C @ synthesize definition."), "Cursor_ObjCDynamicDecl".enum("An Objective-C @ dynamic definition."), "Cursor_CXXAccessSpecifier".enum("An access specifier."), "Cursor_FirstDecl".enum("An access specifier.", "CXCursor_UnexposedDecl"), "Cursor_LastDecl".enum("An access specifier.", "CXCursor_CXXAccessSpecifier"), "Cursor_FirstRef".enum("Decl references", "40"), "Cursor_ObjCSuperClassRef".enum("", "40"), "Cursor_ObjCProtocolRef".enum, "Cursor_ObjCClassRef".enum, "Cursor_TypeRef".enum( """ A reference to a type declaration. A type reference occurs anywhere where a type is named but not declared. For example, given: ${codeBlock(""" typedef unsigned size_type; size_type size;""")} The typedef is a declaration of size_type (CXCursor_TypedefDecl), while the type of the variable "size" is referenced. The cursor referenced by the type of size is the typedef for size_type. """ ), "Cursor_CXXBaseSpecifier".enum( """ A reference to a type declaration. A type reference occurs anywhere where a type is named but not declared. For example, given: ${codeBlock(""" typedef unsigned size_type; size_type size;""")} The typedef is a declaration of size_type (CXCursor_TypedefDecl), while the type of the variable "size" is referenced. The cursor referenced by the type of size is the typedef for size_type. """ ), "Cursor_TemplateRef".enum( "A reference to a class template, function template, template template parameter, or class template partial specialization." ), "Cursor_NamespaceRef".enum("A reference to a namespace or namespace alias."), "Cursor_MemberRef".enum( "A reference to a member of a struct, union, or class that occurs in some non-expression context, e.g., a designated initializer." ), "Cursor_LabelRef".enum( """ A reference to a labeled statement. This cursor kind is used to describe the jump to "start_over" in the goto statement in the following example: ${codeBlock(""" start_over: ++counter; goto start_over;""")} A label reference cursor refers to a label statement. """ ), "Cursor_OverloadedDeclRef".enum( """ A reference to a set of overloaded functions or function templates that has not yet been resolved to a specific function or function template. An overloaded declaration reference cursor occurs in C++ templates where a dependent name refers to a function. For example: ${codeBlock(""" template<typename T> void swap(T&, T&); struct X { ... }; void swap(X&, X&); template<typename T> void reverse(T* first, T* last) { while (first < last - 1) { swap(*first, *--last); ++first; } } struct Y { }; void swap(Y&, Y&);""")} Here, the identifier "swap" is associated with an overloaded declaration reference. In the template definition, "swap" refers to either of the two "swap" functions declared above, so both results will be available. At instantiation time, "swap" may also refer to other functions found via argument-dependent lookup (e.g., the "swap" function at the end of the example). The functions {@code clang_getNumOverloadedDecls()} and {@code clang_getOverloadedDecl()} can be used to retrieve the definitions referenced by this cursor. """ ), "Cursor_VariableRef".enum("A reference to a variable that occurs in some non-expression context, e.g., a C++ lambda capture list."), "Cursor_LastRef".enum( "A reference to a variable that occurs in some non-expression context, e.g., a C++ lambda capture list.", "CXCursor_VariableRef" ), "Cursor_FirstInvalid".enum("Error conditions", "70"), "Cursor_InvalidFile".enum("Error conditions", "70"), "Cursor_NoDeclFound".enum("Error conditions"), "Cursor_NotImplemented".enum("Error conditions"), "Cursor_InvalidCode".enum("Error conditions"), "Cursor_LastInvalid".enum("Error conditions", "CXCursor_InvalidCode"), "Cursor_FirstExpr".enum("Expressions", "100"), "Cursor_UnexposedExpr".enum( """ An expression whose specific kind is not exposed via this interface. Unexposed expressions have the same operations as any other kind of expression; one can extract their location information, spelling, children, etc. However, the specific kind of the expression is not reported. """, "100" ), "Cursor_DeclRefExpr".enum("An expression that refers to some value declaration, such as a function, variable, or enumerator."), "Cursor_MemberRefExpr".enum("An expression that refers to a member of a struct, union, class, Objective-C class, etc."), "Cursor_CallExpr".enum("An expression that calls a function."), "Cursor_ObjCMessageExpr".enum("An expression that sends a message to an Objective-C object or class."), "Cursor_BlockExpr".enum("An expression that represents a block literal."), "Cursor_IntegerLiteral".enum("An integer literal."), "Cursor_FloatingLiteral".enum("A floating point number literal."), "Cursor_ImaginaryLiteral".enum("An imaginary number literal."), "Cursor_StringLiteral".enum("A string literal."), "Cursor_CharacterLiteral".enum("A character literal."), "Cursor_ParenExpr".enum( """ A parenthesized expression, e.g. "(1)". This AST node is only formed if full location information is requested. """ ), "Cursor_UnaryOperator".enum("This represents the unary-expression's (except sizeof and alignof)."), "Cursor_ArraySubscriptExpr".enum("[C99 6.5.2.1] Array Subscripting."), "Cursor_BinaryOperator".enum("A builtin binary operation expression such as \"x + y\" or \"x &lt;= y\"."), "Cursor_CompoundAssignOperator".enum("Compound assignment such as \"+=\"."), "Cursor_ConditionalOperator".enum("The ?: ternary operator."), "Cursor_CStyleCastExpr".enum( """ An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr. For example: (int)f. """ ), "Cursor_CompoundLiteralExpr".enum("[C99 6.5.2.5]"), "Cursor_InitListExpr".enum("Describes an C or C++ initializer list."), "Cursor_AddrLabelExpr".enum("The GNU address of label extension, representing {@code &&label}."), "Cursor_StmtExpr".enum("This is the GNU Statement Expression extension: ({int X=4; X;})"), "Cursor_GenericSelectionExpr".enum("Represents a C11 generic selection."), "Cursor_GNUNullExpr".enum( """ Implements the GNU __null extension, which is a name for a null pointer constant that has integral type (e.g., int or long) and is the same size and alignment as a pointer. The __null extension is typically only used by system headers, which define #NULL as __null in C++ rather than using 0 (which is an integer that may not match the size of a pointer). """ ), "Cursor_CXXStaticCastExpr".enum("C++'s static_cast &lt;&gt; expression."), "Cursor_CXXDynamicCastExpr".enum("C++'s dynamic_cast &lt;&gt; expression."), "Cursor_CXXReinterpretCastExpr".enum("C++'s reinterpret_cast &lt;&gt; expression."), "Cursor_CXXConstCastExpr".enum("C++'s const_cast &lt;&gt; expression."), "Cursor_CXXFunctionalCastExpr".enum( """ Represents an explicit C++ type conversion that uses "functional" notion (C++ [expr.type.conv]). Example: ${codeBlock(""" x = int(0.5);""")} """ ), "Cursor_CXXTypeidExpr".enum("A C++ typeid expression (C++ [expr.typeid])."), "Cursor_CXXBoolLiteralExpr".enum("[C++ 2.13.5] C++ Boolean Literal."), "Cursor_CXXNullPtrLiteralExpr".enum("[C++0x 2.14.7] C++ Pointer Literal."), "Cursor_CXXThisExpr".enum("Represents the \"this\" expression in C++"), "Cursor_CXXThrowExpr".enum( """ [C++ 15] C++ Throw Expression. This handles 'throw' and 'throw' assignment-expression. When assignment-expression isn't present, Op will be null. """ ), "Cursor_CXXNewExpr".enum("A new expression for memory allocation and constructor calls, e.g: \"new CXXNewExpr(foo)\"."), "Cursor_CXXDeleteExpr".enum("A delete expression for memory deallocation and destructor calls, e.g. \"delete[] pArray\"."), "Cursor_UnaryExpr".enum("A unary expression. (noexcept, sizeof, or other traits)"), "Cursor_ObjCStringLiteral".enum("An Objective-C string literal i.e. \" foo\"."), "Cursor_ObjCEncodeExpr".enum("An Objective-C @ encode expression."), "Cursor_ObjCSelectorExpr".enum("An Objective-C @ selector expression."), "Cursor_ObjCProtocolExpr".enum("An Objective-C @ protocol expression."), "Cursor_ObjCBridgedCastExpr".enum( """ An Objective-C "bridged" cast expression, which casts between Objective-C pointers and C pointers, transferring ownership in the process. ${codeBlock(""" NSString *str = (__bridge_transfer NSString *)CFCreateString();""")} """ ), "Cursor_PackExpansionExpr".enum( """ Represents a C++0x pack expansion that produces a sequence of expressions. A pack expansion expression contains a pattern (which itself is an expression) followed by an ellipsis. For example: ${codeBlock(""" template<typename F, typename ...Types> void forward(F f, Types &&...args) { f(static_cast<Types&&>(args)...); }""")} """ ), "Cursor_SizeOfPackExpr".enum( """ Represents an expression that computes the length of a parameter pack. ${codeBlock(""" template<typename ...Types> struct count { static const unsigned value = sizeof...(Types); };""")} """ ), "Cursor_LambdaExpr".enum( """ Represents a C++ lambda expression that produces a local function object. ${codeBlock(""" void abssort(float *x, unsigned N) { std::sort(x, x + N, [](float a, float b) { return std::abs(a) < std::abs(b); }); }""")} """ ), "Cursor_ObjCBoolLiteralExpr".enum("Objective-c Boolean Literal."), "Cursor_ObjCSelfExpr".enum("Represents the \"self\" expression in an Objective-C method."), "Cursor_OMPArraySectionExpr".enum("OpenMP 5.0 [2.1.5, Array Section]."), "Cursor_ObjCAvailabilityCheckExpr".enum("Represents an {@code @available (...)} check."), "Cursor_FixedPointLiteral".enum("Fixed point literal"), "Cursor_OMPArrayShapingExpr".enum("OpenMP 5.0 [2.1.4, Array Shaping]."), "Cursor_OMPIteratorExpr".enum("OpenMP 5.0 [2.1.6 Iterators]"), "Cursor_CXXAddrspaceCastExpr".enum("OpenCL's {@code addrspace_cast<>} expression."), "Cursor_LastExpr".enum("", "CXCursor_CXXAddrspaceCastExpr"), "Cursor_FirstStmt".enum("Statements", "200"), "Cursor_UnexposedStmt".enum( """ A statement whose specific kind is not exposed via this interface. Unexposed statements have the same operations as any other kind of statement; one can extract their location information, spelling, children, etc. However, the specific kind of the statement is not reported. """, "200" ), "Cursor_LabelStmt".enum( """ A labelled statement in a function. This cursor kind is used to describe the "start_over:" label statement in the following example: ${codeBlock(""" start_over: ++counter;""")} """ ), "Cursor_CompoundStmt".enum( """ A group of statements like { stmt stmt }. This cursor kind is used to describe compound statements, e.g. function bodies. """ ), "Cursor_CaseStmt".enum("A case statement."), "Cursor_DefaultStmt".enum("A default statement."), "Cursor_IfStmt".enum("An if statement"), "Cursor_SwitchStmt".enum("A switch statement."), "Cursor_WhileStmt".enum("A while statement."), "Cursor_DoStmt".enum("A do statement."), "Cursor_ForStmt".enum("A for statement."), "Cursor_GotoStmt".enum("A goto statement."), "Cursor_IndirectGotoStmt".enum("An indirect goto statement."), "Cursor_ContinueStmt".enum("A continue statement."), "Cursor_BreakStmt".enum("A break statement."), "Cursor_ReturnStmt".enum("A return statement."), "Cursor_GCCAsmStmt".enum("A GCC inline assembly statement extension."), "Cursor_AsmStmt".enum("A GCC inline assembly statement extension.", "CXCursor_GCCAsmStmt"), "Cursor_ObjCAtTryStmt".enum("Objective-C's overall @ try- @ catch- @ finally statement.", "216"), "Cursor_ObjCAtCatchStmt".enum("Objective-C's @ catch statement."), "Cursor_ObjCAtFinallyStmt".enum("Objective-C's @ finally statement."), "Cursor_ObjCAtThrowStmt".enum("Objective-C's @ throw statement."), "Cursor_ObjCAtSynchronizedStmt".enum("Objective-C's @ synchronized statement."), "Cursor_ObjCAutoreleasePoolStmt".enum("Objective-C's autorelease pool statement."), "Cursor_ObjCForCollectionStmt".enum("Objective-C's collection statement."), "Cursor_CXXCatchStmt".enum("C++'s catch statement."), "Cursor_CXXTryStmt".enum("C++'s try statement."), "Cursor_CXXForRangeStmt".enum("C++'s for (* : *) statement."), "Cursor_SEHTryStmt".enum("Windows Structured Exception Handling's try statement."), "Cursor_SEHExceptStmt".enum("Windows Structured Exception Handling's except statement."), "Cursor_SEHFinallyStmt".enum("Windows Structured Exception Handling's finally statement."), "Cursor_MSAsmStmt".enum("A MS inline assembly statement extension."), "Cursor_NullStmt".enum( """ The null statement ";": C99 6.8.3p3. This cursor kind is used to describe the null statement. """ ), "Cursor_DeclStmt".enum("Adaptor class for mixing declarations with statements and expressions."), "Cursor_OMPParallelDirective".enum("OpenMP parallel directive."), "Cursor_OMPSimdDirective".enum("OpenMP SIMD directive."), "Cursor_OMPForDirective".enum("OpenMP for directive."), "Cursor_OMPSectionsDirective".enum("OpenMP sections directive."), "Cursor_OMPSectionDirective".enum("OpenMP section directive."), "Cursor_OMPSingleDirective".enum("OpenMP single directive."), "Cursor_OMPParallelForDirective".enum("OpenMP parallel for directive."), "Cursor_OMPParallelSectionsDirective".enum("OpenMP parallel sections directive."), "Cursor_OMPTaskDirective".enum("OpenMP task directive."), "Cursor_OMPMasterDirective".enum("OpenMP master directive."), "Cursor_OMPCriticalDirective".enum("OpenMP critical directive."), "Cursor_OMPTaskyieldDirective".enum("OpenMP taskyield directive."), "Cursor_OMPBarrierDirective".enum("OpenMP barrier directive."), "Cursor_OMPTaskwaitDirective".enum("OpenMP taskwait directive."), "Cursor_OMPFlushDirective".enum("OpenMP flush directive."), "Cursor_SEHLeaveStmt".enum("Windows Structured Exception Handling's leave statement."), "Cursor_OMPOrderedDirective".enum("OpenMP ordered directive."), "Cursor_OMPAtomicDirective".enum("OpenMP atomic directive."), "Cursor_OMPForSimdDirective".enum("OpenMP for SIMD directive."), "Cursor_OMPParallelForSimdDirective".enum("OpenMP parallel for SIMD directive."), "Cursor_OMPTargetDirective".enum("OpenMP target directive."), "Cursor_OMPTeamsDirective".enum("OpenMP teams directive."), "Cursor_OMPTaskgroupDirective".enum("OpenMP taskgroup directive."), "Cursor_OMPCancellationPointDirective".enum("OpenMP cancellation point directive."), "Cursor_OMPCancelDirective".enum("OpenMP cancel directive."), "Cursor_OMPTargetDataDirective".enum("OpenMP target data directive."), "Cursor_OMPTaskLoopDirective".enum("OpenMP taskloop directive."), "Cursor_OMPTaskLoopSimdDirective".enum("OpenMP taskloop simd directive."), "Cursor_OMPDistributeDirective".enum("OpenMP distribute directive."), "Cursor_OMPTargetEnterDataDirective".enum("OpenMP target enter data directive."), "Cursor_OMPTargetExitDataDirective".enum("OpenMP target exit data directive."), "Cursor_OMPTargetParallelDirective".enum("OpenMP target parallel directive."), "Cursor_OMPTargetParallelForDirective".enum("OpenMP target parallel for directive."), "Cursor_OMPTargetUpdateDirective".enum("OpenMP target update directive."), "Cursor_OMPDistributeParallelForDirective".enum("OpenMP distribute parallel for directive."), "Cursor_OMPDistributeParallelForSimdDirective".enum("OpenMP distribute parallel for simd directive."), "Cursor_OMPDistributeSimdDirective".enum("OpenMP distribute simd directive."), "Cursor_OMPTargetParallelForSimdDirective".enum("OpenMP target parallel for simd directive."), "Cursor_OMPTargetSimdDirective".enum("OpenMP target simd directive."), "Cursor_OMPTeamsDistributeDirective".enum("OpenMP teams distribute directive."), "Cursor_OMPTeamsDistributeSimdDirective".enum("OpenMP teams distribute simd directive."), "Cursor_OMPTeamsDistributeParallelForSimdDirective".enum("OpenMP teams distribute parallel for simd directive."), "Cursor_OMPTeamsDistributeParallelForDirective".enum("OpenMP teams distribute parallel for directive."), "Cursor_OMPTargetTeamsDirective".enum("OpenMP target teams directive."), "Cursor_OMPTargetTeamsDistributeDirective".enum("OpenMP target teams distribute directive."), "Cursor_OMPTargetTeamsDistributeParallelForDirective".enum("OpenMP target teams distribute parallel for directive."), "Cursor_OMPTargetTeamsDistributeParallelForSimdDirective".enum("OpenMP target teams distribute parallel for simd directive."), "Cursor_OMPTargetTeamsDistributeSimdDirective".enum("OpenMP target teams distribute simd directive."), "Cursor_BuiltinBitCastExpr".enum("C++2a std::bit_cast expression."), "Cursor_OMPMasterTaskLoopDirective".enum("OpenMP master taskloop directive."), "Cursor_OMPParallelMasterTaskLoopDirective".enum("OpenMP parallel master taskloop directive."), "Cursor_OMPMasterTaskLoopSimdDirective".enum("OpenMP master taskloop simd directive."), "Cursor_OMPParallelMasterTaskLoopSimdDirective".enum("OpenMP parallel master taskloop simd directive."), "Cursor_OMPParallelMasterDirective".enum("OpenMP parallel master directive."), "Cursor_OMPDepobjDirective".enum("OpenMP depobj directive."), "Cursor_OMPScanDirective".enum("OpenMP scan directive."), "Cursor_OMPTileDirective".enum("OpenMP tile directive."), "Cursor_OMPCanonicalLoop".enum("OpenMP canonical loop."), "Cursor_OMPInteropDirective".enum("OpenMP interop directive."), "Cursor_OMPDispatchDirective".enum("OpenMP dispatch directive."), "Cursor_OMPMaskedDirective".enum("OpenMP masked directive."), "Cursor_OMPUnrollDirective".enum("OpenMP unroll directive."), "Cursor_LastStmt".enum("", "CXCursor_OMPUnrollDirective"), "Cursor_TranslationUnit".enum( """ Cursor that represents the translation unit itself. The translation unit cursor exists primarily to act as the root cursor for traversing the contents of a translation unit. """, "300" ), "Cursor_FirstAttr".enum("Attributes", "400"), "Cursor_UnexposedAttr".enum("An attribute whose specific kind is not exposed via this interface.", "400"), "Cursor_IBActionAttr".enum(""), "Cursor_IBOutletAttr".enum(""), "Cursor_IBOutletCollectionAttr".enum(""), "Cursor_CXXFinalAttr".enum(""), "Cursor_CXXOverrideAttr".enum(""), "Cursor_AnnotateAttr".enum(""), "Cursor_AsmLabelAttr".enum(""), "Cursor_PackedAttr".enum(""), "Cursor_PureAttr".enum(""), "Cursor_ConstAttr".enum(""), "Cursor_NoDuplicateAttr".enum(""), "Cursor_CUDAConstantAttr".enum(""), "Cursor_CUDADeviceAttr".enum(""), "Cursor_CUDAGlobalAttr".enum(""), "Cursor_CUDAHostAttr".enum(""), "Cursor_CUDASharedAttr".enum(""), "Cursor_VisibilityAttr".enum(""), "Cursor_DLLExport".enum(""), "Cursor_DLLImport".enum(""), "Cursor_NSReturnsRetained".enum(""), "Cursor_NSReturnsNotRetained".enum(""), "Cursor_NSReturnsAutoreleased".enum(""), "Cursor_NSConsumesSelf".enum(""), "Cursor_NSConsumed".enum(""), "Cursor_ObjCException".enum(""), "Cursor_ObjCNSObject".enum(""), "Cursor_ObjCIndependentClass".enum(""), "Cursor_ObjCPreciseLifetime".enum(""), "Cursor_ObjCReturnsInnerPointer".enum(""), "Cursor_ObjCRequiresSuper".enum(""), "Cursor_ObjCRootClass".enum(""), "Cursor_ObjCSubclassingRestricted".enum(""), "Cursor_ObjCExplicitProtocolImpl".enum(""), "Cursor_ObjCDesignatedInitializer".enum(""), "Cursor_ObjCRuntimeVisible".enum(""), "Cursor_ObjCBoxable".enum(""), "Cursor_FlagEnum".enum(""), "Cursor_ConvergentAttr".enum(""), "Cursor_WarnUnusedAttr".enum(""), "Cursor_WarnUnusedResultAttr".enum(""), "Cursor_AlignedAttr".enum(""), "Cursor_LastAttr".enum("", "CXCursor_AlignedAttr"), "Cursor_PreprocessingDirective".enum("Preprocessing", "500"), "Cursor_MacroDefinition".enum(""), "Cursor_MacroExpansion".enum(""), "Cursor_MacroInstantiation".enum("", "CXCursor_MacroExpansion"), "Cursor_InclusionDirective".enum("", "503"), "Cursor_FirstPreprocessing".enum("", "CXCursor_PreprocessingDirective"), "Cursor_LastPreprocessing".enum("", "CXCursor_InclusionDirective"), "Cursor_ModuleImportDecl".enum("A module import declaration.", "600"), "Cursor_TypeAliasTemplateDecl".enum(""), "Cursor_StaticAssert".enum("A static_assert or _Static_assert node"), "Cursor_FriendDecl".enum("a friend declaration."), "Cursor_FirstExtraDecl".enum("", "CXCursor_ModuleImportDecl"), "Cursor_LastExtraDecl".enum("", "CXCursor_FriendDecl"), "Cursor_OverloadCandidate".enum("A code completion overload candidate.", "700") ) EnumConstant( """ Describe the linkage of the entity referred to by a cursor. ({@code enum CXLinkageKind}) """, "Linkage_Invalid".enum("This value indicates that no linkage information is available for a provided CXCursor.", "0"), "Linkage_NoLinkage".enum( "This is the linkage for variables, parameters, and so on that have automatic storage. This covers normal (non-extern) local variables." ), "Linkage_Internal".enum("This is the linkage for static variables and static functions."), "Linkage_UniqueExternal".enum("This is the linkage for entities with external linkage that live in C++ anonymous namespaces."), "Linkage_External".enum("This is the linkage for entities with true, external linkage.") ) EnumConstant( "{@code enum CXVisibilityKind}", "Visibility_Invalid".enum("This value indicates that no visibility information is available for a provided CXCursor.", "0"), "Visibility_Hidden".enum("Symbol not seen by the linker."), "Visibility_Protected".enum("Symbol seen by the linker but resolves to a symbol inside this object."), "Visibility_Default".enum("Symbol seen by the linker and acts like a normal symbol.") ) EnumConstant( """ Describe the "language" of the entity referred to by a cursor. ({@code enum CXLanguageKind}) """, "Language_Invalid".enum("", "0"), "Language_C".enum, "Language_ObjC".enum, "Language_CPlusPlus".enum ) EnumConstant( """ Describe the "thread-local storage (TLS) kind" of the declaration referred to by a cursor. ({@code enum CXTLSKind}) """, "TLS_None".enum("", "0"), "TLS_Dynamic".enum, "TLS_Static".enum ) EnumConstant( """ Describes the kind of type ({@code enum CXTypeKind}) """, "Type_Invalid".enum("Represents an invalid type (e.g., where no type is available).", "0"), "Type_Unexposed".enum("A type whose specific kind is not exposed via this interface."), "Type_Void".enum(""), "Type_Bool".enum(""), "Type_Char_U".enum(""), "Type_UChar".enum(""), "Type_Char16".enum(""), "Type_Char32".enum(""), "Type_UShort".enum(""), "Type_UInt".enum(""), "Type_ULong".enum(""), "Type_ULongLong".enum(""), "Type_UInt128".enum(""), "Type_Char_S".enum(""), "Type_SChar".enum(""), "Type_WChar".enum(""), "Type_Short".enum(""), "Type_Int".enum(""), "Type_Long".enum(""), "Type_LongLong".enum(""), "Type_Int128".enum(""), "Type_Float".enum(""), "Type_Double".enum(""), "Type_LongDouble".enum(""), "Type_NullPtr".enum(""), "Type_Overload".enum(""), "Type_Dependent".enum(""), "Type_ObjCId".enum(""), "Type_ObjCClass".enum(""), "Type_ObjCSel".enum(""), "Type_Float128".enum(""), "Type_Half".enum(""), "Type_Float16".enum(""), "Type_ShortAccum".enum(""), "Type_Accum".enum(""), "Type_LongAccum".enum(""), "Type_UShortAccum".enum(""), "Type_UAccum".enum(""), "Type_ULongAccum".enum(""), "Type_BFloat16".enum(""), "Type_FirstBuiltin".enum("", "CXType_Void"), "Type_LastBuiltin".enum("", "CXType_BFloat16"), "Type_Complex".enum("", "100"), "Type_Pointer".enum(""), "Type_BlockPointer".enum(""), "Type_LValueReference".enum(""), "Type_RValueReference".enum(""), "Type_Record".enum(""), "Type_Enum".enum(""), "Type_Typedef".enum(""), "Type_ObjCInterface".enum(""), "Type_ObjCObjectPointer".enum(""), "Type_FunctionNoProto".enum(""), "Type_FunctionProto".enum(""), "Type_ConstantArray".enum(""), "Type_Vector".enum(""), "Type_IncompleteArray".enum(""), "Type_VariableArray".enum(""), "Type_DependentSizedArray".enum(""), "Type_MemberPointer".enum(""), "Type_Auto".enum(""), "Type_Elaborated".enum( """ Represents a type that was referred to using an elaborated type keyword. E.g., struct S, or via a qualified name, e.g., N::M::type, or both. """ ), "Type_Pipe".enum("OpenCL PipeType."), "Type_OCLImage1dRO".enum(""), "Type_OCLImage1dArrayRO".enum(""), "Type_OCLImage1dBufferRO".enum(""), "Type_OCLImage2dRO".enum(""), "Type_OCLImage2dArrayRO".enum(""), "Type_OCLImage2dDepthRO".enum(""), "Type_OCLImage2dArrayDepthRO".enum(""), "Type_OCLImage2dMSAARO".enum(""), "Type_OCLImage2dArrayMSAARO".enum(""), "Type_OCLImage2dMSAADepthRO".enum(""), "Type_OCLImage2dArrayMSAADepthRO".enum(""), "Type_OCLImage3dRO".enum(""), "Type_OCLImage1dWO".enum(""), "Type_OCLImage1dArrayWO".enum(""), "Type_OCLImage1dBufferWO".enum(""), "Type_OCLImage2dWO".enum(""), "Type_OCLImage2dArrayWO".enum(""), "Type_OCLImage2dDepthWO".enum(""), "Type_OCLImage2dArrayDepthWO".enum(""), "Type_OCLImage2dMSAAWO".enum(""), "Type_OCLImage2dArrayMSAAWO".enum(""), "Type_OCLImage2dMSAADepthWO".enum(""), "Type_OCLImage2dArrayMSAADepthWO".enum(""), "Type_OCLImage3dWO".enum(""), "Type_OCLImage1dRW".enum(""), "Type_OCLImage1dArrayRW".enum(""), "Type_OCLImage1dBufferRW".enum(""), "Type_OCLImage2dRW".enum(""), "Type_OCLImage2dArrayRW".enum(""), "Type_OCLImage2dDepthRW".enum(""), "Type_OCLImage2dArrayDepthRW".enum(""), "Type_OCLImage2dMSAARW".enum(""), "Type_OCLImage2dArrayMSAARW".enum(""), "Type_OCLImage2dMSAADepthRW".enum(""), "Type_OCLImage2dArrayMSAADepthRW".enum(""), "Type_OCLImage3dRW".enum(""), "Type_OCLSampler".enum(""), "Type_OCLEvent".enum(""), "Type_OCLQueue".enum(""), "Type_OCLReserveID".enum(""), "Type_ObjCObject".enum, "Type_ObjCTypeParam".enum, "Type_Attributed".enum, "Type_OCLIntelSubgroupAVCMcePayload".enum(""), "Type_OCLIntelSubgroupAVCImePayload".enum(""), "Type_OCLIntelSubgroupAVCRefPayload".enum(""), "Type_OCLIntelSubgroupAVCSicPayload".enum(""), "Type_OCLIntelSubgroupAVCMceResult".enum(""), "Type_OCLIntelSubgroupAVCImeResult".enum(""), "Type_OCLIntelSubgroupAVCRefResult".enum(""), "Type_OCLIntelSubgroupAVCSicResult".enum(""), "Type_OCLIntelSubgroupAVCImeResultSingleRefStreamout".enum(""), "Type_OCLIntelSubgroupAVCImeResultDualRefStreamout".enum(""), "Type_OCLIntelSubgroupAVCImeSingleRefStreamin".enum(""), "Type_OCLIntelSubgroupAVCImeDualRefStreamin".enum(""), "Type_ExtVector".enum(""), "Type_Atomic".enum("") ) EnumConstant( """ Describes the calling convention of a function type ({@code enum CXCallingConv}) """, "CallingConv_Default".enum("", "0"), "CallingConv_C".enum, "CallingConv_X86StdCall".enum, "CallingConv_X86FastCall".enum, "CallingConv_X86ThisCall".enum, "CallingConv_X86Pascal".enum, "CallingConv_AAPCS".enum, "CallingConv_AAPCS_VFP".enum, "CallingConv_X86RegCall".enum, "CallingConv_IntelOclBicc".enum, "CallingConv_Win64".enum, "CallingConv_X86_64Win64".enum("Alias for compatibility with older versions of API.", "CXCallingConv_Win64"), "CallingConv_X86_64SysV".enum("", "11"), "CallingConv_X86VectorCall".enum(""), "CallingConv_Swift".enum(""), "CallingConv_PreserveMost".enum(""), "CallingConv_PreserveAll".enum(""), "CallingConv_AArch64VectorCall".enum(""), "CallingConv_SwiftAsync".enum(""), "CallingConv_Invalid".enum("", "100"), "CallingConv_Unexposed".enum("", "200") ) EnumConstant( """ Describes the kind of a template argument. ({@code enum CXTemplateArgumentKind}) See the definition of llvm::clang::TemplateArgument::ArgKind for full element descriptions. """, "TemplateArgumentKind_Null".enum("", "0"), "TemplateArgumentKind_Type".enum, "TemplateArgumentKind_Declaration".enum, "TemplateArgumentKind_NullPtr".enum, "TemplateArgumentKind_Integral".enum, "TemplateArgumentKind_Template".enum, "TemplateArgumentKind_TemplateExpansion".enum, "TemplateArgumentKind_Expression".enum, "TemplateArgumentKind_Pack".enum, "TemplateArgumentKind_Invalid".enum("Indicates an error case, preventing the kind from being deduced.") ) EnumConstant( "{@code enum CXTypeNullabilityKind}", "TypeNullability_NonNull".enum("Values of this type can never be null.", "0"), "TypeNullability_Nullable".enum("Values of this type can be null."), "TypeNullability_Unspecified".enum( """ Whether values of this type can be null is (explicitly) unspecified. This captures a (fairly rare) case where we can't conclude anything about the nullability of the type even though it has been considered. """ ), "TypeNullability_Invalid".enum("Nullability is not applicable to this type."), "TypeNullability_NullableResult".enum( """ Generally behaves like {@code Nullable}, except when used in a block parameter that was imported into a swift async method. There, swift will assume that the parameter can get null even if no error occured. {@code _Nullable} parameters are assumed to only get null on error. """ ) ) EnumConstant( """ List the possible error codes for {@code clang_Type_getSizeOf}, {@code clang_Type_getAlignOf}, {@code clang_Type_getOffsetOf} and {@code clang_Cursor_getOffsetOf}. ({@code enum CXTypeLayoutError}) A value of this enumeration type can be returned if the target type is not a valid argument to sizeof, alignof or offsetof. """, "TypeLayoutError_Invalid".enum("Type is of kind CXType_Invalid.", "-1"), "TypeLayoutError_Incomplete".enum("The type is an incomplete Type.", "-2"), "TypeLayoutError_Dependent".enum("The type is a dependent Type.", "-3"), "TypeLayoutError_NotConstantSize".enum("The type is not a constant size type.", "-4"), "TypeLayoutError_InvalidFieldName".enum("The Field name is not valid for this record.", "-5"), "TypeLayoutError_Undeduced".enum("The type is undeduced.", "-6") ) EnumConstant( "{@code enum CXRefQualifierKind}", "RefQualifier_None".enum("No ref-qualifier was provided.", "0"), "RefQualifier_LValue".enum("An lvalue ref-qualifier was provided ({@code &})."), "RefQualifier_RValue".enum("An rvalue ref-qualifier was provided ({@code &&}).") ) EnumConstant( """ Represents the C++ access control level to a base class for a cursor with kind CX_CXXBaseSpecifier. ({@code enum CX_CXXAccessSpecifier}) """, "_CXXInvalidAccessSpecifier".enum("", "0"), "_CXXPublic".enum, "_CXXProtected".enum, "_CXXPrivate".enum ) EnumConstant( """ Represents the storage classes as declared in the source. CX_SC_Invalid was added for the case that the passed cursor in not a declaration. ({@code enum CX_StorageClass}) """, "_SC_Invalid".enum("", "0"), "_SC_None".enum, "_SC_Extern".enum, "_SC_Static".enum, "_SC_PrivateExtern".enum, "_SC_OpenCLWorkGroupLocal".enum, "_SC_Auto".enum, "_SC_Register".enum ) EnumConstant( """ Describes how the traversal of the children of a particular cursor should proceed after visiting a particular child cursor. ({@code enum CXChildVisitResult}) A value of this enumeration type should be returned by each {@code CXCursorVisitor} to indicate how #visitChildren() proceed. """, "ChildVisit_Break".enum("Terminates the cursor traversal.", "0"), "ChildVisit_Continue".enum("Continues the cursor traversal with the next sibling of the cursor just visited, without visiting its children."), "ChildVisit_Recurse".enum("Recursively traverse the children of this cursor, using the same visitor and client data.") ) EnumConstant( """ Properties for the printing policy. ({@code enum CXPrintingPolicyProperty}) See {@code clang::PrintingPolicy} for more information. """, "PrintingPolicy_Indentation".enum("", "0"), "PrintingPolicy_SuppressSpecifiers".enum, "PrintingPolicy_SuppressTagKeyword".enum, "PrintingPolicy_IncludeTagDefinition".enum, "PrintingPolicy_SuppressScope".enum, "PrintingPolicy_SuppressUnwrittenScope".enum, "PrintingPolicy_SuppressInitializers".enum, "PrintingPolicy_ConstantArraySizeAsWritten".enum, "PrintingPolicy_AnonymousTagLocations".enum, "PrintingPolicy_SuppressStrongLifetime".enum, "PrintingPolicy_SuppressLifetimeQualifiers".enum, "PrintingPolicy_SuppressTemplateArgsInCXXConstructors".enum, "PrintingPolicy_Bool".enum, "PrintingPolicy_Restrict".enum, "PrintingPolicy_Alignof".enum, "PrintingPolicy_UnderscoreAlignof".enum, "PrintingPolicy_UseVoidForZeroParams".enum, "PrintingPolicy_TerseOutput".enum, "PrintingPolicy_PolishForDeclaration".enum, "PrintingPolicy_Half".enum, "PrintingPolicy_MSWChar".enum, "PrintingPolicy_IncludeNewlines".enum, "PrintingPolicy_MSVCFormatting".enum, "PrintingPolicy_ConstantsAsWritten".enum, "PrintingPolicy_SuppressImplicitBase".enum, "PrintingPolicy_FullyQualifiedName".enum, "PrintingPolicy_LastProperty".enum("", "CXPrintingPolicy_FullyQualifiedName") ) EnumConstant( """ Property attributes for a {@code CXCursor_ObjCPropertyDecl}. ({@code CXObjCPropertyAttrKind}) """, "ObjCPropertyAttr_noattr".enum("", "0x00"), "ObjCPropertyAttr_readonly".enum("", "0x01"), "ObjCPropertyAttr_getter".enum("", "0x02"), "ObjCPropertyAttr_assign".enum("", "0x04"), "ObjCPropertyAttr_readwrite".enum("", "0x08"), "ObjCPropertyAttr_retain".enum("", "0x10"), "ObjCPropertyAttr_copy".enum("", "0x20"), "ObjCPropertyAttr_nonatomic".enum("", "0x40"), "ObjCPropertyAttr_setter".enum("", "0x80"), "ObjCPropertyAttr_atomic".enum("", "0x100"), "ObjCPropertyAttr_weak".enum("", "0x200"), "ObjCPropertyAttr_strong".enum("", "0x400"), "ObjCPropertyAttr_unsafe_unretained".enum("", "0x800"), "ObjCPropertyAttr_class".enum("", "0x1000") ) EnumConstant( """ 'Qualifiers' written next to the return and parameter types in Objective-C method declarations. ({@code CXObjCDeclQualifierKind}) """, "ObjCDeclQualifier_None".enum("", "0x0"), "ObjCDeclQualifier_In".enum("", "0x1"), "ObjCDeclQualifier_Inout".enum("", "0x2"), "ObjCDeclQualifier_Out".enum("", "0x4"), "ObjCDeclQualifier_Bycopy".enum("", "0x8"), "ObjCDeclQualifier_Byref".enum("", "0x10"), "ObjCDeclQualifier_Oneway".enum("", "0x20") ) EnumConstant( "{@code enum CXNameRefFlags}", "NameRange_WantQualifier".enum("Include the nested-name-specifier, e.g. Foo:: in x.Foo::y, in the range.", "0x1"), "NameRange_WantTemplateArgs".enum("Include the explicit template arguments, e.g. &lt;int&gt; in x.f&lt;int&gt;, in the range.", "0x2"), "NameRange_WantSinglePiece".enum( """ If the name is non-contiguous, return the full spanning range. Non-contiguous names occur in Objective-C when a selector with two or more parameters is used, or in C++ when using an operator: ${codeBlock(""" [object doSomething:here withValue:there]; // Objective-C return some_vector[1]; // C++""")} """, "0x4" ) ) EnumConstant( """ Describes a kind of token. ({@code CXTokenKind}) """, "Token_Punctuation".enum("A token that contains some kind of punctuation.", "0"), "Token_Keyword".enum("A language keyword."), "Token_Identifier".enum("An identifier (that is not a keyword)."), "Token_Literal".enum("A numeric, string, or character literal."), "Token_Comment".enum("A comment.") ) EnumConstant( """ Describes a single piece of text within a code-completion string. ({@code enum CXCompletionChunkKind}) Each "chunk" within a code-completion string ({@code CXCompletionString}) is either a piece of text with a specific "kind" that describes how that text should be interpreted by the client or is another completion string. """, "CompletionChunk_Optional".enum( """ A code-completion string that describes "optional" text that could be a part of the template (but is not required). The Optional chunk is the only kind of chunk that has a code-completion string for its representation, which is accessible via {@code clang_getCompletionChunkCompletionString()}. The code-completion string describes an additional part of the template that is completely optional. For example, optional chunks can be used to describe the placeholders for arguments that match up with defaulted function parameters, e.g. given: ${codeBlock(""" void f(int x, float y = 3.14, double z = 2.71828);""")} The code-completion string for this function would contain: ${ul( "a TypedText chunk for \"f\".", "a LeftParen chunk for \"(\".", "a Placeholder chunk for \"int x\"", """ an Optional chunk containing the remaining defaulted arguments, e.g., ${ul( "a Comma chunk for \",\"", "a Placeholder chunk for \"float y\"", """ an Optional chunk containing the last defaulted argument: ${ul( "a Comma chunk for \",\"", "a Placeholder chunk for \"double z\"" )} """ )} """, "a RightParen chunk for \")\"" )} There are many ways to handle Optional chunks. Two simple approaches are: ${ul( "Completely ignore optional chunks, in which case the template for the function \"f\" would only include the first parameter (\"int x\").", "Fully expand all optional chunks, in which case the template for the function \"f\" would have all of the parameters." )} """, "0" ), "CompletionChunk_TypedText".enum( """ Text that a user would be expected to type to get this code-completion result. There will be exactly one "typed text" chunk in a semantic string, which will typically provide the spelling of a keyword or the name of a declaration that could be used at the current code point. Clients are expected to filter the code-completion results based on the text in this chunk. """ ), "CompletionChunk_Text".enum( """ Text that should be inserted as part of a code-completion result. A "text" chunk represents text that is part of the template to be inserted into user code should this particular code-completion result be selected. """ ), "CompletionChunk_Placeholder".enum( """ Placeholder text that should be replaced by the user. A "placeholder" chunk marks a place where the user should insert text into the code-completion template. For example, placeholders might mark the function parameters for a function declaration, to indicate that the user should provide arguments for each of those parameters. The actual text in a placeholder is a suggestion for the text to display before the user replaces the placeholder with real code. """ ), "CompletionChunk_Informative".enum( """ Informative text that should be displayed but never inserted as part of the template. An "informative" chunk contains annotations that can be displayed to help the user decide whether a particular code-completion result is the right option, but which is not part of the actual template to be inserted by code completion. """ ), "CompletionChunk_CurrentParameter".enum( """ Text that describes the current parameter when code-completion is referring to function call, message send, or template specialization. A "current parameter" chunk occurs when code-completion is providing information about a parameter corresponding to the argument at the code-completion point. For example, given a function ${codeBlock(""" int add(int x, int y);""")} and the source code {@code add(}, where the code-completion point is after the "(", the code-completion string will contain a "current parameter" chunk for "int x", indicating that the current argument will initialize that parameter. After typing further, to {@code add(17}, (where the code-completion point is after the ","), the code-completion string will contain a "current parameter" chunk to "int y". """ ), "CompletionChunk_LeftParen".enum("A left parenthesis ('('), used to initiate a function call or signal the beginning of a function parameter list."), "CompletionChunk_RightParen".enum("A right parenthesis (')'), used to finish a function call or signal the end of a function parameter list."), "CompletionChunk_LeftBracket".enum("A left bracket ('[')."), "CompletionChunk_RightBracket".enum("A right bracket (']')."), "CompletionChunk_LeftBrace".enum("A left brace ('{')."), "CompletionChunk_RightBrace".enum("A right brace ('}')."), "CompletionChunk_LeftAngle".enum("A left angle bracket (' &lt;')."), "CompletionChunk_RightAngle".enum("A right angle bracket ('&gt;')."), "CompletionChunk_Comma".enum("A comma separator (',')."), "CompletionChunk_ResultType".enum( """ Text that specifies the result type of a given result. This special kind of informative chunk is not meant to be inserted into the text buffer. Rather, it is meant to illustrate the type that an expression using the given completion string would have. """ ), "CompletionChunk_Colon".enum("A colon (':')."), "CompletionChunk_SemiColon".enum("A semicolon (';')."), "CompletionChunk_Equal".enum("An '=' sign."), "CompletionChunk_HorizontalSpace".enum("Horizontal space (' ')."), "CompletionChunk_VerticalSpace".enum("Vertical space ('\\n'), after which it is generally a good idea to perform indentation.") ) EnumConstant( """ Flags that can be passed to {@code clang_codeCompleteAt()} to modify its behavior. ({@code enum CXCodeComplete_Flags}) The enumerators in this enumeration can be bitwise-OR'd together to provide multiple options to {@code clang_codeCompleteAt()}. """, "CodeComplete_IncludeMacros".enum("Whether to include macros within the set of code completions returned.", "0x01"), "CodeComplete_IncludeCodePatterns".enum( "Whether to include code patterns for language constructs within the set of code completions, e.g., for loops.", "0x02" ), "CodeComplete_IncludeBriefComments".enum("Whether to include brief documentation within the set of code completions returned.", "0x04"), "CodeComplete_SkipPreamble".enum( """ Whether to speed up completion by omitting top- or namespace-level entities defined in the preamble. There's no guarantee any particular entity is omitted. This may be useful if the headers are indexed externally. """, "0x08" ), "CodeComplete_IncludeCompletionsWithFixIts".enum( "Whether to include completions with small fix-its, e.g. change '.' to '-&gt;' on member access, etc.", "0x10" ) ) EnumConstant( """ Bits that represent the context under which completion is occurring. ({@code enum CXCompletionContext}) The enumerators in this enumeration may be bitwise-OR'd together if multiple contexts are occurring simultaneously. """, "CompletionContext_Unexposed".enum( "The context for completions is unexposed, as only Clang results should be included. (This is equivalent to having no context bits set.)", "0" ), "CompletionContext_AnyType".enum("Completions for any possible type should be included in the results.", "1 << 0"), "CompletionContext_AnyValue".enum("Completions for any possible value (variables, function calls, etc.) should be included in the results.", "1 << 1"), "CompletionContext_ObjCObjectValue".enum("Completions for values that resolve to an Objective-C object should be included in the results.", "1 << 2"), "CompletionContext_ObjCSelectorValue".enum( "Completions for values that resolve to an Objective-C selector should be included in the results.", "1 << 3" ), "CompletionContext_CXXClassTypeValue".enum("Completions for values that resolve to a C++ class type should be included in the results.", "1 << 4"), "CompletionContext_DotMemberAccess".enum( "Completions for fields of the member being accessed using the dot operator should be included in the results.", "1 << 5" ), "CompletionContext_ArrowMemberAccess".enum( "Completions for fields of the member being accessed using the arrow operator should be included in the results.", "1 << 6" ), "CompletionContext_ObjCPropertyAccess".enum( "Completions for properties of the Objective-C object being accessed using the dot operator should be included in the results.", "1 << 7" ), "CompletionContext_EnumTag".enum("Completions for enum tags should be included in the results.", "1 << 8"), "CompletionContext_UnionTag".enum("Completions for union tags should be included in the results.", "1 << 9"), "CompletionContext_StructTag".enum("Completions for struct tags should be included in the results.", "1 << 10"), "CompletionContext_ClassTag".enum("Completions for C++ class names should be included in the results.", "1 << 11"), "CompletionContext_Namespace".enum("Completions for C++ namespaces and namespace aliases should be included in the results.", "1 << 12"), "CompletionContext_NestedNameSpecifier".enum("Completions for C++ nested name specifiers should be included in the results.", "1 << 13"), "CompletionContext_ObjCInterface".enum("Completions for Objective-C interfaces (classes) should be included in the results.", "1 << 14"), "CompletionContext_ObjCProtocol".enum("Completions for Objective-C protocols should be included in the results.", "1 << 15"), "CompletionContext_ObjCCategory".enum("Completions for Objective-C categories should be included in the results.", "1 << 16"), "CompletionContext_ObjCInstanceMessage".enum("Completions for Objective-C instance messages should be included in the results.", "1 << 17"), "CompletionContext_ObjCClassMessage".enum("Completions for Objective-C class messages should be included in the results.", "1 << 18"), "CompletionContext_ObjCSelectorName".enum("Completions for Objective-C selector names should be included in the results.", "1 << 19"), "CompletionContext_MacroName".enum("Completions for preprocessor macro names should be included in the results.", "1 << 20"), "CompletionContext_NaturalLanguage".enum("Natural language completions should be included in the results.", "1 << 21"), "CompletionContext_IncludedFile".enum("{@code \\#include} file completions should be included in the results.", "1 << 22"), "CompletionContext_Unknown".enum("The current context is unknown, so set all contexts.", "((1 << 23) - 1)") ) EnumConstant( "{@code CXEvalResultKind}", "Eval_Int".enum("", "1"), "Eval_Float".enum, "Eval_ObjCStrLiteral".enum, "Eval_StrLiteral".enum, "Eval_CFStr".enum, "Eval_Other".enum, "Eval_UnExposed".enum("", "0") ) EnumConstant( "{@code enum CXVisitorResult}", "Visit_Break".enum("", "0"), "Visit_Continue".enum ) EnumConstant( "{@code CXResult}", "Result_Success".enum("Function returned successfully.", "0"), "Result_Invalid".enum("One of the parameters was invalid for the function."), "Result_VisitBreak".enum("The function was terminated by a callback (e.g. it returned CXVisit_Break)") ) EnumConstant( "{@code CXIdxEntityKind}", "IdxEntity_Unexposed".enum("", "0"), "IdxEntity_Typedef".enum, "IdxEntity_Function".enum, "IdxEntity_Variable".enum, "IdxEntity_Field".enum, "IdxEntity_EnumConstant".enum, "IdxEntity_ObjCClass".enum, "IdxEntity_ObjCProtocol".enum, "IdxEntity_ObjCCategory".enum, "IdxEntity_ObjCInstanceMethod".enum, "IdxEntity_ObjCClassMethod".enum, "IdxEntity_ObjCProperty".enum, "IdxEntity_ObjCIvar".enum, "IdxEntity_Enum".enum, "IdxEntity_Struct".enum, "IdxEntity_Union".enum, "IdxEntity_CXXClass".enum, "IdxEntity_CXXNamespace".enum, "IdxEntity_CXXNamespaceAlias".enum, "IdxEntity_CXXStaticVariable".enum, "IdxEntity_CXXStaticMethod".enum, "IdxEntity_CXXInstanceMethod".enum, "IdxEntity_CXXConstructor".enum, "IdxEntity_CXXDestructor".enum, "IdxEntity_CXXConversionFunction".enum, "IdxEntity_CXXTypeAlias".enum, "IdxEntity_CXXInterface".enum ) EnumConstant( "{@code CXIdxEntityLanguage}", "IdxEntityLang_None".enum("", "0"), "IdxEntityLang_C".enum, "IdxEntityLang_ObjC".enum, "IdxEntityLang_CXX".enum, "IdxEntityLang_Swift".enum ) EnumConstant( """ Extra C++ template information for an entity. This can apply to: CXIdxEntity_Function CXIdxEntity_CXXClass CXIdxEntity_CXXStaticMethod CXIdxEntity_CXXInstanceMethod CXIdxEntity_CXXConstructor CXIdxEntity_CXXConversionFunction CXIdxEntity_CXXTypeAlias ({@code CXIdxEntityCXXTemplateKind}) """, "IdxEntity_NonTemplate".enum("", "0"), "IdxEntity_Template".enum, "IdxEntity_TemplatePartialSpecialization".enum, "IdxEntity_TemplateSpecialization".enum ) EnumConstant( "{@code CXIdxAttrKind}", "IdxAttr_Unexposed".enum("", "0"), "IdxAttr_IBAction".enum, "IdxAttr_IBOutlet".enum, "IdxAttr_IBOutletCollection".enum ) EnumConstant( "{@code CXIdxDeclInfoFlags}", "IdxDeclFlag_Skipped".enum("", "0x1") ) EnumConstant( "{@code CXIdxObjCContainerKind}", "IdxObjCContainer_ForwardRef".enum("", "0"), "IdxObjCContainer_Interface".enum, "IdxObjCContainer_Implementation".enum ) EnumConstant( """ Data for IndexerCallbacks#indexEntityReference. ({@code CXIdxEntityRefKind}) This may be deprecated in a future version as this duplicates the {@code CXSymbolRole_Implicit} bit in {@code CXSymbolRole}. """, "IdxEntityRef_Direct".enum("The entity is referenced directly in user's code.", "1"), "IdxEntityRef_Implicit".enum("An implicit reference, e.g. a reference of an Objective-C method via the dot syntax.") ) EnumConstant( """ Roles that are attributed to symbol occurrences. ({@code CXSymbolRole}) Internal: this currently mirrors low 9 bits of clang::index::SymbolRole with higher bits zeroed. These high bits may be exposed in the future. """, "SymbolRole_None".enum("", "0"), "SymbolRole_Declaration".enum("", "1 << 0"), "SymbolRole_Definition".enum("", "1 << 1"), "SymbolRole_Reference".enum("", "1 << 2"), "SymbolRole_Read".enum("", "1 << 3"), "SymbolRole_Write".enum("", "1 << 4"), "SymbolRole_Call".enum("", "1 << 5"), "SymbolRole_Dynamic".enum("", "1 << 6"), "SymbolRole_AddressOf".enum("", "1 << 7"), "SymbolRole_Implicit".enum("", "1 << 8") ) EnumConstant( "{@code CXIndexOptFlags}", "IndexOpt_None".enum("Used to indicate that no special indexing options are needed.", "0x0"), "IndexOpt_SuppressRedundantRefs".enum( """ Used to indicate that IndexerCallbacks#indexEntityReference should be invoked for only one reference of an entity per source file that does not also include a declaration/definition of the entity. """, "0x1" ), "IndexOpt_IndexFunctionLocalSymbols".enum( "Function-local symbols should be indexed. If this is not set function-local symbols will be ignored.", "0x2" ), "IndexOpt_IndexImplicitTemplateInstantiations".enum( "Implicit function/class template instantiations should be indexed. If this is not set, implicit instantiations will be ignored.", "0x4" ), "IndexOpt_SuppressWarnings".enum("Suppress all compiler warnings when parsing for indexing.", "0x8"), "IndexOpt_SkipParsedBodiesInSession".enum( """ Skip a function/method body that was already parsed during an indexing session associated with a {@code CXIndexAction} object. Bodies in system headers are always skipped. """, "0x10" ) ) charUTF8.const.p( "getCString", "Retrieve the character data associated with the given string.", CXString("string", "") ) void( "disposeString", "Free the given string.", CXString("string", "") ) void( "disposeStringSet", "Free the given string set.", Input..CXStringSet.p("set", "") ) CXIndex( "createIndex", """ Provides a shared context for creating translation units. It provides two options: ${ul( """ {@code excludeDeclarationsFromPCH}: When non-zero, allows enumeration of "local" declarations (when loading any new translation units). A "local" declaration is one that belongs in the translation unit itself and not in a precompiled header that was used by the translation unit. If zero, all declarations will be enumerated. """ )} Here is an example: ${codeBlock(""" // excludeDeclsFromPCH = 1, displayDiagnostics=1 Idx = clang_createIndex(1, 1); // IndexTest.pch was produced with the following command: // "clang -x c IndexTest.h -emit-ast -o IndexTest.pch" TU = clang_createTranslationUnit(Idx, "IndexTest.pch"); // This will load all the symbols from 'IndexTest.pch' clang_visitChildren(clang_getTranslationUnitCursor(TU), TranslationUnitVisitor, 0); clang_disposeTranslationUnit(TU); // This will load all the symbols from 'IndexTest.c', excluding symbols // from 'IndexTest.pch'. char *args[] = { "-Xclang", "-include-pch=IndexTest.pch" }; TU = clang_createTranslationUnitFromSourceFile(Idx, "IndexTest.c", 2, args, 0, 0); clang_visitChildren(clang_getTranslationUnitCursor(TU), TranslationUnitVisitor, 0); clang_disposeTranslationUnit(TU);""")} This process of creating the {@code pch}, loading it separately, and using it (via {@code -include-pch}) allows {@code excludeDeclsFromPCH} to remove redundant callbacks (which gives the indexer the same performance benefit as the compiler). """, intb("excludeDeclarationsFromPCH", ""), intb("displayDiagnostics", "") ) void( "disposeIndex", """ Destroy the given index. The index must not be destroyed until all of the translation units created within that index have been destroyed. """, CXIndex("index", "") ) void( "CXIndex_setGlobalOptions", """ Sets general options associated with a {@code CXIndex}. For example: ${codeBlock(""" CXIndex idx = ...; clang_CXIndex_setGlobalOptions(idx, clang_CXIndex_getGlobalOptions(idx) | CXGlobalOpt_ThreadBackgroundPriorityForIndexing);""")} """, CXIndex("index", ""), unsigned("options", "a bitmask of options, a bitwise OR of {@code CXGlobalOpt_XXX} flags") ) unsigned( "CXIndex_getGlobalOptions", "Gets the general options associated with a CXIndex.", CXIndex("index", ""), returnDoc = "a bitmask of options, a bitwise OR of {@code CXGlobalOpt_XXX} flags that are associated with the given {@code CXIndex} object" ) IgnoreMissing..void( "CXIndex_setInvocationEmissionPathOption", """ Sets the invocation emission path option in a {@code CXIndex}. The invocation emission path specifies a path which will contain log files for certain libclang invocations. A null value (default) implies that libclang invocations are not logged. """, CXIndex("index", ""), nullable..charUTF8.const.p("Path", "") ) CXString( "getFileName", "Retrieve the complete file and path name of the given file.", CXFile("SFile", "") ) time_t( "getFileTime", "Retrieve the last modification time of the given file.", CXFile("SFile", "") ) int( "getFileUniqueID", "Retrieve the unique ID for the given {@code file}.", CXFile("file", "the file to get the ID for"), CXFileUniqueID.p("outID", "stores the returned CXFileUniqueID"), returnDoc = "if there was a failure getting the unique ID, returns non-zero, otherwise returns 0" ) unsignedb( "isFileMultipleIncludeGuarded", """ Determine whether the given header is guarded against multiple inclusions, either with the conventional \#ifndef/\#define/\#endif macro guards or with \#pragma once. """, CXTranslationUnit("tu", ""), CXFile("file", "") ) CXFile( "getFile", "Retrieve a file handle within the given translation unit.", CXTranslationUnit("tu", "the translation unit"), charUTF8.const.p("file_name", "the name of the file"), returnDoc = "the file handle for the named file in the translation unit {@code tu}, or a #NULL file handle if the file was not a part of this translation unit" ) IgnoreMissing..char.const.p( "getFileContents", "Retrieve the buffer associated with the given file.", CXTranslationUnit("tu", "the translation unit"), CXFile("file", "the file for which to retrieve the buffer"), AutoSizeResult..size_t.p("size", "[out] if non-#NULL, will be set to the size of the buffer"), returnDoc = "a pointer to the buffer in memory that holds the contents of {@code file}, or a #NULL pointer when the file is not loaded" ) intb( "File_isEqual", "Returns non-zero if the {@code file1} and {@code file2} point to the same file, or they are both #NULL.", nullable..CXFile("file1", ""), nullable..CXFile("file2", "") ) IgnoreMissing..CXString( "File_tryGetRealPathName", """ Returns the real path name of {@code file}. An empty string may be returned. Use #getFileName() in that case. """, CXFile("file", "") ) CXSourceLocation("getNullLocation", "Retrieve a #NULL (invalid) source location.", void()) unsignedb( "equalLocations", "Determine whether two source locations, which must refer into the same translation unit, refer to exactly the same point in the source code.", CXSourceLocation("loc1", ""), CXSourceLocation("loc2", ""), returnDoc = "non-zero if the source locations refer to the same location, zero if they refer to different locations" ) CXSourceLocation( "getLocation", "Retrieves the source location associated with a given file/line/column in a particular translation unit.", CXTranslationUnit("tu", ""), CXFile("file", ""), unsigned("line", ""), unsigned("column", "") ) CXSourceLocation( "getLocationForOffset", "Retrieves the source location associated with a given character offset in a particular translation unit.", CXTranslationUnit("tu", ""), CXFile("file", ""), unsigned("offset", "") ) intb( "Location_isInSystemHeader", "Returns non-zero if the given source location is in a system header.", CXSourceLocation("location", "") ) intb( "Location_isFromMainFile", "Returns non-zero if the given source location is in the main file of the corresponding translation unit.", CXSourceLocation("location", "") ) CXSourceRange("getNullRange", "Retrieve a #NULL (invalid) source range.", void()) CXSourceRange( "getRange", "Retrieve a source range given the beginning and ending source locations.", CXSourceLocation("begin", ""), CXSourceLocation("end", "") ) unsignedb( "equalRanges", "Determine whether two ranges are equivalent.", CXSourceRange("range1", ""), CXSourceRange("range2", ""), returnDoc = "non-zero if the ranges are the same, zero if they differ" ) intb( "Range_isNull", "Returns non-zero if {@code range} is null.", CXSourceRange("range", "") ) void( "getExpansionLocation", """ Retrieve the file, line, column, and offset represented by the given source location. If the location refers into a macro expansion, retrieves the location of the macro expansion. """, CXSourceLocation("location", "the location within a source file that will be decomposed into its parts"), Check(1)..nullable..CXFile.p("file", "[out] if non-#NULL, will be set to the file to which the given source location points"), Check(1)..nullable..unsigned.p("line", "[out] if non-#NULL, will be set to the line to which the given source location points"), Check(1)..nullable..unsigned.p("column", "[out] if non-#NULL, will be set to the column to which the given source location points"), Check(1)..nullable..unsigned.p("offset", "[out] if non-#NULL, will be set to the offset into the buffer to which the given source location points") ) void( "getPresumedLocation", """ Retrieve the file, line and column represented by the given source location, as specified in a # line directive. Example: given the following source code in a file somefile.c ${codeBlock(""" \#123 "dummy.c" 1 static int func(void) { return 0; }""")} the location information returned by this function would be File: dummy.c Line: 124 Column: 12 whereas clang_getExpansionLocation would have returned File: somefile.c Line: 3 Column: 12 """, CXSourceLocation("location", "the location within a source file that will be decomposed into its parts"), Check(1)..nullable..CXString.p( "filename", """ [out] if non-#NULL, will be set to the filename of the source location. Note that filenames returned will be for "virtual" files, which don't necessarily exist on the machine running clang - e.g. when parsing preprocessed output obtained from a different environment. If a non-#NULL value is passed in, remember to dispose of the returned value using {@code clang_disposeString()} once you've finished with it. For an invalid source location, an empty string is returned. """ ), Check(1)..nullable..unsigned.p( "line", "[out] if non-#NULL, will be set to the line number of the source location. For an invalid source location, zero is returned." ), Check(1)..nullable..unsigned.p( "column", "[out] if non-#NULL, will be set to the column number of the source location. For an invalid source location, zero is returned." ) ) /*void( "getInstantiationLocation", """ Legacy API to retrieve the file, line, column, and offset represented by the given source location. This interface has been replaced by the newer interface #clang_getExpansionLocation(). See that interface's documentation for details. """, CXSourceLocation("location", ""), CXFile.p("file", ""), unsigned.p("line", ""), unsigned.p("column", ""), unsigned.p("offset", "") )*/ void( "getSpellingLocation", """ Retrieve the file, line, column, and offset represented by the given source location. If the location refers into a macro instantiation, return where the location was originally spelled in the source file. """, CXSourceLocation("location", "the location within a source file that will be decomposed into its parts"), Check(1)..nullable..CXFile.p("file", "[out] if non-#NULL, will be set to the file to which the given source location points"), Check(1)..nullable..unsigned.p("line", "[out] if non-#NULL, will be set to the line to which the given source location points"), Check(1)..nullable..unsigned.p("column", "[out] if non-#NULL, will be set to the column to which the given source location points"), Check(1)..nullable..unsigned.p("offset", "[out] if non-#NULL, will be set to the offset into the buffer to which the given source location points") ) void( "getFileLocation", """ Retrieve the file, line, column, and offset represented by the given source location. If the location refers into a macro expansion, return where the macro was expanded or where the macro argument was written, if the location points at a macro argument. """, CXSourceLocation("location", "the location within a source file that will be decomposed into its parts"), Check(1)..nullable..CXFile.p("file", "[out] if non-#NULL, will be set to the file to which the given source location points"), Check(1)..nullable..unsigned.p("line", "[out] if non-#NULL, will be set to the line to which the given source location points"), Check(1)..nullable..unsigned.p("column", "[out] if non-#NULL, will be set to the column to which the given source location points"), Check(1)..nullable..unsigned.p("offset", "[out] if non-#NULL, will be set to the offset into the buffer to which the given source location points") ) CXSourceLocation( "getRangeStart", "Retrieve a source location representing the first character within a source range.", CXSourceRange("range", "") ) CXSourceLocation( "getRangeEnd", "Retrieve a source location representing the last character within a source range.", CXSourceRange("range", "") ) CXSourceRangeList.p( "getSkippedRanges", """ Retrieve all ranges that were skipped by the preprocessor. The preprocessor will skip lines when they are surrounded by an if/ifdef/ifndef directive whose condition does not evaluate to true. """, CXTranslationUnit("tu", ""), CXFile("file", "") ) CXSourceRangeList.p( "getAllSkippedRanges", """ Retrieve all ranges from all files that were skipped by the preprocessor. The preprocessor will skip lines when they are surrounded by an if/ifdef/ifndef directive whose condition does not evaluate to true. """, CXTranslationUnit("tu", "") ) void( "disposeSourceRangeList", "Destroy the given {@code CXSourceRangeList}.", Input..CXSourceRangeList.p("ranges", "") ) unsigned( "getNumDiagnosticsInSet", "Determine the number of diagnostics in a {@code CXDiagnosticSet}.", CXDiagnosticSet("Diags", "") ) CXDiagnostic( "getDiagnosticInSet", "Retrieve a diagnostic associated with the given {@code CXDiagnosticSet}.", CXDiagnosticSet("Diags", "the {@code CXDiagnosticSet} to query"), unsigned("Index", "the zero-based diagnostic number to retrieve"), returnDoc = "the requested diagnostic. This diagnostic must be freed via a call to #disposeDiagnostic()." ) CXDiagnosticSet( "loadDiagnostics", "Deserialize a set of diagnostics from a Clang diagnostics bitcode file.", charUTF8.const.p("file", "the name of the file to deserialize"), Check(1)..CXLoadDiag_Error.p("error", "a pointer to a enum value recording if there was a problem deserializing the diagnostics"), CXString.p("errorString", "a pointer to a ##CXString for recording the error string if the file was not successfully loaded"), returnDoc = "a loaded {@code CXDiagnosticSet} if successful, and #NULL otherwise. These diagnostics should be released using #disposeDiagnosticSet()." ) void( "disposeDiagnosticSet", "Release a {@code CXDiagnosticSet} and all of its contained diagnostics.", CXDiagnosticSet("Diags", "") ) CXDiagnosticSet( "getChildDiagnostics", """ Retrieve the child diagnostics of a {@code CXDiagnostic}. This {@code CXDiagnosticSet} does not need to be released by #disposeDiagnosticSet(). """, CXDiagnostic("D", "") ) unsigned( "getNumDiagnostics", "Determine the number of diagnostics produced for the given translation unit.", CXTranslationUnit("Unit", "") ) CXDiagnostic( "getDiagnostic", "Retrieve a diagnostic associated with the given translation unit.", CXTranslationUnit("Unit", "the translation unit to query"), unsigned("Index", "the zero-based diagnostic number to retrieve"), returnDoc = "the requested diagnostic. This diagnostic must be freed via a call to #disposeDiagnostic()." ) CXDiagnosticSet( "getDiagnosticSetFromTU", "Retrieve the complete set of diagnostics associated with a translation unit.", CXTranslationUnit("Unit", "the translation unit to query") ) void( "disposeDiagnostic", "Destroy a diagnostic.", CXDiagnostic("Diagnostic", "") ) CXString( "formatDiagnostic", """ Format the given diagnostic in a manner that is suitable for display. This routine will format the given diagnostic to a string, rendering the diagnostic according to the various options given. The #defaultDiagnosticDisplayOptions() function returns the set of options that most closely mimics the behavior of the clang compiler. """, CXDiagnostic("Diagnostic", "the diagnostic to print"), unsigned("Options", "a set of options that control the diagnostic display, created by combining {@code CXDiagnosticDisplayOptions} values"), returnDoc = "a new string containing for formatted diagnostic" ) unsigned( "defaultDiagnosticDisplayOptions", "Retrieve the set of display options most similar to the default behavior of the clang compiler.", void(), returnDoc = "a set of display options suitable for use with #formatDiagnostic()" ) CXDiagnosticSeverity( "getDiagnosticSeverity", "Determine the severity of the given diagnostic.", CXDiagnostic("Diagnostic", "") ) CXSourceLocation( "getDiagnosticLocation", """ Retrieve the source location of the given diagnostic. This location is where Clang would print the caret ('^') when displaying the diagnostic on the command line. """, CXDiagnostic("Diagnostic", "") ) CXString( "getDiagnosticSpelling", "Retrieve the text of the given diagnostic.", CXDiagnostic("Diagnostic", "") ) CXString( "getDiagnosticOption", "Retrieve the name of the command-line option that enabled this diagnostic.", CXDiagnostic("Diag", "the diagnostic to be queried"), nullable..CXString.p("Disable", "if non-#NULL, will be set to the option that disables this diagnostic (if any)"), returnDoc = "a string that contains the command-line option used to enable this warning, such as \"-Wconversion\" or \"-pedantic\"" ) unsigned( "getDiagnosticCategory", """ Retrieve the category number for this diagnostic. Diagnostics can be categorized into groups along with other, related diagnostics (e.g., diagnostics under the same warning flag). This routine retrieves the category number for the given diagnostic. """, CXDiagnostic("Diagnostic", ""), returnDoc = "the number of the category that contains this diagnostic, or zero if this diagnostic is uncategorized" ) /*CXString( "getDiagnosticCategoryName", "Retrieve the name of a particular diagnostic category. This is now deprecated. Use clang_getDiagnosticCategoryText() instead.", unsigned("Category", "a diagnostic category number, as returned by {@code clang_getDiagnosticCategory()}"), returnDoc = "the name of the given diagnostic category" )*/ CXString( "getDiagnosticCategoryText", "Retrieve the diagnostic category text for a given diagnostic.", CXDiagnostic("Diagnostic", ""), returnDoc = "the text of the given diagnostic category" ) unsigned( "getDiagnosticNumRanges", "Determine the number of source ranges associated with the given diagnostic.", CXDiagnostic("Diagnostic", "") ) CXSourceRange( "getDiagnosticRange", """ Retrieve a source range associated with the diagnostic. A diagnostic's source ranges highlight important elements in the source code. On the command line, Clang displays source ranges by underlining them with '~' characters. """, CXDiagnostic("Diagnostic", "the diagnostic whose range is being extracted"), unsigned("Range", "the zero-based index specifying which range to"), returnDoc = "the requested source range" ) unsigned( "getDiagnosticNumFixIts", "Determine the number of fix-it hints associated with the given diagnostic.", CXDiagnostic("Diagnostic", "") ) CXString( "getDiagnosticFixIt", """ Retrieve the replacement information for a given fix-it. Fix-its are described in terms of a source range whose contents should be replaced by a string. This approach generalizes over three kinds of operations: removal of source code (the range covers the code to be removed and the replacement string is empty), replacement of source code (the range covers the code to be replaced and the replacement string provides the new code), and insertion (both the start and end of the range point at the insertion location, and the replacement string provides the text to insert). """, CXDiagnostic("Diagnostic", "the diagnostic whose fix-its are being queried"), unsigned("FixIt", "the zero-based index of the fix-it"), CXSourceRange.p( "ReplacementRange", """ the source range whose contents will be replaced with the returned replacement string. Note that source ranges are half-open ranges [a, b), so the source code should be replaced from a and up to (but not including) b. """ ), returnDoc = "a string containing text that should be replace the source code indicated by the {@code ReplacementRange}" ) CXString( "getTranslationUnitSpelling", "Get the original translation unit source file name.", CXTranslationUnit("CTUnit", "") ) CXTranslationUnit( "createTranslationUnitFromSourceFile", """ Return the {@code CXTranslationUnit} for a given source file and the provided command line arguments one would pass to the compiler. Note: The {@code source_filename} argument is optional. If the caller provides a #NULL pointer, the name of the source file is expected to reside in the specified command line arguments. Note: When encountered in {@code clang_command_line_args}, the following options are ignored: ${ul( "'-c'", "'-emit-ast'", "'-fsyntax-only'", "'-o &lt;output file&gt;' (both '-o' and ' &lt;output file&gt;' are ignored)" )} """, CXIndex("CIdx", "the index object with which the translation unit will be associated"), nullable..charUTF8.const.p( "source_filename", "the name of the source file to load, or #NULL if the source file is included in {@code clang_command_line_args}" ), AutoSize("clang_command_line_args")..int("num_clang_command_line_args", "the number of command-line arguments in {@code clang_command_line_args}"), nullable..charUTF8.const.p.const.p( "clang_command_line_args", """ the command-line arguments that would be passed to the {@code clang} executable if it were being invoked out-of-process. These command-line options will be parsed and will affect how the translation unit is parsed. Note that the following options are ignored: '-c', '-emit-ast', '-fsyntax-only' (which is the default), and '-o &lt;output file&gt;'. """ ), AutoSize("unsaved_files")..unsigned("num_unsaved_files", "the number of unsaved file entries in {@code unsaved_files}"), Input..nullable..CXUnsavedFile.p( "unsaved_files", """ the files that have not yet been saved to disk but may be required for code completion, including the contents of those files. The contents and name of these files (as specified by {@code CXUnsavedFile}) are copied when necessary, so the client only needs to guarantee their validity until the call to this function returns. """ ) ) CXTranslationUnit( "createTranslationUnit", """ Same as #createTranslationUnit2(), but returns the {@code CXTranslationUnit} instead of an error code. In case of an error this routine returns a #NULL {@code CXTranslationUnit}, without further detailed error codes. """, CXIndex("CIdx", ""), charUTF8.const.p("ast_filename", "") ) CXErrorCode( "createTranslationUnit2", "Create a translation unit from an AST file ({@code -emit-ast}).", CXIndex("CIdx", ""), charUTF8.const.p("ast_filename", ""), Check(1)..CXTranslationUnit.p("out_TU", "a non-#NULL pointer to store the created {@code CXTranslationUnit}"), returnDoc = "zero on success, otherwise returns an error code" ) unsigned( "defaultEditingTranslationUnitOptions", """ Returns the set of flags that is suitable for parsing a translation unit that is being edited. The set of flags returned provide options for #parseTranslationUnit() to indicate that the translation unit is likely to be reparsed many times, either explicitly (via #reparseTranslationUnit()) or implicitly (e.g., by code completion (#codeCompleteAt()). The returned flag set contains an unspecified set of optimizations (e.g., the precompiled preamble) geared toward improving the performance of these routines. The set of optimizations enabled may change from one version to the next. """, void() ) CXTranslationUnit( "parseTranslationUnit", """ Same as #parseTranslationUnit2(), but returns the {@code CXTranslationUnit} instead of an error code. In case of an error this routine returns a #NULL {@code CXTranslationUnit}, without further detailed error codes. """, CXIndex("CIdx", ""), nullable..charUTF8.const.p("source_filename", ""), nullable..charUTF8.const.p.const.p("command_line_args", ""), AutoSize("command_line_args")..int("num_command_line_args", ""), Input..nullable..CXUnsavedFile.p("unsaved_files", ""), AutoSize("unsaved_files")..unsigned("num_unsaved_files", ""), unsigned("options", "") ) CXErrorCode( "parseTranslationUnit2", """ Parse the given source file and the translation unit corresponding to that file. This routine is the main entry point for the Clang C API, providing the ability to parse a source file into a translation unit that can then be queried by other functions in the API. This routine accepts a set of command-line arguments so that the compilation can be configured in the same way that the compiler is configured on the command line. """, CXIndex("CIdx", "the index object with which the translation unit will be associated"), nullable..charUTF8.const.p( "source_filename", "the name of the source file to load, or #NULL if the source file is included in {@code command_line_args}"), nullable..charUTF8.const.p.const.p( "command_line_args", """ the command-line arguments that would be passed to the {@code clang} executable if it were being invoked out-of-process. These command-line options will be parsed and will affect how the translation unit is parsed. Note that the following options are ignored: '-c', '-emit-ast', '-fsyntax-only' (which is the default), and '-o &lt;output file&gt;'. """ ), AutoSize("command_line_args")..int("num_command_line_args", "the number of command-line arguments in {@code command_line_args}"), Input..nullable..CXUnsavedFile.p( "unsaved_files", """ the files that have not yet been saved to disk but may be required for parsing, including the contents of those files. The contents and name of these files (as specified by CXUnsavedFile) are copied when necessary, so the client only needs to guarantee their validity until the call to this function returns. """ ), AutoSize("unsaved_files")..unsigned("num_unsaved_files", "the number of unsaved file entries in {@code unsaved_files}"), unsigned( "options", """ a bitmask of options that affects how the translation unit is managed but not its compilation. This should be a bitwise OR of the CXTranslationUnit_XXX flags. """ ), Check(1)..CXTranslationUnit.p( "out_TU", """ a non-#NULL pointer to store the created {@code CXTranslationUnit}, describing the parsed code and containing any diagnostics produced by the compiler """ ), returnDoc = "zero on success, otherwise returns an error code" ) CXErrorCode( "parseTranslationUnit2FullArgv", """ Same as #parseTranslationUnit2() but requires a full command line for {@code command_line_args} including {@code argv[0]}. This is useful if the standard library paths are relative to the binary. """, CXIndex("CIdx", ""), nullable..charUTF8.const.p("source_filename", ""), charUTF8.const.p.const.p("command_line_args", ""), AutoSize("command_line_args")..int("num_command_line_args", ""), nullable..CXUnsavedFile.p("unsaved_files", ""), AutoSize("unsaved_files")..unsigned("num_unsaved_files", ""), unsigned("options", ""), Check(1)..CXTranslationUnit.p("out_TU", "") ) unsigned( "defaultSaveOptions", """ Returns the set of flags that is suitable for saving a translation unit. The set of flags returned provide options for #saveTranslationUnit() by default. The returned flag set contains an unspecified set of options that save translation units with the most commonly-requested data. """, CXTranslationUnit("TU", "") ) int( "saveTranslationUnit", """ Saves a translation unit into a serialized representation of that translation unit on disk. Any translation unit that was parsed without error can be saved into a file. The translation unit can then be deserialized into a new {@code CXTranslationUnit} with #createTranslationUnit() or, if it is an incomplete translation unit that corresponds to a header, used as a precompiled header when parsing other translation units. """, CXTranslationUnit("TU", "the translation unit to save"), charUTF8.const.p("FileName", "the file to which the translation unit will be saved"), unsigned( "options", "a bitmask of options that affects how the translation unit is saved. This should be a bitwise OR of the {@code CXSaveTranslationUnit_XXX} flags." ), returnDoc = """ a value that will match one of the enumerators of the {@code CXSaveError} enumeration. Zero (#SaveError_None) indicates that the translation unit was saved successfully, while a non-zero value indicates that a problem occurred. """ ) unsignedb( "suspendTranslationUnit", """ Suspend a translation unit in order to free memory associated with it. A suspended translation unit uses significantly less memory but on the other side does not support any other calls than #reparseTranslationUnit() to resume it or #disposeTranslationUnit() to dispose it completely. """, CXTranslationUnit("TU", "") ) void( "disposeTranslationUnit", "Destroy the specified CXTranslationUnit object.", CXTranslationUnit("TU", "") ) unsigned( "defaultReparseOptions", """ Returns the set of flags that is suitable for reparsing a translation unit. The set of flags returned provide options for {@code clang_reparseTranslationUnit()} by default. The returned flag set contains an unspecified set of optimizations geared toward common uses of reparsing. The set of optimizations enabled may change from one version to the next. """, CXTranslationUnit("TU", "") ) int( "reparseTranslationUnit", """ Reparse the source files that produced this translation unit. This routine can be used to re-parse the source files that originally created the given translation unit, for example because those source files have changed (either on disk or as passed via {@code unsaved_files}). The source code will be reparsed with the same command-line options as it was originally parsed. Reparsing a translation unit invalidates all cursors and source locations that refer into that translation unit. This makes reparsing a translation unit semantically equivalent to destroying the translation unit and then creating a new translation unit with the same command-line arguments. However, it may be more efficient to reparse a translation unit using this routine. """, CXTranslationUnit( "TU", """ the translation unit whose contents will be re-parsed. The translation unit must originally have been built with {@code clang_createTranslationUnitFromSourceFile()}. """ ), AutoSize("unsaved_files")..unsigned("num_unsaved_files", "the number of unsaved file entries in {@code unsaved_files}"), Input..nullable..CXUnsavedFile.p( "unsaved_files", """ the files that have not yet been saved to disk but may be required for parsing, including the contents of those files. The contents and name of these files (as specified by {@code CXUnsavedFile}) are copied when necessary, so the client only needs to guarantee their validity until the call to this function returns. """ ), unsigned( "options", """ a bitset of options composed of the flags in {@code CXReparse_Flags}. The function #defaultReparseOptions() produces a default set of options recommended for most uses, based on the translation unit. """ ), returnDoc = """ 0 if the sources could be reparsed. A non-zero error code will be returned if reparsing was impossible, such that the translation unit is invalid. In such cases, the only valid call for {@code TU} is #disposeTranslationUnit(). The error codes returned by this routine are described by the {@code CXErrorCode} enum. """ ) charUTF8.const.p( "getTUResourceUsageName", "Returns the human-readable null-terminated C string that represents the name of the memory category. This string should never be freed.", CXTUResourceUsageKind("kind", "") ) CXTUResourceUsage( "getCXTUResourceUsage", "Return the memory usage of a translation unit. This object should be released with #disposeCXTUResourceUsage().", CXTranslationUnit("TU", "") ) void( "disposeCXTUResourceUsage", "", CXTUResourceUsage("usage", "") ) CXTargetInfo( "getTranslationUnitTargetInfo", """ Get target information for this translation unit. The {@code CXTargetInfo} object cannot outlive the {@code CXTranslationUnit} object. """, CXTranslationUnit("CTUnit", "") ) void( "TargetInfo_dispose", "Destroy the {@code CXTargetInfo} object.", CXTargetInfo("Info", "") ) CXString( "TargetInfo_getTriple", """ Get the normalized target triple as a string. Returns the empty string in case of any error. """, CXTargetInfo("Info", "") ) int( "TargetInfo_getPointerWidth", """ Get the pointer width of the target in bits. Returns -1 in case of error. """, CXTargetInfo("Info", "") ) CXCursor("getNullCursor", "Retrieve the #NULL cursor, which represents no entity.", void()) CXCursor( "getTranslationUnitCursor", """ Retrieve the cursor that represents the given translation unit. The translation unit cursor can be used to start traversing the various declarations within the given translation unit. """, CXTranslationUnit("TU", "") ) unsignedb( "equalCursors", "Determine whether two cursors are equivalent.", CXCursor("A", ""), CXCursor("B", "") ) intb( "Cursor_isNull", "Returns non-zero if {@code cursor} is null.", CXCursor("cursor", "") ) unsigned( "hashCursor", "Compute a hash value for the given cursor.", CXCursor("cursor", "") ) CXCursorKind( "getCursorKind", "Retrieve the kind of the given cursor.", CXCursor("cursor", "") ) unsignedb( "isDeclaration", "Determine whether the given cursor kind represents a declaration.", CXCursorKind("kind", "") ) IgnoreMissing..unsignedb( "isInvalidDeclaration", """ Determine whether the given declaration is invalid. A declaration is invalid if it could not be parsed successfully. """, CXCursor("cursor", ""), returnDoc = "non-zero if the cursor represents a declaration and it is invalid, otherwise #NULL" ) unsignedb( "isReference", """ Determine whether the given cursor kind represents a simple reference. Note that other kinds of cursors (such as expressions) can also refer to other cursors. Use #getCursorReferenced() to determine whether a particular cursor refers to another entity. """, CXCursorKind("kind", "") ) unsignedb( "isExpression", "Determine whether the given cursor kind represents an expression.", CXCursorKind("kind", "") ) unsignedb( "isStatement", "Determine whether the given cursor kind represents a statement.", CXCursorKind("kind", "") ) unsignedb( "isAttribute", "Determine whether the given cursor kind represents an attribute.", CXCursorKind("kind", "") ) unsignedb( "Cursor_hasAttrs", "Determine whether the given cursor has any attributes.", CXCursor("C", "") ) unsignedb( "isInvalid", "Determine whether the given cursor kind represents an invalid cursor.", CXCursorKind("kind", "") ) unsignedb( "isTranslationUnit", "Determine whether the given cursor kind represents a translation unit.", CXCursorKind("kind", "") ) unsignedb( "isPreprocessing", "Determine whether the given cursor represents a preprocessing element, such as a preprocessor directive or macro instantiation.", CXCursorKind("kind", "") ) unsignedb( "isUnexposed", "Determine whether the given cursor represents a currently unexposed piece of the AST (e.g., CXCursor_UnexposedStmt).", CXCursorKind("kind", "") ) CXLinkageKind( "getCursorLinkage", "Determine the linkage of the entity referred to by a given cursor.", CXCursor("cursor", "") ) CXVisibilityKind( "getCursorVisibility", """ Describe the visibility of the entity referred to by a cursor. This returns the default visibility if not explicitly specified by a visibility attribute. The default visibility may be changed by commandline arguments. """, CXCursor("cursor", "the cursor to query"), returnDoc = "the visibility of the cursor" ) CXAvailabilityKind( "getCursorAvailability", "Determine the availability of the entity that this cursor refers to, taking the current target platform into account.", CXCursor("cursor", "the cursor to query"), returnDoc = "the availability of the cursor" ) int( "getCursorPlatformAvailability", """ Determine the availability of the entity that this cursor refers to on any platforms for which availability information is known. Note that the client is responsible for calling #disposeCXPlatformAvailability() to free each of the platform-availability structures returned. There are {@code min(N, availability_size)} such structures. """, CXCursor("cursor", "the cursor to query"), Check(1)..nullable..int.p("always_deprecated", "if non-#NULL, will be set to indicate whether the entity is deprecated on all platforms"), nullable..CXString.p( "deprecated_message", """ if non-#NULL, will be set to the message text provided along with the unconditional deprecation of this entity. The client is responsible for deallocating this string. """ ), Check(1)..nullable..int.p("always_unavailable", "if non-#NULL, will be set to indicate whether the entity is unavailable on all platforms"), nullable..CXString.p( "unavailable_message", """ if non-#NULL, will be set to the message text provided along with the unconditional unavailability of this entity. The client is responsible for deallocating this string. """ ), Check(1)..nullable..CXPlatformAvailability.p( "availability", """ if non-#NULL, an array of {@code CXPlatformAvailability} instances that will be populated with platform availability information, up to either the number of platforms for which availability information is available (as returned by this function) or {@code availability_size}, whichever is smaller """ ), AutoSize("availability")..int("availability_size", "the number of elements available in the {@code availability} array"), returnDoc = "the number of platforms (N) for which availability information is available (which is unrelated to {@code availability_size})" ) void( "disposeCXPlatformAvailability", "Free the memory associated with a {@code CXPlatformAvailability} structure.", CXPlatformAvailability.p("availability", "") ) IgnoreMissing..CXCursor( "Cursor_getVarDeclInitializer", "If cursor refers to a variable declaration and it has initializer returns cursor referring to the initializer otherwise return null cursor.", CXCursor("cursor", ""), since = "12" ) IgnoreMissing..int( "Cursor_hasVarDeclGlobalStorage", """ If cursor refers to a variable declaration that has global storage returns 1. If cursor refers to a variable declaration that doesn't have global storage returns 0. Otherwise returns -1. """, CXCursor("cursor", ""), since = "12" ) IgnoreMissing..int( "Cursor_hasVarDeclExternalStorage", """ If cursor refers to a variable declaration that has external storage returns 1. If cursor refers to a variable declaration that doesn't have external storage returns 0. Otherwise returns -1. """, CXCursor("cursor", ""), since = "12" ) CXLanguageKind( "getCursorLanguage", "Determine the \"language\" of the entity referred to by a given cursor.", CXCursor("cursor", "") ) IgnoreMissing..CXTLSKind( "getCursorTLSKind", "Determine the \"thread-local storage (TLS) kind\" of the declaration referred to by a cursor.", CXCursor("cursor", "") ) CXTranslationUnit( "Cursor_getTranslationUnit", "Returns the translation unit that a cursor originated from.", CXCursor("cursor", "") ) CXCursorSet("createCXCursorSet", "Creates an empty CXCursorSet.", void()) void( "disposeCXCursorSet", "Disposes a CXCursorSet and releases its associated memory.", CXCursorSet("cset", "") ) unsignedb( "CXCursorSet_contains", "Queries a CXCursorSet to see if it contains a specific CXCursor.", CXCursorSet("cset", ""), CXCursor("cursor", ""), returnDoc = "non-zero if the set contains the specified cursor" ) unsignedb( "CXCursorSet_insert", "Inserts a CXCursor into a CXCursorSet.", CXCursorSet("cset", ""), CXCursor("cursor", ""), returnDoc = "zero if the CXCursor was already in the set, and non-zero otherwise" ) CXCursor( "getCursorSemanticParent", """ Determine the semantic parent of the given cursor. The semantic parent of a cursor is the cursor that semantically contains the given {@code cursor}. For many declarations, the lexical and semantic parents are equivalent (the lexical parent is returned by #getCursorLexicalParent()). They diverge when declarations or definitions are provided out-of-line. For example: ${codeBlock(""" class C { void f(); }; void C::f() { }""")} In the out-of-line definition of {@code C::f}, the semantic parent is the class {@code C}, of which this function is a member. The lexical parent is the place where the declaration actually occurs in the source code; in this case, the definition occurs in the translation unit. In general, the lexical parent for a given entity can change without affecting the semantics of the program, and the lexical parent of different declarations of the same entity may be different. Changing the semantic parent of a declaration, on the other hand, can have a major impact on semantics, and redeclarations of a particular entity should all have the same semantic context. In the example above, both declarations of {@code C::f} have {@code C} as their semantic context, while the lexical context of the first {@code C::f} is {@code C} and the lexical context of the second {@code C::f} is the translation unit. For global declarations, the semantic parent is the translation unit. """, CXCursor("cursor", "") ) CXCursor( "getCursorLexicalParent", """ Determine the lexical parent of the given cursor. The lexical parent of a cursor is the cursor in which the given {@code cursor} was actually written. For many declarations, the lexical and semantic parents are equivalent (the semantic parent is returned by #getCursorSemanticParent()). They diverge when declarations or definitions are provided out-of-line. For example: ${codeBlock(""" class C { void f(); }; void C::f() { }""")} In the out-of-line definition of {@code C::f}, the semantic parent is the class {@code C}, of which this function is a member. The lexical parent is the place where the declaration actually occurs in the source code; in this case, the definition occurs in the translation unit. In general, the lexical parent for a given entity can change without affecting the semantics of the program, and the lexical parent of different declarations of the same entity may be different. Changing the semantic parent of a declaration, on the other hand, can have a major impact on semantics, and redeclarations of a particular entity should all have the same semantic context. In the example above, both declarations of {@code C::f} have {@code C} as their semantic context, while the lexical context of the first {@code C::f} is {@code C} and the lexical context of the second {@code C::f} is the translation unit. For declarations written in the global scope, the lexical parent is the translation unit. """, CXCursor("cursor", "") ) void( "getOverriddenCursors", """ Determine the set of methods that are overridden by the given method. In both Objective-C and C++, a method (aka virtual member function, in C++) can override a virtual method in a base class. For Objective-C, a method is said to override any method in the class's base class, its protocols, or its categories' protocols, that has the same selector and is of the same kind (class or instance). If no such method exists, the search continues to the class's superclass, its protocols, and its categories, and so on. A method from an Objective-C implementation is considered to override the same methods as its corresponding method in the interface. For C++, a virtual member function overrides any virtual member function with the same signature that occurs in its base classes. With multiple inheritance, a virtual member function can override several virtual member functions coming from different base classes. In all cases, this function determines the immediate overridden method, rather than all of the overridden methods. For example, if a method is originally declared in a class A, then overridden in B (which in inherits from A) and also in C (which inherited from B), then the only overridden method returned from this function when invoked on C's method will be B's method. The client may then invoke this function again, given the previously-found overridden methods, to map out the complete method-override set. """, CXCursor("cursor", "a cursor representing an Objective-C or C++ method. This routine will compute the set of methods that this method overrides."), Check(1)..CXCursor.p.p( "overridden", """ a pointer whose pointee will be replaced with a pointer to an array of cursors, representing the set of overridden methods. If there are no overridden methods, the pointee will be set to #NULL. The pointee must be freed via a call to #disposeOverriddenCursors(). """ ), Check(1)..unsigned.p( "num_overridden", "a pointer to the number of overridden functions, will be set to the number of overridden functions in the array pointed to by {@code overridden}" ) ) void( "disposeOverriddenCursors", "Free the set of overridden cursors returned by {@code clang_getOverriddenCursors()}.", Unsafe..CXCursor.p("overridden", "") ) CXFile( "getIncludedFile", "Retrieve the file that is included by the given inclusion directive cursor.", CXCursor("cursor", "") ) CXCursor( "getCursor", """ Map a source location to the cursor that describes the entity at that location in the source code. {@code clang_getCursor()} maps an arbitrary source location within a translation unit down to the most specific cursor that describes the entity at that location. For example, given an expression {@code x + y}, invoking {@code clang_getCursor()} with a source location pointing to "x" will return the cursor for "x"; similarly for "y". If the cursor points anywhere between "x" or "y" (e.g., on the + or the whitespace around it), clang_getCursor() will return a cursor referring to the "+" expression. """, CXTranslationUnit("TU", ""), CXSourceLocation("location", ""), returnDoc = "a cursor representing the entity at the given source location, or a #NULL cursor if no such entity can be found" ) CXSourceLocation( "getCursorLocation", """ Retrieve the physical location of the source constructor referenced by the given cursor. The location of a declaration is typically the location of the name of that declaration, where the name of that declaration would occur if it is unnamed, or some keyword that introduces that particular declaration. The location of a reference is where that reference occurs within the source code. """, CXCursor("cursor", "") ) CXSourceRange( "getCursorExtent", """ Retrieve the physical extent of the source construct referenced by the given cursor. The extent of a cursor starts with the file/line/column pointing at the first character within the source construct that the cursor refers to and ends with the last character within that source construct. For a declaration, the extent covers the declaration itself. For a reference, the extent covers the location of the reference (e.g., where the referenced entity was actually used). """, CXCursor("cursor", "") ) CXType( "getCursorType", "Retrieve the type of a {@code CXCursor} (if any).", CXCursor("C", "") ) CXString( "getTypeSpelling", """ Pretty-print the underlying type using the rules of the language of the translation unit from which it came. If the type is invalid, an empty string is returned. """, CXType("CT", "") ) CXType( "getTypedefDeclUnderlyingType", """ Retrieve the underlying type of a typedef declaration. If the cursor does not reference a typedef declaration, an invalid type is returned. """, CXCursor("C", "") ) CXType( "getEnumDeclIntegerType", """ Retrieve the integer type of an enum declaration. If the cursor does not reference an enum declaration, an invalid type is returned. """, CXCursor("C", "") ) long_long( "getEnumConstantDeclValue", """ Retrieve the integer value of an enum constant declaration as a signed long long. If the cursor does not reference an enum constant declaration, {@code LLONG_MIN} is returned. Since this is also potentially a valid constant value, the kind of the cursor must be verified before calling this function. """, CXCursor("C", "") ) unsigned_long_long( "getEnumConstantDeclUnsignedValue", """ Retrieve the integer value of an enum constant declaration as an unsigned long long. If the cursor does not reference an enum constant declaration, {@code ULLONG_MAX} is returned. Since this is also potentially a valid constant value, the kind of the cursor must be verified before calling this function. """, CXCursor("C", "") ) int( "getFieldDeclBitWidth", """ Retrieve the bit width of a bit field declaration as an integer. If a cursor that is not a bit field declaration is passed in, -1 is returned. """, CXCursor("C", "") ) int( "Cursor_getNumArguments", """ Retrieve the number of non-variadic arguments associated with a given cursor. The number of arguments can be determined for calls as well as for declarations of functions or methods. For other cursors -1 is returned. """, CXCursor("C", "") ) CXCursor( "Cursor_getArgument", """ Retrieve the argument cursor of a function or method. The argument cursor can be determined for calls as well as for declarations of functions or methods. For other cursors and for invalid indices, an invalid cursor is returned. """, CXCursor("C", ""), unsigned("i", "") ) int( "Cursor_getNumTemplateArguments", """ Returns the number of template args of a function decl representing a template specialization. If the argument cursor cannot be converted into a template function declaration, -1 is returned. For example, for the following declaration and specialization: ${codeBlock(""" template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo <float , -7, true>();""")} The value 3 would be returned from this call. """, CXCursor("C", "") ) CXTemplateArgumentKind( "Cursor_getTemplateArgumentKind", """ Retrieve the kind of the I'th template argument of the {@code CXCursor} {@code C}. If the argument {@code CXCursor} does not represent a {@code FunctionDecl}, an invalid template argument kind is returned. For example, for the following declaration and specialization: ${codeBlock(""" template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo <float , -7, true>();""")} For I = 0, 1, and 2, {@code Type}, {@code Integral}, and {@code Integral} will be returned, respectively. """, CXCursor("C", ""), unsigned("I", "") ) CXType( "Cursor_getTemplateArgumentType", """ Retrieve a {@code CXType} representing the type of a {@code TemplateArgument} of a function decl representing a template specialization. If the argument {@code CXCursor does} not represent a {@code FunctionDecl} whose {@code I}'th template argument has a kind of {@code CXTemplateArgKind_Integral}, an invalid type is returned. For example, for the following declaration and specialization: ${codeBlock(""" template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo <float , -7, true>();""")} If called with I = 0, "float", will be returned. Invalid types will be returned for I == 1 or 2. """, CXCursor("C", ""), unsigned("I", "") ) long_long( "Cursor_getTemplateArgumentValue", """ Retrieve the value of an {@code Integral} {@code TemplateArgument} (of a function decl representing a template specialization) as a {@code signed long long}. It is undefined to call this function on a {@code CXCursor} that does not represent a {@code FunctionDecl} or whose {@code I}'th template argument is not an integral value. For example, for the following declaration and specialization: ${codeBlock(""" template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo <float , -7, true>();""")} If called with I = 1 or 2, -7 or true will be returned, respectively. For I == 0, this function's behavior is undefined. """, CXCursor("C", ""), unsigned("I", "") ) unsigned_long_long( "Cursor_getTemplateArgumentUnsignedValue", """ Retrieve the value of an {@code Integral} {@code TemplateArgument} (of a function decl representing a template specialization) as an {@code unsigned long long}. It is undefined to call this function on a {@code CXCursor} that does not represent a {@code FunctionDecl} or whose {@code I}'th template argument is not an integral value. For example, for the following declaration and specialization: ${codeBlock(""" template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo <float , 2147483649, true>();""")} If called with I = 1 or 2, 2147483649 or true will be returned, respectively. For I == 0, this function's behavior is undefined. """, CXCursor("C", ""), unsigned("I", "") ) unsignedb( "equalTypes", "Determine whether two {@code CXTypes} represent the same type.", CXType("A", ""), CXType("B", ""), returnDoc = "non-zero if the {@code CXTypes} represent the same type and zero otherwise" ) CXType( "getCanonicalType", """ Return the canonical type for a {@code CXType}. Clang's type system explicitly models typedefs and all the ways a specific type can be represented. The canonical type is the underlying type with all the "sugar" removed. For example, if 'T' is a typedef for 'int', the canonical type for 'T' would be 'int'. """, CXType("T", "") ) unsignedb( "isConstQualifiedType", """ Determine whether a {@code CXType} has the "const" qualifier set, without looking through typedefs that may have added "const" at a different level. """, CXType("T", "") ) unsignedb( "Cursor_isMacroFunctionLike", "Determine whether a {@code CXCursor} that is a macro, is function like.", CXCursor("C", "") ) unsignedb( "Cursor_isMacroBuiltin", "Determine whether a {@code CXCursor} that is a macro, is a builtin one.", CXCursor("C", "") ) unsignedb( "Cursor_isFunctionInlined", "Determine whether a {@code CXCursor} that is a function declaration, is an inline declaration.", CXCursor("C", "") ) unsignedb( "isVolatileQualifiedType", """ Determine whether a {@code CXType} has the "volatile" qualifier set, without looking through typedefs that may have added "volatile" at a different level. """, CXType("T", "") ) unsignedb( "isRestrictQualifiedType", """ Determine whether a {@code CXType} has the "restrict" qualifier set, without looking through typedefs that may have added "restrict" at a different level. """, CXType("T", "") ) unsigned( "getAddressSpace", "Returns the address space of the given type.", CXType("T", "") ) CXString( "getTypedefName", "Returns the typedef name of the given type.", CXType("CT", "") ) CXType( "getPointeeType", "For pointer types, returns the type of the pointee.", CXType("T", "") ) CXCursor( "getTypeDeclaration", "Return the cursor for the declaration of the given type.", CXType("T", "") ) CXString( "getDeclObjCTypeEncoding", "Returns the Objective-C type encoding for the specified declaration.", CXCursor("C", "") ) CXString( "Type_getObjCEncoding", "Returns the Objective-C type encoding for the specified {@code CXType}.", CXType("type", "") ) CXString( "getTypeKindSpelling", "Retrieve the spelling of a given {@code CXTypeKind}.", CXTypeKind("K", "") ) CXCallingConv( "getFunctionTypeCallingConv", """ Retrieve the calling convention associated with a function type. If a non-function type is passed in, #CallingConv_Invalid is returned. """, CXType("T", "") ) CXType( "getResultType", """ Retrieve the return type associated with a function type. If a non-function type is passed in, an invalid type is returned. """, CXType("T", "") ) int( "getExceptionSpecificationType", """ Retrieve the exception specification type associated with a function type. This is a value of type {@code CXCursor_ExceptionSpecificationKind}. If a non-function type is passed in, an error code of -1 is returned. """, CXType("T", "") ) int( "getNumArgTypes", """ Retrieve the number of non-variadic parameters associated with a function type. If a non-function type is passed in, -1 is returned. """, CXType("T", "") ) CXType( "getArgType", """ Retrieve the type of a parameter of a function type. If a non-function type is passed in or the function does not have enough parameters, an invalid type is returned. """, CXType("T", ""), unsigned("i", "") ) IgnoreMissing..CXType( "Type_getObjCObjectBaseType", """ Retrieves the base type of the {@code ObjCObjectType}. If the type is not an ObjC object, an invalid type is returned. """, CXType("T", "") ) IgnoreMissing..unsigned( "Type_getNumObjCProtocolRefs", """ Retrieve the number of protocol references associated with an ObjC object/id. If the type is not an ObjC object, 0 is returned. """, CXType("T", "") ) IgnoreMissing..CXCursor( "Type_getObjCProtocolDecl", """ Retrieve the decl for a protocol reference for an ObjC object/id. If the type is not an ObjC object or there are not enough protocol references, an invalid cursor is returned. """, CXType("T", ""), unsigned("i", "") ) IgnoreMissing..unsigned( "Type_getNumObjCTypeArgs", """ Retrieve the number of type arguments associated with an ObjC object. If the type is not an ObjC object, 0 is returned. """, CXType("T", "") ) IgnoreMissing..CXType( "Type_getObjCTypeArg", """ Retrieve a type argument associated with an ObjC object. If the type is not an ObjC or the index is not valid, an invalid type is returned. """, CXType("T", ""), unsigned("i", "") ) unsignedb( "isFunctionTypeVariadic", "Return 1 if the {@code CXType} is a variadic function type, and 0 otherwise.", CXType("T", "") ) CXType( "getCursorResultType", """ Retrieve the return type associated with a given cursor. This only returns a valid type if the cursor refers to a function or method. """, CXCursor("C", "") ) int( "getCursorExceptionSpecificationType", """ Retrieve the exception specification type associated with a given cursor. This is a value of type {@code CXCursor_ExceptionSpecificationKind}. This only returns a valid result if the cursor refers to a function or method. """, CXCursor("C", "") ) unsignedb( "isPODType", "Return 1 if the {@code CXType} is a POD (plain old data) type, and 0 otherwise.", CXType("T", "") ) CXType( "getElementType", """ Return the element type of an array, complex, or vector type. If a type is passed in that is not an array, complex, or vector type, an invalid type is returned. """, CXType("T", "") ) long_long( "getNumElements", """ Return the number of elements of an array or vector type. If a type is passed in that is not an array or vector type, -1 is returned. """, CXType("T", "") ) CXType( "getArrayElementType", """ Return the element type of an array type. If a non-array type is passed in, an invalid type is returned. """, CXType("T", "") ) long_long( "getArraySize", """ Return the array size of a constant array. If a non-array type is passed in, -1 is returned. """, CXType("T", "") ) CXType( "Type_getNamedType", """ Retrieve the type named by the qualified-id. If a non-elaborated type is passed in, an invalid type is returned. """, CXType("T", "") ) unsignedb( "Type_isTransparentTagTypedef", """ Determine if a typedef is 'transparent' tag. A typedef is considered 'transparent' if it shares a name and spelling location with its underlying tag type, as is the case with the {@code NS_ENUM} macro. """, CXType("T", ""), returnDoc = "non-zero if transparent and zero otherwise" ) IgnoreMissing..CXTypeNullabilityKind( "Type_getNullability", "Retrieve the nullability kind of a pointer type.", CXType("T", "") ) long_long( "Type_getAlignOf", """ Return the alignment of a type in bytes as per {@code C++[expr.alignof]} standard. If the type declaration is invalid, #TypeLayoutError_Invalid is returned. If the type declaration is an incomplete type, #TypeLayoutError_Incomplete is returned. If the type declaration is a dependent type, #TypeLayoutError_Dependent is returned. If the type declaration is not a constant size type, #TypeLayoutError_NotConstantSize is returned. """, CXType("T", "") ) CXType( "Type_getClassType", """ Return the class type of an member pointer type. If a non-member-pointer type is passed in, an invalid type is returned. """, CXType("T", "") ) long_long( "Type_getSizeOf", """ Return the size of a type in bytes as per {@code C++[expr.sizeof]} standard. If the type declaration is invalid, #TypeLayoutError_Invalid is returned. If the type declaration is an incomplete type, #TypeLayoutError_Incomplete is returned. If the type declaration is a dependent type, #TypeLayoutError_Dependent is returned. """, CXType("T", "") ) long_long( "Type_getOffsetOf", """ Return the offset of a field named {@code S} in a record of type {@code T} in bits as it would be returned by {@code __offsetof__} as per {@code C++11[18.2p4]} If the cursor is not a record field declaration, #TypeLayoutError_Invalid is returned. If the field's type declaration is an incomplete type, #TypeLayoutError_Incomplete is returned. If the field's type declaration is a dependent type, #TypeLayoutError_Dependent is returned. If the field's name {@code S} is not found, #TypeLayoutError_InvalidFieldName is returned. """, CXType("T", ""), charUTF8.const.p("S", "") ) IgnoreMissing..CXType( "Type_getModifiedType", """ Return the type that was modified by this attributed type. If the type is not an attributed type, an invalid type is returned. """, CXType("T", "") ) IgnoreMissing..CXType( "Type_getValueType", """ Gets the type contained by this atomic type. If a non-atomic type is passed in, an invalid type is returned. """, CXType("CT", ""), since = "11" ) long_long( "Cursor_getOffsetOfField", """ Return the offset of the field represented by the Cursor. If the cursor is not a field declaration, -1 is returned. If the cursor semantic parent is not a record field declaration, #TypeLayoutError_Invalid is returned. If the field's type declaration is an incomplete type, #TypeLayoutError_Incomplete is returned. If the field's type declaration is a dependent type, #TypeLayoutError_Dependent is returned. If the field's name S is not found, #TypeLayoutError_InvalidFieldName is returned. """, CXCursor("C", "") ) unsignedb( "Cursor_isAnonymous", "Determine whether the given cursor represents an anonymous tag or namespace.", CXCursor("C", "") ) IgnoreMissing..unsignedb( "Cursor_isAnonymousRecordDecl", "Determine whether the given cursor represents an anonymous record declaration.", CXCursor("C", ""), since = "9" ) IgnoreMissing..unsignedb( "Cursor_isInlineNamespace", "Determine whether the given cursor represents an inline namespace declaration.", CXCursor("C", ""), since = "9" ) int( "Type_getNumTemplateArguments", "Returns the number of template arguments for given template specialization, or -1 if type {@code T} is not a template specialization.", CXType("T", "") ) CXType( "Type_getTemplateArgumentAsType", """ Returns the type template argument of a template class specialization at given index. This function only returns template type arguments and does not handle template template arguments or variadic packs. """, CXType("T", ""), unsigned("i", "") ) CXRefQualifierKind( "Type_getCXXRefQualifier", """ Retrieve the ref-qualifier kind of a function or method. The ref-qualifier is returned for C++ functions or methods. For other types or non-C++ declarations, #RefQualifier_None is returned. """, CXType("T", "") ) unsignedb( "Cursor_isBitField", "Returns non-zero if the cursor specifies a Record member that is a bitfield.", CXCursor("C", "") ) unsignedb( "isVirtualBase", "Returns 1 if the base class specified by the cursor with kind #Cursor_CXXBaseSpecifier is virtual.", CXCursor("cursor", "") ) CX_CXXAccessSpecifier( "getCXXAccessSpecifier", """ Returns the access control level for the referenced object. If the cursor refers to a C++ declaration, its access control level within its parent scope is returned. Otherwise, if the cursor refers to a base specifier or access specifier, the specifier itself is returned. """, CXCursor("cursor", "") ) CX_StorageClass( "Cursor_getStorageClass", """ Returns the storage class for a function or variable declaration. If the passed in Cursor is not a function or variable declaration, #_SC_Invalid is returned else the storage class. """, CXCursor("cursor", "") ) unsigned( "getNumOverloadedDecls", "Determine the number of overloaded declarations referenced by a #Cursor_OverloadedDeclRef cursor.", CXCursor("cursor", "the cursor whose overloaded declarations are being queried"), returnDoc = "the number of overloaded declarations referenced by {@code cursor}. If it is not a {@code CXCursor_OverloadedDeclRef} cursor, returns 0." ) CXCursor( "getOverloadedDecl", "Retrieve a cursor for one of the overloaded declarations referenced by a #Cursor_OverloadedDeclRef cursor.", CXCursor("cursor", "the cursor whose overloaded declarations are being queried"), unsigned("index", "the zero-based index into the set of overloaded declarations in the cursor"), returnDoc = """ a cursor representing the declaration referenced by the given {@code cursor} at the specified {@code index}. If the cursor does not have an associated set of overloaded declarations, or if the index is out of bounds, returns #getNullCursor(); """ ) CXType( "getIBOutletCollectionType", "For cursors representing an {@code iboutletcollection} attribute, this function returns the collection element type.", CXCursor("cursor", "") ) unsignedb( "visitChildren", """ Visit the children of a particular cursor. This function visits all the direct children of the given cursor, invoking the given {@code visitor} function with the cursors of each visited child. The traversal may be recursive, if the visitor returns #ChildVisit_Recurse. The traversal may also be ended prematurely, if the visitor returns #ChildVisit_Break. """, CXCursor( "parent", "the cursor whose child may be visited. All kinds of cursors can be visited, including invalid cursors (which, by definition, have no children)." ), CXCursorVisitor("visitor", "the visitor function that will be invoked for each child of {@code parent}"), nullable..CXClientData( "client_data", "pointer data supplied by the client, which will be passed to the visitor each time it is invoked" ), returnDoc = "a non-zero value if the traversal was terminated prematurely by the visitor returning #ChildVisit_Break" ) CXString( "getCursorUSR", """ Retrieve a Unified Symbol Resolution (USR) for the entity referenced by the given cursor. A Unified Symbol Resolution (USR) is a string that identifies a particular entity (function, class, variable, etc.) within a program. USRs can be compared across translation units to determine, e.g., when references in one translation refer to an entity defined in another translation unit. """, CXCursor("cursor", "") ) CXString( "constructUSR_ObjCClass", "Construct a USR for a specified Objective-C class.", charUTF8.const.p("class_name", "") ) CXString( "constructUSR_ObjCCategory", "Construct a USR for a specified Objective-C category.", charUTF8.const.p("class_name", ""), charUTF8.const.p("category_name", "") ) CXString( "constructUSR_ObjCProtocol", "Construct a USR for a specified Objective-C protocol.", charUTF8.const.p("protocol_name", "") ) CXString( "constructUSR_ObjCIvar", "Construct a USR for a specified Objective-C instance variable and the USR for its containing class.", charUTF8.const.p("name", ""), CXString("classUSR", "") ) CXString( "constructUSR_ObjCMethod", "Construct a USR for a specified Objective-C method and the USR for its containing class.", charUTF8.const.p("name", ""), unsignedb("isInstanceMethod", ""), CXString("classUSR", "") ) CXString( "constructUSR_ObjCProperty", "Construct a USR for a specified Objective-C property and the USR for its containing class.", charUTF8.const.p("property", ""), CXString("classUSR", "") ) CXString( "getCursorSpelling", "Retrieve a name for the entity referenced by this cursor.", CXCursor("cursor", "") ) CXSourceRange( "Cursor_getSpellingNameRange", """ Retrieve a range for a piece that forms the cursors spelling name. Most of the times there is only one range for the complete spelling but for Objective-C methods and Objective-C message expressions, there are multiple pieces for each selector identifier. """, CXCursor("cursor", ""), unsigned( "pieceIndex", "the index of the spelling name piece. If this is greater than the actual number of pieces, it will return a #NULL (invalid) range." ), unsigned("options", "reserved") ) IgnoreMissing..unsigned( "PrintingPolicy_getProperty", "Get a property value for the given printing policy.", CXPrintingPolicy("Policy", ""), CXPrintingPolicyProperty("Property", "") ) IgnoreMissing..void( "PrintingPolicy_setProperty", "Set a property value for the given printing policy.", CXPrintingPolicy("Policy", ""), CXPrintingPolicyProperty("Property", ""), unsigned("Value", "") ) IgnoreMissing..CXPrintingPolicy( "getCursorPrintingPolicy", """ Retrieve the default policy for the cursor. The policy should be released after use with {@code clang_PrintingPolicy_dispose}. """, CXCursor("cursor", "") ) IgnoreMissing..void( "PrintingPolicy_dispose", "Release a printing policy.", CXPrintingPolicy("Policy", "") ) IgnoreMissing..CXString( "getCursorPrettyPrinted", "Pretty print declarations.", CXCursor("Cursor", "the cursor representing a declaration"), CXPrintingPolicy("Policy", "the policy to control the entities being printed. If #NULL, a default policy is used."), returnDoc = "the pretty printed declaration or the empty string for other cursors" ) CXString( "getCursorDisplayName", """ Retrieve the display name for the entity referenced by this cursor. The display name contains extra information that helps identify the cursor, such as the parameters of a function or template or the arguments of a class template specialization. """, CXCursor("cursor", "") ) CXCursor( "getCursorReferenced", """ For a cursor that is a reference, retrieve a cursor representing the entity that it references. Reference cursors refer to other entities in the AST. For example, an Objective-C superclass reference cursor refers to an Objective-C class. This function produces the cursor for the Objective-C class from the cursor for the superclass reference. If the input cursor is a declaration or definition, it returns that declaration or definition unchanged. Otherwise, returns the #NULL cursor. """, CXCursor("cursor", "") ) CXCursor( "getCursorDefinition", """ For a cursor that is either a reference to or a declaration of some entity, retrieve a cursor that describes the definition of that entity. Some entities can be declared multiple times within a translation unit, but only one of those declarations can also be a definition. For example, given: ${codeBlock(""" int f(int, int); int g(int x, int y) { return f(x, y); } int f(int a, int b) { return a + b; } int f(int, int);""")} there are three declarations of the function "f", but only the second one is a definition. The {@code clang_getCursorDefinition()} function will take any cursor pointing to a declaration of "f" (the first or fourth lines of the example) or a cursor referenced that uses "f" (the call to "f' inside "g") and will return a declaration cursor pointing to the definition (the second "f" declaration). If given a cursor for which there is no corresponding definition, e.g., because there is no definition of that entity within this translation unit, returns a #NULL cursor. """, CXCursor("cursor", "") ) unsignedb( "isCursorDefinition", "Determine whether the declaration pointed to by this cursor is also a definition of that entity.", CXCursor("cursor", "") ) CXCursor( "getCanonicalCursor", """ Retrieve the canonical cursor corresponding to the given cursor. In the C family of languages, many kinds of entities can be declared several times within a single translation unit. For example, a structure type can be forward-declared (possibly multiple times) and later defined: ${codeBlock(""" struct X; struct X; struct X { int member; };""")} The declarations and the definition of {@code X} are represented by three different cursors, all of which are declarations of the same underlying entity. One of these cursor is considered the "canonical" cursor, which is effectively the representative for the underlying entity. One can determine if two cursors are declarations of the same underlying entity by comparing their canonical cursors. """, CXCursor("cursor", ""), returnDoc = "the canonical cursor for the entity referred to by the given cursor" ) int( "Cursor_getObjCSelectorIndex", """ If the cursor points to a selector identifier in an Objective-C method or message expression, this returns the selector index. After getting a cursor with #getCursor(), this can be called to determine if the location points to a selector identifier. """, CXCursor("cursor", ""), returnDoc = "the selector index if the cursor is an Objective-C method or message expression and the cursor is pointing to a selector identifier, or -1 otherwise" ) intb( "Cursor_isDynamicCall", """ Given a cursor pointing to a C++ method call or an Objective-C message, returns non-zero if the method/message is "dynamic", meaning: For a C++ method: the call is virtual. For an Objective-C message: the receiver is an object instance, not 'super' or a specific class. If the method/message is "static" or the cursor does not point to a method/message, it will return zero. """, CXCursor("C", "") ) CXType( "Cursor_getReceiverType", "Given a cursor pointing to an Objective-C message or property reference, or C++ method call, returns the {@code CXType} of the receiver.", CXCursor("C", "") ) unsigned( "Cursor_getObjCPropertyAttributes", """ Given a cursor that represents a property declaration, return the associated property attributes. The bits are formed from {@code CXObjCPropertyAttrKind}. """, CXCursor("C", ""), unsigned("reserved", "reserved for future use, pass 0") ) IgnoreMissing..CXString( "Cursor_getObjCPropertyGetterName", "Given a cursor that represents a property declaration, return the name of the method that implements the getter.", CXCursor("C", "") ) IgnoreMissing..CXString( "Cursor_getObjCPropertySetterName", "Given a cursor that represents a property declaration, return the name of the method that implements the setter, if any.", CXCursor("C", "") ) unsigned( "Cursor_getObjCDeclQualifiers", """ Given a cursor that represents an Objective-C method or parameter declaration, return the associated Objective-C qualifiers for the return type or the parameter respectively. The bits are formed from CXObjCDeclQualifierKind. """, CXCursor("C", "") ) unsignedb( "Cursor_isObjCOptional", """ Given a cursor that represents an Objective-C method or property declaration, return non-zero if the declaration was affected by "@optional". Returns zero if the cursor is not such a declaration or it is "@required". """, CXCursor("C", "") ) unsignedb( "Cursor_isVariadic", "Returns non-zero if the given cursor is a variadic function or method.", CXCursor("C", "") ) unsignedb( "Cursor_isExternalSymbol", "Returns non-zero if the given cursor points to a symbol marked with external_source_symbol attribute.", CXCursor("C", ""), Check(1)..nullable..CXString.p("language", "if non-#NULL, and the attribute is present, will be set to the 'language' string from the attribute"), Check(1)..nullable..CXString.p("definedIn", "if non-#NULL, and the attribute is present, will be set to the 'definedIn' string from the attribute"), Check(1)..nullable..unsigned.p( "isGenerated", "if non-#NULL, and the attribute is present, will be set to non-zero if the 'generated_declaration' is set in the attribute" ) ) CXSourceRange( "Cursor_getCommentRange", """ Given a cursor that represents a declaration, return the associated comment's source range. The range may include multiple consecutive comments with whitespace in between. """, CXCursor("C", "") ) CXString( "Cursor_getRawCommentText", "Given a cursor that represents a declaration, return the associated comment text, including comment markers.", CXCursor("C", "") ) CXString( "Cursor_getBriefCommentText", """ Given a cursor that represents a documentable entity (e.g., declaration), return the associated; otherwise return the first paragraph. """, CXCursor("C", "") ) CXString( "Cursor_getMangling", "Retrieve the {@code CXString} representing the mangled name of the cursor.", CXCursor("cursor", "") ) CXStringSet.p( "Cursor_getCXXManglings", "Retrieve the {@code CXString}s representing the mangled symbols of the C++ constructor or destructor at the cursor.", CXCursor("cursor", "") ) IgnoreMissing..CXStringSet.p( "Cursor_getObjCManglings", "Retrieve the {@code CXString}s representing the mangled symbols of the ObjC class interface or implementation at the cursor.", CXCursor("cursor", "") ) CXModule( "Cursor_getModule", "Given a #Cursor_ModuleImportDecl cursor, return the associated module.", CXCursor("C", "") ) CXModule( "getModuleForFile", "Given a {@code CXFile} header file, return the module that contains it, if one exists.", CXTranslationUnit("TU", ""), CXFile("file", "") ) CXFile( "Module_getASTFile", "", CXModule("Module", "a module object"), returnDoc = "the module file where the provided module object came from" ) CXModule( "Module_getParent", "", CXModule("Module", "a module object"), returnDoc = "the parent of a sub-module or #NULL if the given module is top-level, e.g. for 'std.vector' it will return the 'std' module." ) CXString( "Module_getName", "", CXModule("Module", "a module object"), returnDoc = "the name of the module, e.g. for the 'std.vector' sub-module it will return \"vector\"." ) CXString( "Module_getFullName", "", CXModule("Module", "a module object"), returnDoc = "the full name of the module, e.g. \"std.vector\"." ) intb( "Module_isSystem", "", CXModule("Module", "a module object"), returnDoc = "non-zero if the module is a system one" ) unsigned( "Module_getNumTopLevelHeaders", "", CXTranslationUnit("TU", ""), CXModule("Module", "a module object"), returnDoc = "the number of top level headers associated with this module" ) CXFile( "Module_getTopLevelHeader", "", CXTranslationUnit("TU", ""), CXModule("Module", "a module object"), unsigned("Index", "top level header index (zero-based)"), returnDoc = "the specified top level header associated with the module" ) unsignedb( "CXXConstructor_isConvertingConstructor", "Determine if a C++ constructor is a converting constructor.", CXCursor("C", "") ) unsignedb( "CXXConstructor_isCopyConstructor", "Determine if a C++ constructor is a copy constructor.", CXCursor("C", "") ) unsignedb( "CXXConstructor_isDefaultConstructor", "Determine if a C++ constructor is the default constructor.", CXCursor("C", "") ) unsignedb( "CXXConstructor_isMoveConstructor", "Determine if a C++ constructor is a move constructor.", CXCursor("C", "") ) unsignedb( "CXXField_isMutable", "Determine if a C++ field is declared 'mutable'.", CXCursor("C", "") ) unsignedb( "CXXMethod_isDefaulted", "Determine if a C++ method is declared '= default'.", CXCursor("C", "") ) unsignedb( "CXXMethod_isPureVirtual", "Determine if a C++ member function or member function template is pure virtual.", CXCursor("C", "") ) unsignedb( "CXXMethod_isStatic", "Determine if a C++ member function or member function template is declared 'static'.", CXCursor("C", "") ) unsignedb( "CXXMethod_isVirtual", """ Determine if a C++ member function or member function template is explicitly declared 'virtual' or if it overrides a virtual method from one of the base classes. """, CXCursor("C", "") ) IgnoreMissing..unsignedb( "CXXRecord_isAbstract", "Determine if a C++ record is abstract, i.e. whether a class or struct has a pure virtual member function.", CXCursor("C", "") ) unsignedb( "EnumDecl_isScoped", "Determine if an enum declaration refers to a scoped enum.", CXCursor("C", "") ) unsignedb( "CXXMethod_isConst", "Determine if a C++ member function or member function template is declared 'const'.", CXCursor("C", "") ) CXCursorKind( "getTemplateCursorKind", """ Given a cursor that represents a template, determine the cursor kind of the specializations would be generated by instantiating the template. This routine can be used to determine what flavor of function template, class template, or class template partial specialization is stored in the cursor. For example, it can describe whether a class template cursor is declared with "struct", "class" or "union". """, CXCursor("C", "the cursor to query. This cursor should represent a template declaration."), returnDoc = """ the cursor kind of the specializations that would be generated by instantiating the template {@code C}. If {@code C} is not a template, returns #Cursor_NoDeclFound. """ ) CXCursor( "getSpecializedCursorTemplate", """ Given a cursor that may represent a specialization or instantiation of a template, retrieve the cursor that represents the template that it specializes or from which it was instantiated. This routine determines the template involved both for explicit specializations of templates and for implicit instantiations of the template, both of which are referred to as "specializations". For a class template specialization (e.g., {@code std::vector<bool>}), this routine will return either the primary template ({@code std::vector}) or, if the specialization was instantiated from a class template partial specialization, the class template partial specialization. For a class template partial specialization and a function template specialization (including instantiations), this this routine will return the specialized template. For members of a class template (e.g., member functions, member classes, or static data members), returns the specialized or instantiated member. Although not strictly "templates" in the C++ language, members of class templates have the same notions of specializations and instantiations that templates do, so this routine treats them similarly. """, CXCursor("C", "a cursor that may be a specialization of a template or a member of a template"), returnDoc = """ if the given cursor is a specialization or instantiation of a template or a member thereof, the template or member that it specializes or from which it was instantiated. Otherwise, returns a #NULL cursor. """ ) CXSourceRange( "getCursorReferenceNameRange", "Given a cursor that references something else, return the source range covering that reference.", CXCursor("C", "a cursor pointing to a member reference, a declaration reference, or an operator call"), unsigned( "NameFlags", "a bitset with three independent flags: #NameRange_WantQualifier, #NameRange_WantTemplateArgs, and #NameRange_WantSinglePiece" ), unsigned( "PieceIndex", """ for contiguous names or when passing the flag #NameRange_WantSinglePiece, only one piece with index 0 is available. When the #NameRange_WantSinglePiece flag is not passed for a non-contiguous names, this index can be used to retrieve the individual pieces of the name. See also #NameRange_WantSinglePiece. """ ), returnDoc = """ the piece of the name pointed to by the given cursor. If there is no name, or if the {@code PieceIndex} is out-of-range, a null-cursor will be returned. """ ) IgnoreMissing..CXToken.p( "getToken", "Get the raw lexical token starting with the given location.", CXTranslationUnit("TU", "the translation unit whose text is being tokenized"), CXSourceLocation("Location", "the source location with which the token starts"), returnDoc = """ the token starting with the given location or #NULL if no such token exist. The returned pointer must be freed with #disposeTokens() before the translation unit is destroyed. """ ) CXTokenKind( "getTokenKind", "Determine the kind of the given token.", CXToken("token", "") ) CXString( "getTokenSpelling", """ Determine the spelling of the given token. The spelling of a token is the textual representation of that token, e.g., the text of an identifier or keyword. """, CXTranslationUnit("TU", ""), CXToken("token", "") ) CXSourceLocation( "getTokenLocation", "Retrieve the source location of the given token.", CXTranslationUnit("TU", ""), CXToken("token", "") ) CXSourceRange( "getTokenExtent", "Retrieve a source range that covers the given token.", CXTranslationUnit("TU", ""), CXToken("token", "") ) void( "tokenize", "Tokenize the source code described by the given range into raw lexical tokens.", CXTranslationUnit("TU", "the translation unit whose text is being tokenized"), CXSourceRange( "Range", "the source range in which text should be tokenized. All of the tokens produced by tokenization will fall within this source range," ), Check(1)..CXToken.p.p( "Tokens", """ this pointer will be set to point to the array of tokens that occur within the given source range. The returned pointer must be freed with #disposeTokens() before the translation unit is destroyed. """ ), Check(1)..unsigned.p("NumTokens", "will be set to the number of tokens in the {@code *Tokens} array") ) void( "annotateTokens", """ Annotate the given set of tokens by providing cursors for each token that can be mapped to a specific entity within the abstract syntax tree. This token-annotation routine is equivalent to invoking #getCursor() for the source locations of each of the tokens. The cursors provided are filtered, so that only those cursors that have a direct correspondence to the token are accepted. For example, given a function call {@code f(x)}, {@code clang_getCursor()} would provide the following cursors: ${ul( "when the cursor is over the 'f', a DeclRefExpr cursor referring to 'f'.", "when the cursor is over the '(' or the ')', a CallExpr referring to 'f'.", "when the cursor is over the 'x', a DeclRefExpr cursor referring to 'x'." )} Only the first and last of these cursors will occur within the annotate, since the tokens "f" and "x' directly refer to a function and a variable, respectively, but the parentheses are just a small part of the full syntax of the function call expression, which is not provided as an annotation. """, CXTranslationUnit("TU", "the translation unit that owns the given tokens"), Input..CXToken.p("Tokens", "the set of tokens to annotate"), AutoSize("Tokens", "Cursors")..unsigned("NumTokens", "the number of tokens in {@code Tokens}"), CXCursor.p("Cursors", "an array of {@code NumTokens} cursors, whose contents will be replaced with the cursors corresponding to each token") ) void( "disposeTokens", "Free the given set of tokens.", CXTranslationUnit("TU", ""), Input..CXToken.p("Tokens", ""), AutoSize("Tokens")..unsigned("NumTokens", "") ) CXString( "getCursorKindSpelling", "", CXCursorKind("Kind", "") ) void( "getDefinitionSpellingAndExtent", "", CXCursor("cursor", ""), Check(1)..nullable..char.const.p.p("startBuf", ""), Check(1)..nullable..char.const.p.p("endBuf", ""), Check(1)..nullable..unsigned.p("startLine", ""), Check(1)..nullable..unsigned.p("startColumn", ""), Check(1)..nullable..unsigned.p("endLine", ""), Check(1)..nullable..unsigned.p("endColumn", "") ) void("enableStackTraces", "", void()) void( "executeOnThread", "", CXExecuteOnThread("fn", ""), nullable..opaque_p("user_data", ""), unsigned("stack_size", "") ) CXCompletionChunkKind( "getCompletionChunkKind", "Determine the kind of a particular chunk within a completion string.", CXCompletionString("completion_string", "the completion string to query"), unsigned("chunk_number", "the 0-based index of the chunk in the completion string"), returnDoc = "the kind of the chunk at the index {@code chunk_number}" ) CXString( "getCompletionChunkText", "Retrieve the text associated with a particular chunk within a completion string.", CXCompletionString("completion_string", "the completion string to query"), unsigned("chunk_number", "the 0-based index of the chunk in the completion string"), returnDoc = "the text associated with the chunk at index {@code chunk_number}" ) CXCompletionString( "getCompletionChunkCompletionString", "Retrieve the completion string associated with a particular chunk within a completion string.", CXCompletionString("completion_string", "the completion string to query"), unsigned("chunk_number", "the 0-based index of the chunk in the completion string"), returnDoc = "the completion string associated with the chunk at index {@code chunk_number}" ) unsigned( "getNumCompletionChunks", "Retrieve the number of chunks in the given code-completion string.", CXCompletionString("completion_string", "") ) unsigned( "getCompletionPriority", """ Determine the priority of this code completion. The priority of a code completion indicates how likely it is that this particular completion is the completion that the user will select. The priority is selected by various internal heuristics. """, CXCompletionString("completion_string", "the completion string to query"), returnDoc = "the priority of this completion string. Smaller values indicate higher-priority (more likely) completions." ) CXAvailabilityKind( "getCompletionAvailability", "Determine the availability of the entity that this code-completion string refers to.", CXCompletionString("completion_string", "the completion string to query"), returnDoc = "the availability of the completion string" ) unsigned( "getCompletionNumAnnotations", "Retrieve the number of annotations associated with the given completion string.", CXCompletionString("completion_string", "the completion string to query"), returnDoc = "the number of annotations associated with the given completion string" ) CXString( "getCompletionAnnotation", "Retrieve the annotation associated with the given completion string.", CXCompletionString("completion_string", "the completion string to query"), unsigned("annotation_number", "the 0-based index of the annotation of the completion string"), returnDoc = "annotation string associated with the completion at index {@code annotation_number}, or a #NULL string if that annotation is not available" ) CXString( "getCompletionParent", """ Retrieve the parent context of the given completion string. The parent context of a completion string is the semantic parent of the declaration (if any) that the code completion represents. For example, a code completion for an Objective-C method would have the method's class or protocol as its context. """, CXCompletionString("completion_string", "the code completion string whose parent is being queried"), Check(1)..nullable..CXCursorKind.p("kind", "DEPRECATED: always set to #Cursor_NotImplemented if non-#NULL"), returnDoc = "the name of the completion parent, e.g., \"NSObject\" if the completion string represents a method in the {@code NSObject} class." ) CXString( "getCompletionBriefComment", "Retrieve the brief documentation comment attached to the declaration that corresponds to the given completion string.", CXCompletionString("completion_string", "") ) CXCompletionString( "getCursorCompletionString", "Retrieve a completion string for an arbitrary declaration or macro definition cursor.", CXCursor("cursor", "the cursor to query"), returnDoc = "a non-context-sensitive completion string for declaration and macro definition cursors, or #NULL for other kinds of cursors" ) IgnoreMissing..unsigned( "getCompletionNumFixIts", """ Retrieve the number of fix-its for the given completion index. Calling this makes sense only if #CodeComplete_IncludeCompletionsWithFixIts option was set. """, CXCodeCompleteResults.p("results", "the structure keeping all completion results"), unsigned("completion_index", "the index of the completion"), returnDoc = "the number of fix-its which must be applied before the completion at {@code completion_index} can be applied" ) IgnoreMissing..CXString( "getCompletionFixIt", """ Fix-its that <b>must</b> be applied before inserting the text for the corresponding completion. By default, #codeCompleteAt() only returns completions with empty fix-its. Extra completions with non-empty fix-its should be explicitly requested by setting #CodeComplete_IncludeCompletionsWithFixIts. For the clients to be able to compute position of the cursor after applying fix-its, the following conditions are guaranteed to hold for {@code replacement_range} of the stored fix-its: ${ul( """ Ranges in the fix-its are guaranteed to never contain the completion point (or identifier under completion point, if any) inside them, except at the start or at the end of the range. """, """ If a fix-it range starts or ends with completion point (or starts or ends after the identifier under completion point), it will contain at least one character. It allows to unambiguously recompute completion point after applying the fix-it. """ )} The intuition is that provided fix-its change code around the identifier we complete, but are not allowed to touch the identifier itself or the completion point. One example of completions with corrections are the ones replacing '.' with '-&gt;' and vice versa: {@code std::unique_ptr<std::vector<int>> vec_ptr;} In 'vec_ptr.^', one of the completions is 'push_back', it requires replacing '.' with '-&gt;'. In 'vec_ptr-&gt;^', one of the completions is 'release', it requires replacing '-&gt;' with '.'. """, CXCodeCompleteResults.p("results", "the structure keeping all completion results"), unsigned("completion_index", "the index of the completion"), unsigned("fixit_index", "the index of the fix-it for the completion at {@code completion_index}"), CXSourceRange.p("replacement_range", "the fix-it range that must be replaced before the completion at completion_index can be applied"), returnDoc = "the fix-it string that must replace the code at replacement_range before the completion at completion_index can be applied" ) unsigned("defaultCodeCompleteOptions", "Returns a default set of code-completion options that can be passed to #codeCompleteAt().", void()) CXCodeCompleteResults.p( "codeCompleteAt", """ Perform code completion at a given location in a translation unit. This function performs code completion at a particular file, line, and column within source code, providing results that suggest potential code snippets based on the context of the completion. The basic model for code completion is that Clang will parse a complete source file, performing syntax checking up to the location where code-completion has been requested. At that point, a special code-completion token is passed to the parser, which recognizes this token and determines, based on the current location in the C/Objective-C/C++ grammar and the state of semantic analysis, what completions to provide. These completions are returned via a new {@code CXCodeCompleteResults} structure. Code completion itself is meant to be triggered by the client when the user types punctuation characters or whitespace, at which point the code-completion location will coincide with the cursor. For example, if {@code p} is a pointer, code-completion might be triggered after the "-" and then after the "&gt;" in {@code p->}. When the code-completion location is after the "&gt;", the completion results will provide, e.g., the members of the struct that "p" points to. The client is responsible for placing the cursor at the beginning of the token currently being typed, then filtering the results based on the contents of the token. For example, when code-completing for the expression {@code p->get}, the client should provide the location just after the "&gt;" (e.g., pointing at the "g") to this code-completion hook. Then, the client can filter the results based on the current token text ("get"), only showing those results that start with "get". The intent of this interface is to separate the relatively high-latency acquisition of code-completion results from the filtering of results on a per-character basis, which must have a lower latency. """, CXTranslationUnit( "TU", """ the translation unit in which code-completion should occur. The source files for this translation unit need not be completely up-to-date (and the contents of those source files may be overridden via {@code unsaved_files}). Cursors referring into the translation unit may be invalidated by this invocation. """ ), charUTF8.const.p( "complete_filename", "the name of the source file where code completion should be performed. This filename may be any file included in the translation unit." ), unsigned("complete_line", "the line at which code-completion should occur"), unsigned( "complete_column", """ the column at which code-completion should occur. Note that the column should point just after the syntactic construct that initiated code completion, and not in the middle of a lexical token. """ ), nullable..CXUnsavedFile.p( "unsaved_files", """ the Files that have not yet been saved to disk but may be required for parsing or code completion, including the contents of those files. The contents and name of these files (as specified by {@code CXUnsavedFile}) are copied when necessary, so the client only needs to guarantee their validity until the call to this function returns. """ ), AutoSize("unsaved_files")..unsigned("num_unsaved_files", "the number of unsaved file entries in {@code unsaved_files}"), unsigned( "options", """ extra options that control the behavior of code completion, expressed as a bitwise OR of the enumerators of the {@code CXCodeComplete_Flags} enumeration. The #defaultCodeCompleteOptions() function returns a default set of code-completion options. """ ), returnDoc = """ if successful, a new {@code CXCodeCompleteResults} structure containing code-completion results, which should eventually be freed with #disposeCodeCompleteResults(). If code completion fails, returns #NULL. """ ) void( "sortCodeCompletionResults", "Sort the code-completion results in case-insensitive alphabetical order.", CXCompletionResult.p("Results", "the set of results to sort"), AutoSize("Results")..unsigned("NumResults", "the number of results in {@code Results}") ) void( "disposeCodeCompleteResults", "Free the given set of code-completion results.", CXCodeCompleteResults.p("Results", "") ) unsigned( "codeCompleteGetNumDiagnostics", "Determine the number of diagnostics produced prior to the location where code completion was performed.", CXCodeCompleteResults.p("Results", "") ) CXDiagnostic( "codeCompleteGetDiagnostic", "Retrieve a diagnostic associated with the given code completion.", CXCodeCompleteResults.p("Results", "the code completion results to query"), unsigned("Index", "the zero-based diagnostic number to retrieve"), returnDoc = "the requested diagnostic. This diagnostic must be freed via a call to #disposeDiagnostic()." ) unsigned_long_long( "codeCompleteGetContexts", "Determines what completions are appropriate for the context the given code completion.", CXCodeCompleteResults.p("Results", "the code completion results to query"), returnDoc = "the kinds of completions that are appropriate for use along with the given code completion results" ) CXCursorKind( "codeCompleteGetContainerKind", """ Returns the cursor kind for the container for the current code completion context. The container is only guaranteed to be set for contexts where a container exists (i.e. member accesses or Objective-C message sends); if there is not a container, this function will return #Cursor_InvalidCode. """, CXCodeCompleteResults.p("Results", "the code completion results to query"), Check(1)..unsigned.p( "IsIncomplete", """ on return, this value will be false if Clang has complete information about the container. If Clang does not have complete information, this value will be true. """ ), returnDoc = "the container kind, or #Cursor_InvalidCode if there is not a container" ) CXString( "codeCompleteGetContainerUSR", """ Returns the USR for the container for the current code completion context. If there is not a container for the current context, this function will return the empty string. """, CXCodeCompleteResults.p("Results", "the code completion results to query"), returnDoc = "the USR for the container" ) CXString( "codeCompleteGetObjCSelector", """ Returns the currently-entered selector for an Objective-C message send, formatted like "initWithFoo:bar:". Only guaranteed to return a non-empty string for #CompletionContext_ObjCInstanceMessage and #CompletionContext_ObjCClassMessage. """, CXCodeCompleteResults.p("Results", "the code completion results to query"), returnDoc = "the selector (or partial selector) that has been entered thus far for an Objective-C message send" ) CXString( "getClangVersion", "Return a version string, suitable for showing to a user, but not intended to be parsed (the format is not guaranteed to be stable).", void() ) void( "toggleCrashRecovery", "Enable/disable crash recovery.", unsignedb("isEnabled", "flag to indicate if crash recovery is enabled. A non-zero value enables crash recovery, while 0 disables it.") ) void( "getInclusions", """ Visit the set of preprocessor inclusions in a translation unit. The visitor function is called with the provided data for every included file. This does not include headers included by the PCH file (unless one is inspecting the inclusions in the PCH file itself). """, CXTranslationUnit("tu", ""), CXInclusionVisitor("visitor", ""), nullable..CXClientData("client_data", "") ) CXEvalResult( "Cursor_Evaluate", """ If cursor is a statement declaration tries to evaluate the statement and if its variable, tries to evaluate its initializer, into its corresponding type. If it's an expression, tries to evaluate the expression. """, CXCursor("C", "") ) CXEvalResultKind( "EvalResult_getKind", "Returns the kind of the evaluated result.", CXEvalResult("E", "") ) int( "EvalResult_getAsInt", "Returns the evaluation result as integer if the kind is Int.", CXEvalResult("E", "") ) long_long( "EvalResult_getAsLongLong", """ Returns the evaluation result as a long long integer if the kind is Int. This prevents overflows that may happen if the result is returned with #EvalResult_getAsInt(). """, CXEvalResult("E", "") ) unsignedb( "EvalResult_isUnsignedInt", "Returns a non-zero value if the kind is Int and the evaluation result resulted in an unsigned integer.", CXEvalResult("E", "") ) unsigned_long_long( "EvalResult_getAsUnsigned", "Returns the evaluation result as an unsigned integer if the kind is Int and #EvalResult_isUnsignedInt() is non-zero.", CXEvalResult("E", "") ) double( "EvalResult_getAsDouble", "Returns the evaluation result as double if the kind is double.", CXEvalResult("E", "") ) charUTF8.const.p( "EvalResult_getAsStr", """ Returns the evaluation result as a constant string if the kind is other than Int or float. User must not free this pointer, instead call #EvalResult_dispose() on the {@code CXEvalResult} returned by #Cursor_Evaluate(). """, CXEvalResult("E", "") ) void( "EvalResult_dispose", "Disposes the created {@code Eval} memory.", CXEvalResult("E", "") ) CXRemapping( "getRemappings", "Retrieve a remapping.", charUTF8.const.p("path", "the path that contains metadata about remappings"), returnDoc = "the requested remapping. This remapping must be freed via a call to #remap_dispose(). Can return #NULL if an error occurred." ) CXRemapping( "getRemappingsFromFileList", "Retrieve a remapping.", charUTF8.const.p.p("filePaths", "pointer to an array of file paths containing remapping info"), AutoSize("filePaths")..unsigned("numFiles", "number of file paths"), returnDoc = "the requested remapping. This remapping must be freed via a call to #remap_dispose(). Can return #NULL if an error occurred." ) unsigned( "remap_getNumFiles", "Determine the number of remappings.", CXRemapping("Remapping", "") ) void( "remap_getFilenames", "Get the original and the associated filename from the remapping.", CXRemapping("Remapping", ""), unsigned("index", ""), nullable..CXString.p("original", "if non-#NULL, will be set to the original filename"), nullable..CXString.p("transformed", "if non-#NULL, will be set to the filename that the original is associated with") ) void( "remap_dispose", "Dispose the remapping.", CXRemapping("Remapping", "") ) CXResult( "findReferencesInFile", "Find references of a declaration in a specific file.", CXCursor("cursor", "pointing to a declaration or a reference of one"), CXFile("file", "to search for references"), CXCursorAndRangeVisitor( "visitor", """ callback that will receive pairs of {@code CXCursor/CXSourceRange} for each reference found. The {@code CXSourceRange} will point inside the file; if the reference is inside a macro (and not a macro argument) the {@code CXSourceRange} will be invalid. """ ), returnDoc = "one of the {@code CXResult} enumerators" ) CXResult( "findIncludesInFile", "Find {@code \\#import/\\#include} directives in a specific file.", CXTranslationUnit("TU", "translation unit containing the file to query"), CXFile("file", "to search for {@code \\#import/\\#include} directives"), CXCursorAndRangeVisitor("visitor", "callback that will receive pairs of {@code CXCursor/CXSourceRange} for each directive found"), returnDoc = "one of the CXResult enumerators" ) intb( "index_isEntityObjCContainerKind", "", CXIdxEntityKind("kind", "") ) CXIdxObjCContainerDeclInfo.const.p( "index_getObjCContainerDeclInfo", "", CXIdxDeclInfo.const.p("info", "") ) CXIdxObjCInterfaceDeclInfo.const.p( "index_getObjCInterfaceDeclInfo", "", CXIdxDeclInfo.const.p("info", "") ) CXIdxObjCCategoryDeclInfo.const.p( "index_getObjCCategoryDeclInfo", "", CXIdxDeclInfo.const.p("info", "") ) CXIdxObjCProtocolRefListInfo.const.p( "index_getObjCProtocolRefListInfo", "", CXIdxDeclInfo.const.p("info", "") ) CXIdxObjCPropertyDeclInfo.const.p( "index_getObjCPropertyDeclInfo", "", CXIdxDeclInfo.const.p("info", "") ) CXIdxIBOutletCollectionAttrInfo.const.p( "index_getIBOutletCollectionAttrInfo", "", CXIdxAttrInfo.const.p("info", "") ) CXIdxCXXClassDeclInfo.const.p( "index_getCXXClassDeclInfo", "", CXIdxDeclInfo.const.p("info", "") ) CXIdxClientContainer( "index_getClientContainer", "For retrieving a custom {@code CXIdxClientContainer} attached to a container.", CXIdxContainerInfo.const.p("info", "") ) void( "index_setClientContainer", "For setting a custom {@code CXIdxClientContainer} attached to a container.", CXIdxContainerInfo.const.p("info", ""), CXIdxClientContainer("container", "") ) CXIdxClientEntity( "index_getClientEntity", "For retrieving a custom {@code CXIdxClientEntity} attached to an entity.", CXIdxEntityInfo.const.p("info", "") ) void( "index_setClientEntity", "For setting a custom {@code CXIdxClientEntity} attached to an entity.", CXIdxEntityInfo.const.p("info", ""), CXIdxClientEntity("entity", "") ) CXIndexAction( "IndexAction_create", "An indexing action/session, to be applied to one or multiple translation units.", CXIndex("CIdx", "the index object with which the index action will be associated") ) void( "IndexAction_dispose", """ Destroy the given index action. The index action must not be destroyed until all of the translation units created within that index action have been destroyed. """, CXIndexAction("action", "") ) int( "indexSourceFile", """ Index the given source file and the translation unit corresponding to that file via callbacks implemented through ##IndexerCallbacks. The rest of the parameters are the same as #parseTranslationUnit(). """, CXIndexAction("action", ""), nullable..CXClientData("client_data", "pointer data supplied by the client, which will be passed to the invoked callbacks"), IndexerCallbacks.p("index_callbacks", "pointer to indexing callbacks that the client implements"), unsigned("index_callbacks_size", "size of ##IndexerCallbacks structure that gets passed in {@code index_callbacks}"), unsigned( "index_options", "a bitmask of options that affects how indexing is performed. This should be a bitwise OR of the {@code CXIndexOpt_XXX} flags." ), charUTF8.const.p("source_filename", ""), nullable..charUTF8.const.p.const.p("command_line_args", ""), AutoSize("command_line_args")..int("num_command_line_args", ""), nullable..CXUnsavedFile.p("unsaved_files", ""), AutoSize("unsaved_files")..unsigned("num_unsaved_files", ""), Check(1)..nullable..CXTranslationUnit.p( "out_TU", "pointer to store a {@code CXTranslationUnit} that can be reused after indexing is finished. Set to #NULL if you do not require it." ), unsigned("TU_options", ""), returnDoc = """ 0 on success or if there were errors from which the compiler could recover. If there is a failure from which there is no recovery, returns a non-zero {@code CXErrorCode}. """ ) int( "indexSourceFileFullArgv", """ Same as #indexSourceFile() but requires a full command line for {@code command_line_args} including {@code argv[0]}. This is useful if the standard library paths are relative to the binary. """, CXIndexAction("action", ""), nullable..CXClientData("client_data", ""), IndexerCallbacks.p("index_callbacks", ""), unsigned("index_callbacks_size", ""), unsigned("index_options", ""), charUTF8.const.p("source_filename", ""), charUTF8.const.p.const.p("command_line_args", ""), AutoSize("command_line_args")..int("num_command_line_args", ""), nullable..CXUnsavedFile.p("unsaved_files", ""), AutoSize("unsaved_files")..unsigned("num_unsaved_files", ""), Check(1)..nullable..CXTranslationUnit.p("out_TU", ""), unsigned("TU_options", "") ) intb( "indexTranslationUnit", """ Index the given translation unit via callbacks implemented through ##IndexerCallbacks. The order of callback invocations is not guaranteed to be the same as when indexing a source file. The high level order will be: ${ul( "Preprocessor callbacks invocations", "Declaration/reference callbacks invocations", "Diagnostic callback invocations" )} The parameters are the same as #indexSourceFile(). """, CXIndexAction("action", ""), nullable..CXClientData("client_data", ""), IndexerCallbacks.p("index_callbacks", ""), unsigned("index_callbacks_size", ""), unsigned("index_options", ""), CXTranslationUnit("TU", ""), returnDoc = "if there is a failure from which there is no recovery, returns non-zero, otherwise returns 0" ) void( "indexLoc_getFileLocation", """ Retrieve the {@code CXIdxFile}, file, line, column, and offset represented by the given {@code CXIdxLoc}. If the location refers into a macro expansion, retrieves the location of the macro expansion and if it refers into a macro argument retrieves the location of the argument. """, CXIdxLoc("loc", ""), Check(1)..nullable..CXIdxClientFile.p("indexFile", ""), Check(1)..nullable..CXFile.p("file", ""), Check(1)..nullable..unsigned.p("line", ""), Check(1)..nullable..unsigned.p("column", ""), Check(1)..nullable..unsigned.p("offset", "") ) CXSourceLocation( "indexLoc_getCXSourceLocation", "Retrieve the {@code CXSourceLocation} represented by the given {@code CXIdxLoc}.", CXIdxLoc("loc", "") ) unsignedb( "Type_visitFields", """ Visit the fields of a particular type. This function visits all the direct fields of the given cursor, invoking the given {@code visitor} function with the cursors of each visited field. The traversal may be ended prematurely, if the visitor returns #Visit_Break. """, CXType("T", "the record type whose field may be visited"), CXFieldVisitor("visitor", "the visitor function that will be invoked for each field of {@code T}"), nullable..CXClientData( "client_data", "pointer data supplied by the client, which will be passed to the visitor each time it is invoked" ), returnDoc = "a non-zero value if the traversal was terminated prematurely by the visitor returning #Visit_Break" ) }
bsd-3-clause
fd4ee1e48e88a1b07761db4a6ec65b37
38.511994
160
0.636578
4.969359
false
false
false
false
mdanielwork/intellij-community
platform/configuration-store-impl/src/XmlElementStorage.kt
1
15228
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.openapi.components.PathMacroManager import com.intellij.openapi.components.PathMacroSubstitutor import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.vfs.safeOutputStream import com.intellij.util.LineSeparator import com.intellij.util.SmartList import com.intellij.util.containers.SmartHashSet import com.intellij.util.io.delete import com.intellij.util.loadElement import gnu.trove.THashMap import org.jdom.Attribute import org.jdom.Element import java.io.FileNotFoundException import java.io.OutputStream import java.io.Writer import java.nio.file.Path abstract class XmlElementStorage protected constructor(val fileSpec: String, protected val rootElementName: String?, private val pathMacroSubstitutor: PathMacroSubstitutor? = null, roamingType: RoamingType? = RoamingType.DEFAULT, private val provider: StreamProvider? = null) : StorageBaseEx<StateMap>() { val roamingType: RoamingType = roamingType ?: RoamingType.DEFAULT protected abstract fun loadLocalData(): Element? final override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? = storageData.getState(componentName, archive) override fun archiveState(storageData: StateMap, componentName: String, serializedState: Element?) { storageData.archive(componentName, serializedState) } override fun hasState(storageData: StateMap, componentName: String): Boolean = storageData.hasState(componentName) override fun loadData(): StateMap = loadElement()?.let { loadState(it) } ?: StateMap.EMPTY private fun loadElement(useStreamProvider: Boolean = true): Element? { var element: Element? = null try { val isLoadLocalData: Boolean if (useStreamProvider && provider != null) { isLoadLocalData = !provider.read(fileSpec, roamingType) { inputStream -> inputStream?.let { element = loadElement(inputStream) providerDataStateChanged(createDataWriterForElement(element!!), DataStateChanged.LOADED) } } } else { isLoadLocalData = true } if (isLoadLocalData) { element = loadLocalData() } } catch (e: FileNotFoundException) { throw e } catch (e: Throwable) { LOG.error("Cannot load data for $fileSpec", e) } return element } protected open fun providerDataStateChanged(writer: DataWriter?, type: DataStateChanged) { } private fun loadState(element: Element): StateMap { beforeElementLoaded(element) return StateMap.fromMap(FileStorageCoreUtil.load(element, pathMacroSubstitutor)) } fun setDefaultState(element: Element) { element.name = rootElementName!! storageDataRef.set(loadState(element)) } override fun createSaveSessionProducer(): StateStorage.SaveSessionProducer? = if (checkIsSavingDisabled()) null else createSaveSession(getStorageData()) protected abstract fun createSaveSession(states: StateMap): StateStorage.SaveSessionProducer override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<in String>) { val oldData = storageDataRef.get() val newData = getStorageData(true) if (oldData == null) { LOG.debug { "analyzeExternalChangesAndUpdateIfNeed: old data null, load new for ${toString()}" } componentNames.addAll(newData.keys()) } else { val changedComponentNames = oldData.getChangedComponentNames(newData) LOG.debug { "analyzeExternalChangesAndUpdateIfNeed: changedComponentNames $changedComponentNames for ${toString()}" } if (changedComponentNames.isNotEmpty()) { componentNames.addAll(changedComponentNames) } } } private fun setStates(oldStorageData: StateMap, newStorageData: StateMap?) { if (oldStorageData !== newStorageData && storageDataRef.getAndSet(newStorageData) !== oldStorageData) { LOG.warn("Old storage data is not equal to current, new storage data was set anyway") } } abstract class XmlElementStorageSaveSession<T : XmlElementStorage>(private val originalStates: StateMap, protected val storage: T) : SaveSessionBase() { private var copiedStates: MutableMap<String, Any>? = null private val newLiveStates = THashMap<String, Element>() override fun createSaveSession(): XmlElementStorageSaveSession<T>? = if (copiedStates == null || storage.checkIsSavingDisabled()) null else this override fun setSerializedState(componentName: String, element: Element?) { val normalized = element?.normalizeRootName() if (copiedStates == null) { copiedStates = setStateAndCloneIfNeed(componentName, normalized, originalStates, newLiveStates) } else { updateState(copiedStates!!, componentName, normalized, newLiveStates) } } override fun save() { val stateMap = StateMap.fromMap(copiedStates!!) val elements = save(stateMap, newLiveStates) val writer: DataWriter? if (elements == null) { writer = null } else { val rootAttributes = LinkedHashMap<String, String>() storage.beforeElementSaved(elements, rootAttributes) val macroManager = if (storage.pathMacroSubstitutor == null) null else (storage.pathMacroSubstitutor as TrackingPathMacroSubstitutorImpl).macroManager writer = XmlDataWriter(storage.rootElementName, elements, rootAttributes, macroManager) } // during beforeElementSaved() elements can be modified and so, even if our save() never returns empty list, at this point, elements can be an empty list var isSavedLocally = false val provider = storage.provider if (elements == null) { if (provider == null || !provider.delete(storage.fileSpec, storage.roamingType)) { isSavedLocally = true saveLocally(writer) } } else if (provider != null && provider.isApplicable(storage.fileSpec, storage.roamingType)) { // we should use standard line-separator (\n) - stream provider can share file content on any OS provider.write(storage.fileSpec, writer!!.toBufferExposingByteArray(), storage.roamingType) } else { isSavedLocally = true saveLocally(writer) } if (!isSavedLocally) { storage.providerDataStateChanged(writer, DataStateChanged.SAVED) } storage.setStates(originalStates, stateMap) } protected abstract fun saveLocally(dataWriter: DataWriter?) } protected open fun beforeElementLoaded(element: Element) { } protected open fun beforeElementSaved(elements: MutableList<Element>, rootAttributes: MutableMap<String, String>) { } fun updatedFromStreamProvider(changedComponentNames: MutableSet<String>, deleted: Boolean) { updatedFrom(changedComponentNames, deleted, true) } fun updatedFrom(changedComponentNames: MutableSet<String>, deleted: Boolean, useStreamProvider: Boolean) { if (roamingType == RoamingType.DISABLED) { // storage roaming was changed to DISABLED, but settings repository has old state return } LOG.runAndLogException { val newElement = if (deleted) null else loadElement(useStreamProvider) val states = storageDataRef.get() if (newElement == null) { // if data was loaded, mark as changed all loaded components if (states != null) { changedComponentNames.addAll(states.keys()) setStates(states, null) } } else if (states != null) { val newStates = loadState(newElement) changedComponentNames.addAll(states.getChangedComponentNames(newStates)) setStates(states, newStates) } } } } internal class XmlDataWriter(private val rootElementName: String?, private val elements: List<Element>, private val rootAttributes: Map<String, String>, private val macroManager: PathMacroManager?) : StringDataWriter() { override fun hasData(filter: DataWriterFilter): Boolean { return elements.any { filter.hasData(it) } } override fun write(writer: Writer, lineSeparator: String, filter: DataWriterFilter?) { var lineSeparatorWithIndent = lineSeparator val hasRootElement = rootElementName != null val replacePathMap = macroManager?.replacePathMap val macroFilter = macroManager?.macroFilter if (hasRootElement) { lineSeparatorWithIndent += " " writer.append('<').append(rootElementName) for (entry in rootAttributes) { writer.append(' ') writer.append(entry.key) writer.append('=') writer.append('"') var value = entry.value if (replacePathMap != null) { value = replacePathMap.substitute(JDOMUtil.escapeText(value, false, true), SystemInfoRt.isFileSystemCaseSensitive) } writer.append(JDOMUtil.escapeText(value, false, true)) writer.append('"') } if (elements.isEmpty()) { // see note in save() why elements here can be an empty list writer.append(" />") return } writer.append('>') } val xmlOutputter = JbXmlOutputter(lineSeparatorWithIndent, filter?.toElementFilter(), replacePathMap, macroFilter) for (element in elements) { if (hasRootElement) { writer.append(lineSeparatorWithIndent) } xmlOutputter.printElement(writer, element, 0) } if (rootElementName != null) { writer.append(lineSeparator) writer.append("</").append(rootElementName).append('>') } } } private fun save(states: StateMap, newLiveStates: Map<String, Element>? = null): MutableList<Element>? { if (states.isEmpty()) { return null } var result: MutableList<Element>? = null for (componentName in states.keys()) { val element: Element try { element = states.getElement(componentName, newLiveStates)?.clone() ?: continue } catch (e: Exception) { LOG.error("Cannot save \"$componentName\" data", e) continue } // name attribute should be first val elementAttributes = element.attributes var nameAttribute = element.getAttribute(FileStorageCoreUtil.NAME) @Suppress("SuspiciousEqualsCombination") if (nameAttribute != null && nameAttribute === elementAttributes.get(0) && componentName == nameAttribute.value) { // all is OK } else { if (nameAttribute == null) { nameAttribute = Attribute(FileStorageCoreUtil.NAME, componentName) elementAttributes.add(0, nameAttribute) } else { nameAttribute.value = componentName if (elementAttributes.get(0) != nameAttribute) { elementAttributes.remove(nameAttribute) elementAttributes.add(0, nameAttribute) } } } if (result == null) { result = SmartList() } result.add(element) } return result } internal fun Element.normalizeRootName(): Element { if (org.jdom.JDOMInterner.isInterned(this)) { if (name == FileStorageCoreUtil.COMPONENT) { return this } else { val clone = clone() clone.name = FileStorageCoreUtil.COMPONENT return clone } } else { if (parent != null) { LOG.warn("State element must not have parent: ${JDOMUtil.writeElement(this)}") detach() } name = FileStorageCoreUtil.COMPONENT return this } } // newStorageData - myStates contains only live (unarchived) states private fun StateMap.getChangedComponentNames(newStates: StateMap): Set<String> { val bothStates = keys().toMutableSet() bothStates.retainAll(newStates.keys()) val diffs = SmartHashSet<String>() diffs.addAll(newStates.keys()) diffs.addAll(keys()) diffs.removeAll(bothStates) for (componentName in bothStates) { compare(componentName, newStates, diffs) } return diffs } enum class DataStateChanged { LOADED, SAVED } interface DataWriterFilter { enum class ElementLevel { ZERO, FIRST } companion object { fun requireAttribute(name: String, onLevel: ElementLevel): DataWriterFilter { return object: DataWriterFilter { override fun toElementFilter(): JDOMUtil.ElementOutputFilter { return JDOMUtil.ElementOutputFilter { childElement, level -> level != onLevel.ordinal || childElement.getAttribute(name) != null } } override fun hasData(element: Element): Boolean { val elementFilter = toElementFilter() if (onLevel == ElementLevel.ZERO && elementFilter.accept(element, 0)) { return true } return element.children.any { elementFilter.accept(it, 1) } } } } } fun toElementFilter(): JDOMUtil.ElementOutputFilter fun hasData(element: Element): Boolean } interface DataWriter { // LineSeparator cannot be used because custom (with indent) line separator can be used fun write(output: OutputStream, lineSeparator: String = LineSeparator.LF.separatorString, filter: DataWriterFilter? = null) fun hasData(filter: DataWriterFilter): Boolean } internal fun DataWriter?.writeTo(file: Path, lineSeparator: String = LineSeparator.LF.separatorString) { if (this == null) { file.delete() } else { file.safeOutputStream(null).use { write(it, lineSeparator) } } } internal abstract class StringDataWriter : DataWriter { final override fun write(output: OutputStream, lineSeparator: String, filter: DataWriterFilter?) { output.bufferedWriter().use { write(it, lineSeparator, filter) } } internal abstract fun write(writer: Writer, lineSeparator: String, filter: DataWriterFilter?) } internal fun DataWriter.toBufferExposingByteArray(lineSeparator: LineSeparator = LineSeparator.LF): BufferExposingByteArrayOutputStream { val out = BufferExposingByteArrayOutputStream(1024) out.use { write(out, lineSeparator.separatorString) } return out } // use ONLY for non-ordinal usages (default project, deprecated directoryBased storage) internal fun createDataWriterForElement(element: Element): DataWriter { return object: DataWriter { override fun hasData(filter: DataWriterFilter) = filter.hasData(element) override fun write(output: OutputStream, lineSeparator: String, filter: DataWriterFilter?) { output.bufferedWriter().use { JbXmlOutputter(lineSeparator, filter?.toElementFilter(), null, null).output(element, it) } } } }
apache-2.0
e9ccab0d8f1ce6d9fc384c9eebcd1b1f
35.002364
177
0.695955
5.074309
false
false
false
false
mdanielwork/intellij-community
platform/platform-impl/src/com/intellij/internal/ShowUpdateInfoDialogAction.kt
4
4430
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal import com.intellij.ide.util.BrowseFilesListener import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.fileChooser.FileTextField import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.* import com.intellij.openapi.updateSettings.impl.UpdateChecker import com.intellij.ui.ScrollPaneFactory import com.intellij.util.loadElement import com.intellij.util.text.nullize import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.JComponent import javax.swing.JPanel import javax.swing.JTextArea /** * @author gregsh */ class ShowUpdateInfoDialogAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val dialog = MyDialog(e.project) if (dialog.showAndGet()) { try { UpdateChecker.testPlatformUpdate(dialog.updateXmlText(), dialog.patchFilePath(), dialog.forceUpdate()) } catch (ex: Exception) { Messages.showErrorDialog(e.project, "${ex.javaClass.name}: ${ex.message}", "Something Went Wrong") } } } private class MyDialog(private val project: Project?) : DialogWrapper(project, true) { private lateinit var textArea: JTextArea private lateinit var fileField: FileTextField private var forceUpdate = false init { title = "Updates.xml <channel> Text" init() } override fun createCenterPanel(): JComponent? { textArea = JTextArea(40, 100) UIUtil.addUndoRedoActions(textArea) textArea.wrapStyleWord = true textArea.lineWrap = true fileField = FileChooserFactory.getInstance().createFileTextField(BrowseFilesListener.SINGLE_FILE_DESCRIPTOR, disposable) val fileCombo = TextFieldWithBrowseButton(fileField.field) val fileDescriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor() fileCombo.addBrowseFolderListener("Patch File", "Patch file", project, fileDescriptor) val panel = JPanel(BorderLayout(0, JBUI.scale(10))) panel.add(ScrollPaneFactory.createScrollPane(textArea), BorderLayout.CENTER) panel.add(LabeledComponent.create(fileCombo, "Patch file:"), BorderLayout.SOUTH) return panel } override fun createActions() = arrayOf( object : AbstractAction("&Check Updates") { override fun actionPerformed(e: ActionEvent?) { forceUpdate = false doOKAction() } }, object : AbstractAction("&Show Dialog") { override fun actionPerformed(e: ActionEvent?) { forceUpdate = true doOKAction() } }, cancelAction) override fun doValidate(): ValidationInfo? { val text = textArea.text?.trim() ?: "" if (text.isEmpty()) { return ValidationInfo("Please paste something here", textArea) } try { loadElement(completeUpdateInfoXml(text)) } catch (e: Exception) { return ValidationInfo(e.message ?: "Error: ${e.javaClass.name}", textArea) } return super.doValidate() } override fun getPreferredFocusedComponent() = textArea override fun getDimensionServiceKey() = "TEST_UPDATE_INFO_DIALOG" internal fun updateXmlText() = completeUpdateInfoXml(textArea.text?.trim() ?: "") internal fun forceUpdate() = forceUpdate internal fun patchFilePath() = fileField.field.text.nullize(nullizeSpaces = true) private fun completeUpdateInfoXml(text: String) = when (loadElement(text).name) { "products" -> text "channel" -> { val productName = ApplicationNamesInfo.getInstance().fullProductName val productCode = ApplicationInfo.getInstance().build.productCode """<products><product name="${productName}"><code>${productCode}</code>${text}</product></products>""" } else -> throw IllegalArgumentException("Unknown root element") } } }
apache-2.0
fac205ecaf311653ce9b8b7a1041f067
36.871795
140
0.717833
4.809989
false
false
false
false
intellij-solidity/intellij-solidity
src/main/kotlin/me/serce/solidity/lang/stubs/impl.kt
1
14024
package me.serce.solidity.lang.stubs import com.intellij.psi.PsiFile import com.intellij.psi.StubBuilder import com.intellij.psi.stubs.* import com.intellij.psi.tree.IStubFileElementType import me.serce.solidity.lang.SolidityLanguage import me.serce.solidity.lang.core.SolidityFile import me.serce.solidity.lang.psi.* import me.serce.solidity.lang.psi.impl.* class SolidityFileStub(file: SolidityFile?) : PsiFileStubImpl<SolidityFile>(file) { override fun getType() = Type object Type : IStubFileElementType<SolidityFileStub>(SolidityLanguage) { // bump version every time stub tree changes override fun getStubVersion() = 15 override fun getBuilder(): StubBuilder = object : DefaultStubBuilder() { override fun createStubForFile(file: PsiFile) = SolidityFileStub(file as SolidityFile) } override fun serialize(stub: SolidityFileStub, dataStream: StubOutputStream) {} override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolidityFileStub(null) override fun getExternalId(): String = "Solidity.file" } } fun factory(name: String): SolStubElementType<*, *> = when (name) { "ENUM_DEFINITION" -> SolEnumDefStub.Type "CONTRACT_DEFINITION" -> SolContractOrLibDefStub.Type "FUNCTION_DEFINITION" -> SolFunctionDefStub.Type "MODIFIER_DEFINITION" -> SolModifierDefStub.Type "STRUCT_DEFINITION" -> SolStructDefStub.Type "EVENT_DEFINITION" -> SolEventDefStub.Type "ERROR_DEFINITION" -> SolErrorDefStub.Type "USER_DEFINED_VALUE_TYPE_DEFINITION" -> SolUserDefinedValueTypeDefStub.Type "STATE_VARIABLE_DECLARATION" -> SolStateVarDeclStub.Type "CONSTANT_VARIABLE_DECLARATION" -> SolConstantVariableDeclStub.Type "IMPORT_PATH" -> SolImportPathDefStub.Type "ELEMENTARY_TYPE_NAME" -> SolTypeRefStub.Type("ELEMENTARY_TYPE_NAME", ::SolElementaryTypeNameImpl) "MAPPING_TYPE_NAME" -> SolTypeRefStub.Type("MAPPING_TYPE_NAME", ::SolMappingTypeNameImpl) "FUNCTION_TYPE_NAME" -> SolTypeRefStub.Type("FUNCTION_TYPE_NAME", ::SolFunctionTypeNameImpl) "ARRAY_TYPE_NAME" -> SolTypeRefStub.Type("ARRAY_TYPE_NAME", ::SolArrayTypeNameImpl) "BYTES_ARRAY_TYPE_NAME" -> SolTypeRefStub.Type("BYTES_ARRAY_TYPE_NAME", ::SolBytesArrayTypeNameImpl) "USER_DEFINED_LOCATION_TYPE_NAME" -> SolTypeRefStub.Type("USER_DEFINED_LOCATION_TYPE_NAME", ::SolUserDefinedLocationTypeNameImpl) "USER_DEFINED_TYPE_NAME" -> SolTypeRefStub.Type("USER_DEFINED_TYPE_NAME", ::SolUserDefinedTypeNameImpl) else -> error("Unknown element $name") } class SolEnumDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolEnumDefinition>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolEnumDefStub, SolEnumDefinition>("ENUM_DEFINITION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolEnumDefStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolEnumDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolEnumDefStub) = SolEnumDefinitionImpl(stub, this) override fun createStub(psi: SolEnumDefinition, parentStub: StubElement<*>?) = SolEnumDefStub(parentStub, this, psi.name) override fun indexStub(stub: SolEnumDefStub, sink: IndexSink) = sink.indexEnumDef(stub) } } class SolUserDefinedValueTypeDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolUserDefinedValueTypeDefinition>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolUserDefinedValueTypeDefStub, SolUserDefinedValueTypeDefinition>("USER_DEFINED_VALUE_TYPE_DEFINITION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolUserDefinedValueTypeDefStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolUserDefinedValueTypeDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolUserDefinedValueTypeDefStub) = SolUserDefinedValueTypeDefinitionImpl(stub, this) override fun createStub(psi: SolUserDefinedValueTypeDefinition, parentStub: StubElement<*>?) = SolUserDefinedValueTypeDefStub(parentStub, this, psi.name) override fun indexStub(stub: SolUserDefinedValueTypeDefStub, sink: IndexSink) = sink.indexUserDefinedValueTypeDef(stub) } } class SolFunctionDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolFunctionDefinition>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolFunctionDefStub, SolFunctionDefinition>("FUNCTION_DEFINITION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolFunctionDefStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolFunctionDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolFunctionDefStub) = SolFunctionDefinitionImpl(stub, this) override fun createStub(psi: SolFunctionDefinition, parentStub: StubElement<*>?) = SolFunctionDefStub(parentStub, this, psi.name) override fun indexStub(stub: SolFunctionDefStub, sink: IndexSink) = sink.indexFunctionDef(stub) } } class SolModifierDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolModifierDefinition>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolModifierDefStub, SolModifierDefinition>("MODIFIER_DEFINITION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolModifierDefStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolModifierDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolModifierDefStub) = SolModifierDefinitionImpl(stub, this) override fun createStub(psi: SolModifierDefinition, parentStub: StubElement<*>?) = SolModifierDefStub(parentStub, this, psi.name) override fun indexStub(stub: SolModifierDefStub, sink: IndexSink) = sink.indexModifierDef(stub) } } class SolStructDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolStructDefinition>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolStructDefStub, SolStructDefinition>("STRUCT_DEFINITION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolStructDefStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolStructDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolStructDefStub) = SolStructDefinitionImpl(stub, this) override fun createStub(psi: SolStructDefinition, parentStub: StubElement<*>?) = SolStructDefStub(parentStub, this, psi.name) override fun indexStub(stub: SolStructDefStub, sink: IndexSink) = sink.indexStructDef(stub) } } class SolStateVarDeclStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolStateVariableDeclaration>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolStateVarDeclStub, SolStateVariableDeclaration>("STATE_VARIABLE_DECLARATION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolStateVarDeclStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolStateVarDeclStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolStateVarDeclStub) = SolStateVariableDeclarationImpl(stub, this) override fun createStub(psi: SolStateVariableDeclaration, parentStub: StubElement<*>?) = SolStateVarDeclStub(parentStub, this, psi.name) override fun indexStub(stub: SolStateVarDeclStub, sink: IndexSink) = sink.indexStateVarDecl(stub) } } class SolConstantVariableDeclStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolConstantVariableDeclaration>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolConstantVariableDeclStub, SolConstantVariableDeclaration>("CONSTANT_VARIABLE_DECLARATION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolConstantVariableDeclStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolConstantVariableDeclStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolConstantVariableDeclStub) = SolConstantVariableDeclarationImpl(stub, this) override fun createStub(psi: SolConstantVariableDeclaration, parentStub: StubElement<*>?) = SolConstantVariableDeclStub(parentStub, this, psi.name) override fun indexStub(stub: SolConstantVariableDeclStub, sink: IndexSink) = sink.indexConstantVariableDecl(stub) } } class SolContractOrLibDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolContractDefinition>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolContractOrLibDefStub, SolContractDefinition>("CONTRACT_DEFINITION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolContractOrLibDefStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolContractOrLibDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolContractOrLibDefStub) = SolContractDefinitionImpl(stub, this) override fun createStub(psi: SolContractDefinition, parentStub: StubElement<*>?) = SolContractOrLibDefStub(parentStub, this, psi.name) override fun indexStub(stub: SolContractOrLibDefStub, sink: IndexSink) = sink.indexContractDef(stub) } } class SolTypeRefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *> ) : StubBase<SolTypeName>(parent, elementType) { class Type<T : SolTypeName>( debugName: String, private val psiFactory: (SolTypeRefStub, IStubElementType<*, *>) -> T ) : SolStubElementType<SolTypeRefStub, T>(debugName) { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolTypeRefStub(parentStub, this) override fun serialize(stub: SolTypeRefStub, dataStream: StubOutputStream) = with(dataStream) { } override fun createPsi(stub: SolTypeRefStub) = psiFactory(stub, this) override fun createStub(psi: T, parentStub: StubElement<*>?) = SolTypeRefStub(parentStub, this) override fun indexStub(stub: SolTypeRefStub, sink: IndexSink) {} } } class SolEventDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolEventDefinition>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolEventDefStub, SolEventDefinition>("EVENT_DEFINITION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolEventDefStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolEventDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolEventDefStub) = SolEventDefinitionImpl(stub, this) override fun createStub(psi: SolEventDefinition, parentStub: StubElement<*>?) = SolEventDefStub(parentStub, this, psi.name) override fun indexStub(stub: SolEventDefStub, sink: IndexSink) = sink.indexEventDef(stub) } } class SolErrorDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String? ) : StubBase<SolErrorDefinition>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolErrorDefStub, SolErrorDefinition>("ERROR_DEFINITION") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolErrorDefStub(parentStub, this, dataStream.readNameAsString()) override fun serialize(stub: SolErrorDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) } override fun createPsi(stub: SolErrorDefStub) = SolErrorDefinitionImpl(stub, this) override fun createStub(psi: SolErrorDefinition, parentStub: StubElement<*>?) = SolErrorDefStub(parentStub, this, psi.name) override fun indexStub(stub: SolErrorDefStub, sink: IndexSink) = sink.indexErrorDef(stub) } } class SolImportPathDefStub( parent: StubElement<*>?, elementType: IStubElementType<*, *>, override val name: String?, val path: String? ) : StubBase<SolImportPathImpl>(parent, elementType), SolNamedStub { object Type : SolStubElementType<SolImportPathDefStub, SolImportPathImpl>("IMPORT_PATH") { override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) = SolImportPathDefStub(parentStub, this, dataStream.readNameAsString(), dataStream.readUTFFast()) override fun serialize(stub: SolImportPathDefStub, dataStream: StubOutputStream) = with(dataStream) { writeName(stub.name) writeUTFFast(stub.path ?: "") } override fun createPsi(stub: SolImportPathDefStub) = SolImportPathImpl(stub, this) override fun createStub(psi: SolImportPathImpl, parentStub: StubElement<*>?) = SolImportPathDefStub(parentStub, this, psi.name, psi.text) override fun indexStub(stub: SolImportPathDefStub, sink: IndexSink) = sink.indexImportPathDef(stub) } } private fun StubInputStream.readNameAsString(): String? = readName()?.string
mit
0a60b3349dfd0fbb6f15a6804c787a38
40.862687
141
0.761338
5.070137
false
false
false
false
dahlstrom-g/intellij-community
platform/build-scripts/testFramework/src/org/jetbrains/intellij/build/testFramework/binaryReproducibility/BuildArtifactsReproducibilityTest.kt
2
3413
// 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.intellij.build.testFramework.binaryReproducibility import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.JvmArchitecture import org.jetbrains.intellij.build.OsFamily import org.jetbrains.intellij.build.impl.getOsDistributionBuilder import java.nio.file.Path import java.util.* import kotlin.io.path.exists import kotlin.io.path.isDirectory import kotlin.io.path.isRegularFile class BuildArtifactsReproducibilityTest { private val buildDateInSeconds = System.getenv("SOURCE_DATE_EPOCH")?.toLongOrNull() private val randomSeedNumber = Random().nextLong() private lateinit var diffDirectory: Path val isEnabled = System.getProperty("intellij.build.test.artifacts.reproducibility") == "true" fun configure(options: BuildOptions) { assert(isEnabled) requireNotNull(buildDateInSeconds) { "SOURCE_DATE_EPOCH environment variable is required" } options.buildDateInSeconds = buildDateInSeconds options.randomSeedNumber = randomSeedNumber // FIXME IJI-823 workaround options.buildStepsToSkip.add(BuildOptions.PREBUILD_SHARED_INDEXES) options.buildStepsToSkip.remove(BuildOptions.OS_SPECIFIC_DISTRIBUTIONS_STEP) } fun compare(context1: BuildContext, context2: BuildContext) { assert(isEnabled) assert(!this::diffDirectory.isInitialized) diffDirectory = System.getProperty("intellij.build.test.artifacts.reproducibility.diffDir")?.let { Path.of(it) } ?: context1.paths.artifactDir.resolve(".diff") val errors = OsFamily.ALL.asSequence().flatMap { os -> val artifacts1 = getOsDistributionBuilder(os, context = context1)!!.getArtifactNames(context1) val artifacts2 = getOsDistributionBuilder(os, context = context2)!!.getArtifactNames(context2) assert(artifacts1 == artifacts2) artifacts1.map { "artifacts/$it" } + "dist.${os.distSuffix}" + JvmArchitecture.ALL.map { "dist.${os.distSuffix}.$it" } }.plus("dist.all").plus("dist").mapNotNull { val path1 = context1.paths.buildOutputDir.resolve(it) val path2 = context2.paths.buildOutputDir.resolve(it) if (!path1.exists() && !path2.exists()) { context1.messages.warning("Neither $path1 nor $path2 exists") return@mapNotNull null } val diff = diffDirectory.resolve(it) val test = FileTreeContentTest(diff, context1.paths.tempDir) val error = when { path1.isDirectory() && path2.isDirectory() -> test.assertTheSameContent(path1, path2) path1.isRegularFile() && path2.isRegularFile() -> test.assertTheSame(Path.of(it), context1.paths.buildOutputDir, context2.paths.buildOutputDir) else -> error("Unable to compare $path1 and $path2") } if (error != null) { context1.messages.artifactBuilt("$diff") } else { context1.messages.info("$path1 and $path2 are byte-to-byte identical.") } error }.toList() if (errors.isNotEmpty()) { throw Exception("Build is not reproducible").apply { errors.forEach(::addSuppressed) } } } }
apache-2.0
5a54542b846fad801267b6752291065e
45.767123
124
0.690595
4.370038
false
true
false
false
paslavsky/spek
spek-core/src/main/kotlin/org/jetbrains/spek/junit/JUnitClassRunner.kt
1
4660
package org.jetbrains.spek.junit import org.jetbrains.spek.api.* import org.junit.runner.Description import org.junit.runner.notification.Failure import org.junit.runner.notification.RunNotifier import org.junit.runners.ParentRunner import java.io.Serializable import kotlin.collections.arrayListOf import kotlin.collections.getOrPut import kotlin.collections.hashMapOf data class JUnitUniqueId(val id: Int) : Serializable { companion object { var id = 0 fun next() = JUnitUniqueId(id++) } } fun junitAction(description: Description, notifier: RunNotifier, action: () -> Unit) { if (description.isTest) notifier.fireTestStarted(description) try { action() } catch(e: SkippedException) { notifier.fireTestIgnored(description) } catch(e: PendingException) { notifier.fireTestIgnored(description) } catch(e: Throwable) { notifier.fireTestFailure(Failure(description, e)) } finally { if (description.isTest) notifier.fireTestFinished(description) } } class JUnitOnRunner<T>(val specificationClass: Class<T>, val given: TestGivenAction, val on: TestOnAction) : ParentRunner<TestItAction>(specificationClass) { val _children by lazy(LazyThreadSafetyMode.NONE) { val result = arrayListOf<TestItAction>() try { on.iterateIt { result.add(it) } } catch (e: SkippedException) { } catch (e: PendingException) { } result } val _description by lazy(LazyThreadSafetyMode.NONE) { val desc = Description.createSuiteDescription(on.description(), JUnitUniqueId.next())!! for (item in children) { desc.addChild(describeChild(item)) } desc } val childrenDescriptions = hashMapOf<String, Description>() override fun getChildren(): MutableList<TestItAction> = _children override fun getDescription(): Description? = _description protected override fun describeChild(child: TestItAction?): Description? { return childrenDescriptions.getOrPut(child!!.description(), { Description.createSuiteDescription("${child.description()} (${on.description()})", JUnitUniqueId.next())!! }) } protected override fun runChild(child: TestItAction?, notifier: RunNotifier?) { junitAction(describeChild(child)!!, notifier!!) { child!!.run() } } } class JUnitGivenRunner<T>(val specificationClass: Class<T>, val given: TestGivenAction) : ParentRunner<JUnitOnRunner<T>>(specificationClass) { val _children by lazy(LazyThreadSafetyMode.NONE) { val result = arrayListOf<JUnitOnRunner<T>>() try { given.iterateOn { result.add(JUnitOnRunner(specificationClass, given, it)) } } catch (e: SkippedException) { } catch (e: PendingException) { } result } val _description by lazy(LazyThreadSafetyMode.NONE) { val desc = Description.createSuiteDescription(given.description(), JUnitUniqueId.next())!! for (item in children) { desc.addChild(describeChild(item)) } desc } override fun getChildren(): MutableList<JUnitOnRunner<T>> = _children override fun getDescription(): Description? = _description protected override fun describeChild(child: JUnitOnRunner<T>?): Description? { return child?.description } protected override fun runChild(child: JUnitOnRunner<T>?, notifier: RunNotifier?) { junitAction(describeChild(child)!!, notifier!!) { child!!.run(notifier) } } } class JUnitClassRunner<T>(val specificationClass: Class<T>) : ParentRunner<JUnitGivenRunner<T>>(specificationClass) { private val suiteDescription = Description.createSuiteDescription(specificationClass) override fun getChildren(): MutableList<JUnitGivenRunner<T>> = _children val _children by lazy(LazyThreadSafetyMode.NONE) { if (Spek::class.java.isAssignableFrom(specificationClass) && !specificationClass.isLocalClass) { val spek = specificationClass.newInstance() as Spek val result = arrayListOf<JUnitGivenRunner<T>>() spek.iterateGiven { result.add(JUnitGivenRunner(specificationClass, it)) } result } else arrayListOf() } protected override fun describeChild(child: JUnitGivenRunner<T>?): Description? { return child?.description } protected override fun runChild(child: JUnitGivenRunner<T>?, notifier: RunNotifier?) { junitAction(describeChild(child)!!, notifier!!) { child!!.run(notifier) } } }
bsd-3-clause
ae0542cb13f10ba9298eb96cd3ce9987
34.572519
157
0.675966
4.750255
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CopyWithoutNamedArgumentsInspection.kt
1
2379
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.AddNamesToCallArgumentsIntention import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.callExpressionVisitor import org.jetbrains.kotlin.psi.psiUtil.referenceExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class CopyWithoutNamedArgumentsInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return callExpressionVisitor(fun(expression) { val reference = expression.referenceExpression() as? KtNameReferenceExpression ?: return if (reference.getReferencedNameAsName() != DataClassDescriptorResolver.COPY_METHOD_NAME) return if (expression.valueArguments.all { it.isNamed() }) return val context = expression.analyze(BodyResolveMode.PARTIAL) val call = expression.getResolvedCall(context) ?: return val receiver = call.dispatchReceiver?.type?.constructor?.declarationDescriptor as? ClassDescriptor ?: return if (!receiver.isData) return if (call.candidateDescriptor != context[BindingContext.DATA_CLASS_COPY_FUNCTION, receiver]) return holder.registerProblem( expression.calleeExpression ?: return, KotlinBundle.message("copy.method.of.data.class.is.called.without.named.arguments"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(AddNamesToCallArgumentsIntention()) ) }) } }
apache-2.0
97ea520de2440d4a2982ab59023d72b6
50.73913
120
0.774695
5.322148
false
false
false
false
HomeMods/Relay
pi/src/com/homemods/relay/pi/bluetooth/PiBluetoothServer.kt
1
1914
package com.homemods.relay.pi.bluetooth import com.homemods.relay.bluetooth.BluetoothConnection import com.homemods.relay.bluetooth.BluetoothServer import javax.bluetooth.DiscoveryAgent import javax.bluetooth.LocalDevice import javax.bluetooth.UUID import javax.microedition.io.Connector import javax.microedition.io.StreamConnectionNotifier /** * @author sergeys */ class PiBluetoothServer : BluetoothServer { private var running: Boolean = true private var discoveryThread: Thread? = null override fun beginDiscovery(onDiscovery: (BluetoothConnection) -> Unit) { if (discoveryThread != null) throw Exception("Server already in discovery mode") running = false discoveryThread = Thread( { val localDevice = LocalDevice.getLocalDevice()!! localDevice.discoverable = DiscoveryAgent.GIAC val uuid = UUID("9fb18ac2a4fd865a79163c954fa189bf", false) println(uuid) val url = "btspp://localhost:$uuid;name=RemoteBluetooth" val streamConnectionNotifier = Connector.open(url) as StreamConnectionNotifier while (running) { val connection = streamConnectionNotifier.acceptAndOpen()!! onDiscovery(PiBluetoothConnection(connection)) } streamConnectionNotifier.close() }, "Bluetooth Discovery Thread").apply { isDaemon = true start() } } override fun endDiscovery() { if (discoveryThread == null) throw Exception("Server not in discovery mode") running = false discoveryThread?.apply { @Suppress("DEPRECATION") stop() } } }
mit
c5af5952d44eb2402e34ef2d43b47f9d
34.444444
98
0.594044
5.547826
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/base/db/migrations/Migration13.kt
1
1441
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.base.db.migrations import androidx.sqlite.db.SupportSQLiteDatabase import androidx.room.migration.Migration object Migration13 : Migration(12, 13) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "UPDATE PASSE SET exact=1 " + "WHERE _id IN (SELECT DISTINCT p._id " + "FROM PASSE p, SHOOT s " + "WHERE p._id=s.passe " + "AND s.x!=0)" ) database.execSQL("ALTER TABLE TRAINING ADD COLUMN exact INTEGER DEFAULT 0") database.execSQL( "UPDATE TRAINING SET exact=1 " + "WHERE _id IN (SELECT DISTINCT t._id " + "FROM TRAINING t, ROUND r, PASSE p " + "WHERE t._id=r.training " + "AND r._id=p.round " + "AND p.exact=1)" ) } }
gpl-2.0
72ab55692b59fe7713d8b89aa86a971d
35.025
83
0.601666
4.28869
false
false
false
false
github/codeql
java/ql/test/kotlin/library-tests/jvmoverloads-annotation/test.kt
1
1420
fun getString() = "Hello world" object Test { @JvmOverloads @JvmStatic fun testStaticFunction(a: Int, b: String = getString(), c: Double, d: Float = 1.0f, e: Boolean): Int = a @JvmOverloads fun testMemberFunction(a: Int, b: String = getString(), c: Double, d: Float = 1.0f, e: Boolean): Int = a @JvmOverloads fun Test2.testMemberExtensionFunction(a: Int, b: String = getString(), c: Double, d: Float = 1.0f, e: Boolean): Int = a } public class Test2 @JvmOverloads constructor(a: Int, b: String = getString(), c: Double, d: Float = 1.0f, e: Boolean) { companion object { @JvmOverloads fun testCompanionFunction(a: Int, b: String = getString(), c: Double, d: Float = 1.0f, e: Boolean): Int = a @JvmOverloads @JvmStatic fun testStaticCompanionFunction(a: Int, b: String = getString(), c: Double, d: Float = 1.0f, e: Boolean): Int = a } } public class GenericTest<T> @JvmOverloads constructor(a: Int = 1, b: T, c: String = "Hello world", d: T) { @JvmOverloads fun testMemberFunction(a: Int = 1, b: T, c: String = "Hello world", d: T): Int = a fun useSpecialised(spec1: GenericTest<Float>, spec2: GenericTest<Double>) { spec1.testMemberFunction(1, 1.0f, "Hello world", 2.0f) spec2.testMemberFunction(1, 1.0, "Hello world", 2.0) } } @JvmOverloads fun Test.testExtensionFunction(a: Int, b: String = getString(), c: Double, d: Float = 1.0f, e: Boolean): Int = a
mit
5e64c5584e7f542d660a2fab0c02bc4a
30.555556
121
0.661972
3.183857
false
true
false
false
raniejade/zerofx
zerofx-view-helpers/src/main/kotlin/io/polymorphicpanda/zerofx/template/helpers/Dsl.kt
1
1495
package io.polymorphicpanda.zerofx.template.helpers import javafx.beans.property.BooleanProperty import javafx.scene.Node import javafx.scene.control.Label internal fun <K: Node, T: Builder<K>> builder(parent: Builder<*>?, builder: T, block: T.() -> Unit): K { return builder.run { block.invoke(this) if (parent != null && parent is PaneBuilder) { parent.add(this.node) } node } } fun builder(block: PaneBuilder<*>.() -> Unit) = BuilderDelegate(block) fun Builder<*>.stackPane(block: StackPaneBuilder.() -> Unit) = builder(this, StackPaneBuilder(), block) fun Builder<*>.borderPane(block: BorderPaneBuilder.() -> Unit) = builder(this, BorderPaneBuilder(), block) fun Builder<*>.vbox(block: VBoxBuilder.() -> Unit) = builder(this, VBoxBuilder(), block) fun Builder<*>.hbox(block: HBoxBuilder.() -> Unit) = builder(this, HBoxBuilder(), block) fun Builder<*>.label(text: String = "", block: LabelBuilder.() -> Unit = {}) = builder(this, LabelBuilder(Label(text)), block) fun Builder<*>.button(block: ButtonBuilder.() -> Unit) = builder(this, ButtonBuilder(), block) fun <T> Builder<*>.listView(block: ListViewBuilder<T>.() -> Unit) = builder(this, ListViewBuilder(), block) fun Builder<*>.textField(block: TextFieldBuilder.() -> Unit) = builder(this, TextFieldBuilder(), block) fun Builder<*>.textArea(block: TextAreaBuilder.() -> Unit) = builder(this, TextAreaBuilder(), block) fun switch(condition: BooleanProperty) { }
mit
29ebb5c447eb764bad3d1bad786eaea1
35.463415
108
0.680268
3.873057
false
false
false
false