repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinFunctionParameterInfoHandler.kt
1
26964
// 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.parameterInfo import com.intellij.codeInsight.CodeInsightBundle import com.intellij.lang.parameterInfo.* import com.intellij.openapi.application.runReadAction import com.intellij.openapi.project.Project import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.ui.Gray import com.intellij.ui.JBColor import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.completion.canBeUsedWithoutNameInCall import org.jetbrains.kotlin.idea.core.OptionalParametersHelper import org.jetbrains.kotlin.idea.core.resolveCandidates import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.ShadowedDeclarationsFilter import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.NULLABILITY_ANNOTATIONS import org.jetbrains.kotlin.load.java.sam.SamAdapterDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.containsError import org.jetbrains.kotlin.utils.checkWithAttachment import java.awt.Color import kotlin.reflect.KClass class KotlinFunctionParameterInfoHandler : KotlinParameterInfoWithCallHandlerBase<KtValueArgumentList, KtValueArgument>(KtValueArgumentList::class, KtValueArgument::class) { override fun getActualParameters(arguments: KtValueArgumentList) = arguments.arguments.toTypedArray() override fun getActualParametersRBraceType(): KtSingleValueToken = KtTokens.RPAR override fun getArgumentListAllowedParentClasses() = setOf(KtCallElement::class.java) } class KotlinLambdaParameterInfoHandler : KotlinParameterInfoWithCallHandlerBase<KtLambdaArgument, KtLambdaArgument>(KtLambdaArgument::class, KtLambdaArgument::class) { override fun getActualParameters(lambdaArgument: KtLambdaArgument) = arrayOf(lambdaArgument) override fun getActualParametersRBraceType(): KtSingleValueToken = KtTokens.RBRACE override fun getArgumentListAllowedParentClasses() = setOf(KtLambdaArgument::class.java) override fun getParameterIndex(context: UpdateParameterInfoContext, argumentList: KtLambdaArgument): Int { val size = (argumentList.parent as? KtCallElement)?.valueArguments?.size ?: 1 return size - 1 } } class KotlinArrayAccessParameterInfoHandler : KotlinParameterInfoWithCallHandlerBase<KtContainerNode, KtExpression>(KtContainerNode::class, KtExpression::class) { override fun getArgumentListAllowedParentClasses() = setOf(KtArrayAccessExpression::class.java) override fun getActualParameters(containerNode: KtContainerNode): Array<out KtExpression> = containerNode.allChildren.filterIsInstance<KtExpression>().toList().toTypedArray() override fun getActualParametersRBraceType(): KtSingleValueToken = KtTokens.RBRACKET } abstract class KotlinParameterInfoWithCallHandlerBase<TArgumentList : KtElement, TArgument : KtElement>( private val argumentListClass: KClass<TArgumentList>, private val argumentClass: KClass<TArgument> ) : ParameterInfoHandlerWithTabActionSupport<TArgumentList, KotlinParameterInfoWithCallHandlerBase.CallInfo, TArgument> { companion object { @JvmField val GREEN_BACKGROUND: Color = JBColor(Color(231, 254, 234), Gray._100) val STOP_SEARCH_CLASSES: Set<Class<out KtElement>> = setOf( KtNamedFunction::class.java, KtVariableDeclaration::class.java, KtValueArgumentList::class.java, KtLambdaArgument::class.java, KtContainerNode::class.java, KtTypeArgumentList::class.java ) private val RENDERER = DescriptorRenderer.SHORT_NAMES_IN_TYPES.withOptions { enhancedTypes = true renderUnabbreviatedType = false } } private fun findCall(argumentList: TArgumentList, bindingContext: BindingContext): Call? { return (argumentList.parent as? KtElement)?.getCall(bindingContext) } override fun getActualParameterDelimiterType(): KtSingleValueToken = KtTokens.COMMA override fun getArgListStopSearchClasses(): Set<Class<out KtElement>> = STOP_SEARCH_CLASSES override fun getArgumentListClass() = argumentListClass.java override fun showParameterInfo(element: TArgumentList, context: CreateParameterInfoContext) { context.showHint(element, element.textRange.startOffset, this) } override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): TArgumentList? { val element = context.file.findElementAt(context.offset) ?: return null val argumentList = PsiTreeUtil.getParentOfType(element, argumentListClass.java) ?: return null val argument = element.parents.takeWhile { it != argumentList }.lastOrNull() if (argument != null && !argumentClass.java.isInstance(argument)) { val arguments = getActualParameters(argumentList) val index = arguments.indexOf(element) context.setCurrentParameter(index) context.highlightedParameter = element } return argumentList } override fun findElementForParameterInfo(context: CreateParameterInfoContext): TArgumentList? { //todo: calls to this constructors, when we will have auxiliary constructors val file = context.file as? KtFile ?: return null val token = file.findElementAt(context.offset) ?: return null val argumentList = PsiTreeUtil.getParentOfType(token, argumentListClass.java, true, *STOP_SEARCH_CLASSES.toTypedArray()) ?: return null val bindingContext = argumentList.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val call = findCall(argumentList, bindingContext) ?: return null val resolutionFacade = file.getResolutionFacade() val candidates = call.resolveCandidates(bindingContext, resolutionFacade) .map { it.resultingDescriptor } .distinctBy { it.original } val shadowedDeclarationsFilter = ShadowedDeclarationsFilter( bindingContext, resolutionFacade, call.callElement, call.explicitReceiver as? ReceiverValue ) context.itemsToShow = shadowedDeclarationsFilter.filter(candidates).map { CallInfo(it) }.toTypedArray() return argumentList } override fun updateParameterInfo(argumentList: TArgumentList, context: UpdateParameterInfoContext) { if (context.parameterOwner !== argumentList) { context.removeHint() } val parameterIndex = getParameterIndex(context, argumentList) context.setCurrentParameter(parameterIndex) runReadAction { val resolutionFacade = argumentList.getResolutionFacade() val bindingContext = argumentList.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL) val call = findCall(argumentList, bindingContext) ?: return@runReadAction context.objectsToView.forEach { resolveCallInfo(it as CallInfo, call, bindingContext, resolutionFacade, parameterIndex) } } } protected open fun getParameterIndex(context: UpdateParameterInfoContext, argumentList: TArgumentList): Int { val offset = context.offset return argumentList.allChildren .takeWhile { it.startOffset < offset } .count { it.node.elementType == KtTokens.COMMA } } override fun updateUI(itemToShow: CallInfo, context: ParameterInfoUIContext) { if (!updateUIOrFail(itemToShow, context)) { context.isUIComponentEnabled = false return } } private fun updateUIOrFail(itemToShow: CallInfo, context: ParameterInfoUIContext): Boolean { if (context.parameterOwner == null || !context.parameterOwner.isValid) return false if (!argumentListClass.java.isInstance(context.parameterOwner)) return false val call = itemToShow.call ?: return false val supportsMixedNamedArgumentsInTheirOwnPosition = call.callElement.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition) @Suppress("UNCHECKED_CAST") val argumentList = context.parameterOwner as TArgumentList val currentArgumentIndex = context.currentParameterIndex if (currentArgumentIndex < 0) return false // by some strange reason we are invoked with currentParameterIndex == -1 during initialization val project = argumentList.project val (substitutedDescriptor, argumentToParameter, highlightParameterIndex, isGrey) = matchCallWithSignature( itemToShow, currentArgumentIndex ) ?: return false var boldStartOffset = -1 var boldEndOffset = -1 var disabledBeforeHighlight = false val text = buildString { val usedParameterIndices = HashSet<Int>() var namedMode = false var argumentIndex = 0 if (call.callType == Call.CallType.ARRAY_SET_METHOD) { // for set-operator the last parameter is used for the value assigned usedParameterIndices.add(substitutedDescriptor.valueParameters.lastIndex) } val includeParameterNames = !substitutedDescriptor.hasSynthesizedParameterNames() fun appendParameter( parameter: ValueParameterDescriptor, named: Boolean = false, markUsedUnusedParameterBorder: Boolean = false ) { argumentIndex++ if (length > 0) { append(", ") if (markUsedUnusedParameterBorder) { // mark the space after the comma as bold; bold text needs to be at least one character long boldStartOffset = length - 1 boldEndOffset = length disabledBeforeHighlight = true } } val highlightParameter = parameter.index == highlightParameterIndex if (highlightParameter) { boldStartOffset = length } append(renderParameter(parameter, includeParameterNames, named || namedMode, project)) if (highlightParameter) { boldEndOffset = length } } for (argument in call.valueArguments) { if (argument is LambdaArgument) continue val parameter = argumentToParameter(argument) ?: continue if (!usedParameterIndices.add(parameter.index)) continue if (argument.isNamed() && !(supportsMixedNamedArgumentsInTheirOwnPosition && argument.canBeUsedWithoutNameInCall(itemToShow)) ) { namedMode = true } appendParameter(parameter, argument.isNamed()) } for (parameter in substitutedDescriptor.valueParameters) { if (parameter.index !in usedParameterIndices) { if (argumentIndex != parameter.index) { namedMode = true } appendParameter(parameter, markUsedUnusedParameterBorder = highlightParameterIndex == null && boldStartOffset == -1) } } if (length == 0) { append(CodeInsightBundle.message("parameter.info.no.parameters")) } } val color = if (itemToShow.isResolvedToDescriptor) GREEN_BACKGROUND else context.defaultParameterColor context.setupUIComponentPresentation( text, boldStartOffset, boldEndOffset, isGrey, itemToShow.isDeprecatedAtCallSite, disabledBeforeHighlight, color ) return true } private fun renderParameter(parameter: ValueParameterDescriptor, includeName: Boolean, named: Boolean, project: Project): String { return buildString { if (named) append("[") parameter .annotations .filterNot { it.fqName in NULLABILITY_ANNOTATIONS } .forEach { it.fqName?.let { fqName -> append("@${fqName.shortName().asString()} ") } } if (parameter.varargElementType != null) { append("vararg ") } if (includeName) { append(parameter.name) append(": ") } append(RENDERER.renderType(parameterTypeToRender(parameter))) if (parameter.hasDefaultValue()) { append(" = ") append(parameter.renderDefaultValue(project)) } if (named) append("]") } } private fun ValueParameterDescriptor.renderDefaultValue(project: Project): String { val expression = OptionalParametersHelper.defaultParameterValueExpression(this, project) if (expression != null) { val text = expression.text if (text.length <= 32) { return text } if (expression is KtConstantExpression || expression is KtStringTemplateExpression) { if (text.startsWith("\"")) { return "\"...\"" } else if (text.startsWith("\'")) { return "\'...\'" } } } return "..." } private fun parameterTypeToRender(descriptor: ValueParameterDescriptor): KotlinType { var type = descriptor.varargElementType ?: descriptor.type if (type.containsError()) { val original = descriptor.original type = original.varargElementType ?: original.type } return type } private fun isResolvedToDescriptor( call: Call, functionDescriptor: FunctionDescriptor, bindingContext: BindingContext ): Boolean { val target = call.getResolvedCall(bindingContext)?.resultingDescriptor as? FunctionDescriptor return target != null && descriptorsEqual(target, functionDescriptor) } private data class SignatureInfo( val substitutedDescriptor: FunctionDescriptor, val argumentToParameter: (ValueArgument) -> ValueParameterDescriptor?, val highlightParameterIndex: Int?, val isGrey: Boolean ) data class CallInfo( val overload: FunctionDescriptor? = null, var call: Call? = null, var resolvedCall: ResolvedCall<FunctionDescriptor>? = null, var parameterIndex: Int? = null, var dummyArgument: ValueArgument? = null, var dummyResolvedCall: ResolvedCall<FunctionDescriptor>? = null, var isResolvedToDescriptor: Boolean = false, var isGreyArgumentIndex: Int = -1, var isDeprecatedAtCallSite: Boolean = false ) { override fun toString(): String = "CallInfo(overload=$overload, call=$call, resolvedCall=${resolvedCall?.resultingDescriptor}($resolvedCall), parameterIndex=$parameterIndex, dummyArgument=$dummyArgument, dummyResolvedCall=$dummyResolvedCall, isResolvedToDescriptor=$isResolvedToDescriptor, isGreyArgumentIndex=$isGreyArgumentIndex, isDeprecatedAtCallSite=$isDeprecatedAtCallSite)" } fun Call.arguments(): List<ValueArgument> { val isArraySetMethod = callType == Call.CallType.ARRAY_SET_METHOD return valueArguments.let<List<ValueArgument>, List<ValueArgument>> { args -> // For array set method call, we're only interested in the arguments in brackets which are all except the last one if (isArraySetMethod) args.dropLast(1) else args } } private fun resolveCallInfo( info: CallInfo, call: Call, bindingContext: BindingContext, resolutionFacade: ResolutionFacade, parameterIndex: Int ) { val overload = info.overload ?: return val isArraySetMethod = call.callType == Call.CallType.ARRAY_SET_METHOD val arguments = call.arguments() val resolvedCall = resolvedCall(call, bindingContext, resolutionFacade, overload) ?: return // add dummy current argument if we don't have one val dummyArgument = object : ValueArgument { override fun getArgumentExpression(): KtExpression? = null override fun getArgumentName(): ValueArgumentName? = null override fun isNamed(): Boolean = false override fun asElement(): KtElement = call.callElement // is a hack but what to do? override fun getSpreadElement(): LeafPsiElement? = null override fun isExternal() = false } val dummyResolvedCall = dummyResolvedCall(call, arguments, dummyArgument, isArraySetMethod, bindingContext, resolutionFacade, overload) val resultingDescriptor = resolvedCall.resultingDescriptor val resolvedToDescriptor = isResolvedToDescriptor(call, resultingDescriptor, bindingContext) // grey out if not all arguments are matched val isGreyArgumentIndex = arguments.indexOfFirst { argument -> resolvedCall.getArgumentMapping(argument).isError() && !argument.hasError(bindingContext) /* ignore arguments that have error type */ } @OptIn(FrontendInternals::class) val isDeprecated = resolutionFacade.frontendService<DeprecationResolver>().getDeprecations(resultingDescriptor).isNotEmpty() with(info) { this.call = call this.resolvedCall = resolvedCall this.parameterIndex = parameterIndex this.dummyArgument = dummyArgument this.dummyResolvedCall = dummyResolvedCall this.isResolvedToDescriptor = resolvedToDescriptor this.isGreyArgumentIndex = isGreyArgumentIndex this.isDeprecatedAtCallSite = isDeprecated } } private fun dummyResolvedCall( call: Call, arguments: List<ValueArgument>, dummyArgument: ValueArgument, isArraySetMethod: Boolean, bindingContext: BindingContext, resolutionFacade: ResolutionFacade, overload: FunctionDescriptor ): ResolvedCall<FunctionDescriptor>? { val callToUse = object : DelegatingCall(call) { val argumentsWithCurrent = arguments + dummyArgument + // For array set method call, also add the argument in the right-hand side (if (isArraySetMethod) listOf(call.valueArguments.last()) else listOf()) override fun getValueArguments() = argumentsWithCurrent override fun getFunctionLiteralArguments() = emptyList<LambdaArgument>() override fun getValueArgumentList(): KtValueArgumentList? = null } return resolvedCall(callToUse, bindingContext, resolutionFacade, overload) } private fun resolvedCall( call: Call, bindingContext: BindingContext, resolutionFacade: ResolutionFacade, overload: FunctionDescriptor ): ResolvedCall<FunctionDescriptor>? { val candidates = call.resolveCandidates(bindingContext, resolutionFacade) // First try to find strictly matching descriptor, then one with the same declaration. // The second way is needed for the case when the descriptor was invalidated and new one has been built. // See testLocalFunctionBug(). return candidates.firstOrNull { it.resultingDescriptor.original == overload.original } ?: candidates.firstOrNull { descriptorsEqual(it.resultingDescriptor, overload) } } private fun matchCallWithSignature( info: CallInfo, currentArgumentIndex: Int ): SignatureInfo? { val call = info.call ?: return null val resolvedCall = info.resolvedCall ?: return null if (currentArgumentIndex == 0 && call.valueArguments.isEmpty() && resolvedCall.resultingDescriptor.valueParameters.isEmpty()) { return SignatureInfo(resolvedCall.resultingDescriptor, { null }, null, isGrey = false) } val arguments = call.arguments() checkWithAttachment( arguments.size >= currentArgumentIndex, lazyMessage = { "currentArgumentIndex: $currentArgumentIndex has to be not more than number of arguments ${arguments.size} " + " (parameterIndex: ${info.parameterIndex}) :call.valueArguments: ${call.valueArguments} call.callType: ${call.callType}" }, attachments = { info.call?.let { c -> it.withPsiAttachment("file.kt", c.callElement.containingFile) } it.withAttachment("info.txt", info) } ) val callToUse: ResolvedCall<FunctionDescriptor> val currentArgument = if (arguments.size > currentArgumentIndex) { callToUse = resolvedCall arguments[currentArgumentIndex] } else { callToUse = info.dummyResolvedCall ?: return null info.dummyArgument ?: return null } val resultingDescriptor = callToUse.resultingDescriptor fun argumentToParameter(argument: ValueArgument): ValueParameterDescriptor? { return (callToUse.getArgumentMapping(argument) as? ArgumentMatch)?.valueParameter } val currentParameter = argumentToParameter(currentArgument) val highlightParameterIndex = currentParameter?.index val argumentsBeforeCurrent = arguments.subList(0, currentArgumentIndex) if (argumentsBeforeCurrent.any { argumentToParameter(it) == null }) { // some of arguments before the current one are not mapped to any of the parameters return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey = true) } if (currentParameter == null) { if (currentArgumentIndex < arguments.lastIndex) { // the current argument is not the last one and it is not mapped to any of the parameters return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey = true) } val usedParameters = argumentsBeforeCurrent.mapNotNull { argumentToParameter(it) }.toSet() val availableParameters = if (call.callType == Call.CallType.ARRAY_SET_METHOD) { resultingDescriptor.valueParameters.dropLast(1) } else { resultingDescriptor.valueParameters } val noUnusedParametersLeft = (availableParameters - usedParameters).isEmpty() if (currentArgument == info.dummyArgument) { val supportsTrailingCommas = call.callElement.languageVersionSettings.supportsFeature(LanguageFeature.TrailingCommas) if (!supportsTrailingCommas && noUnusedParametersLeft) { // current argument is empty but there are no unused parameters left and trailing commas are not supported return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey = true) } } else if (noUnusedParametersLeft) { // there are no unused parameters left to which this argument could be matched return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey = true) } } // grey out if not all arguments before the current are matched val isGrey = info.isGreyArgumentIndex in 0 until currentArgumentIndex return SignatureInfo(resultingDescriptor, ::argumentToParameter, highlightParameterIndex, isGrey) } private fun ValueArgument.hasError(bindingContext: BindingContext) = getArgumentExpression()?.let { bindingContext.getType(it) }?.isError ?: true private fun ValueArgument.canBeUsedWithoutNameInCall(callInfo: CallInfo) = this is KtValueArgument && this.canBeUsedWithoutNameInCall(callInfo.resolvedCall as ResolvedCall<out CallableDescriptor>) // we should not compare descriptors directly because partial resolve is involved private fun descriptorsEqual(descriptor1: FunctionDescriptor, descriptor2: FunctionDescriptor): Boolean { if (descriptor1.original == descriptor2.original) return true val isSamDescriptor1 = descriptor1 is SamAdapterDescriptor<*> val isSamDescriptor2 = descriptor2 is SamAdapterDescriptor<*> // Previously it worked because of different order // If descriptor1 is SamAdapter and descriptor2 isn't, this function shouldn't return `true` because of equal declaration if (isSamDescriptor1 xor isSamDescriptor2) return false val declaration1 = DescriptorToSourceUtils.descriptorToDeclaration(descriptor1) ?: return false val declaration2 = DescriptorToSourceUtils.descriptorToDeclaration(descriptor2) return declaration1 == declaration2 } }
apache-2.0
b739f0badfd9bbbced4e640243c81a39
44.090301
358
0.68673
5.868118
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/settings/language/SingleLanguageInlayHintsSettingsPanel.kt
1
11940
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints.settings.language import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.hint.EditorFragmentComponent import com.intellij.codeInsight.hints.ChangeListener import com.intellij.codeInsight.hints.InlayHintsSettings import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable import com.intellij.codeInsight.hints.settings.InlayProviderSettingsModel import com.intellij.ide.CopyProvider import com.intellij.ide.DataManager import com.intellij.lang.Language import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.fileTypes.PlainTextFileType import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.options.ex.Settings import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.psi.PsiDocumentManager import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.EditorTextField import com.intellij.ui.JBColor import com.intellij.ui.JBSplitter import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBList import com.intellij.ui.components.JBScrollPane import com.intellij.ui.layout.* import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.awt.GridLayout import java.awt.datatransfer.StringSelection import java.util.concurrent.Callable import javax.swing.* import javax.swing.border.LineBorder private const val TOP_PANEL_PROPORTION = 0.35f class SingleLanguageInlayHintsSettingsPanel( private val myModels: Array<InlayProviderSettingsModel>, private val myLanguage: Language, private val myProject: Project ) : JPanel(), CopyProvider { private val config = InlayHintsSettings.instance() private val myProviderList = createList() private var myCurrentProvider = selectLastViewedProvider() private val myEditorTextField = createEditor(myLanguage, myProject) { updateHints() } private val myCurrentProviderCustomSettingsPane = JBScrollPane().also { it.border = null } private val myCurrentProviderCasesPane = JBScrollPane().also { it.border = null it.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER it.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER } private val myBottomPanel = createBottomPanel() private var myCasesPanel: CasesPanel? = null private val myRightPanel: JPanel = JPanel() private val myWarningContainer = JPanel().also { it.layout = BoxLayout(it, BoxLayout.Y_AXIS) } init { layout = GridLayout(1, 1) val splitter = JBSplitter(true) splitter.firstComponent = createTopPanel() splitter.secondComponent = myBottomPanel for (model in myModels) { model.onChangeListener = object : ChangeListener { override fun settingsChanged() { updateHints() } } } myProviderList.addListSelectionListener { val newProviderModel = myProviderList.selectedValue update(newProviderModel) config.saveLastViewedProviderId(newProviderModel.id) } myProviderList.selectedIndex = findIndexToSelect() add(splitter) updateWithNewProvider() } internal fun getModels(): Array<InlayProviderSettingsModel> { return myModels } internal fun setCurrentModel(model: InlayProviderSettingsModel) { myProviderList.setSelectedValue(model, true) } private fun selectLastViewedProvider(): InlayProviderSettingsModel { return myModels[findIndexToSelect()] } private fun findIndexToSelect(): Int { val id = config.getLastViewedProviderId() ?: return 0 return when (val index = myModels.indexOfFirst { it.id == id }) { -1 -> 0 else -> index } } private fun createList(): JBList<InlayProviderSettingsModel> { return JBList(*myModels).also { it.cellRenderer = object : ColoredListCellRenderer<InlayProviderSettingsModel>(), ListCellRenderer<InlayProviderSettingsModel> { override fun customizeCellRenderer(list: JList<out InlayProviderSettingsModel>, value: InlayProviderSettingsModel, index: Int, selected: Boolean, hasFocus: Boolean) { append(value.name) } } } } private fun createTopPanel(): JPanel { val panel = JPanel() panel.layout = GridLayout(1, 1) val horizontalSplitter = JBSplitter(false, TOP_PANEL_PROPORTION) horizontalSplitter.firstComponent = createLeftPanel() horizontalSplitter.secondComponent = fillRightPanel() panel.add(horizontalSplitter) return panel } private fun createLeftPanel() = JBScrollPane(myProviderList) private fun fillRightPanel(): JPanel { return withInset(panel { row { myWarningContainer(growY) } row { withInset(myCurrentProviderCasesPane)() } row { withInset(myCurrentProviderCustomSettingsPane)() } }) } private fun createBottomPanel(): JPanel { val panel = JPanel() panel.layout = BorderLayout() panel.add(createPreviewPanel(), BorderLayout.CENTER) return panel } private fun createPreviewPanel(): JPanel { val previewPanel = JPanel() previewPanel.layout = BorderLayout() previewPanel.add(myEditorTextField, BorderLayout.CENTER) return previewPanel } private fun withInset(component: JComponent): JPanel { val panel = JPanel(GridLayout()) panel.add(component) panel.border = JBUI.Borders.empty(2) return panel } private fun update(newProvider: InlayProviderSettingsModel) { if (myCurrentProvider == newProvider) return myCurrentProvider = newProvider updateWithNewProvider() } private fun updateWithNewProvider() { myCurrentProviderCasesPane.setViewportView(createCasesPanel()) myCurrentProviderCustomSettingsPane.setViewportView(myCurrentProvider.component) myRightPanel.validate() updateWarningPanel() val previewText = myCurrentProvider.previewText if (previewText == null) { myBottomPanel.isVisible = false } else { myBottomPanel.isVisible = true myEditorTextField.text = previewText updateHints() } } private fun updateWarningPanel() { myWarningContainer.removeAll() if (!config.hintsEnabled(myLanguage)) { myWarningContainer.add(JLabel(CodeInsightBundle.message("settings.inlay.hints.warning.hints.for.language.disabled", myLanguage.displayName))) myWarningContainer.add(ActionLink(CodeInsightBundle.message("settings.inlay.hints.warning.configure.settings", myLanguage.displayName)) { val settings = Settings.KEY.getData(DataManager.getInstance().getDataContext(this)) if (settings != null) { val mainConfigurable = settings.find(InlayHintsConfigurable::class.java) if (mainConfigurable != null) { settings.select(mainConfigurable) } } }) } myWarningContainer.revalidate() myWarningContainer.repaint() } private fun createCasesPanel(): JPanel { val model = myCurrentProvider val casesPanel = CasesPanel( cases = model.cases, mainCheckBoxName = model.mainCheckBoxLabel, loadMainCheckBoxValue = { model.isEnabled }, onUserChangedMainCheckBox = { model.isEnabled = it model.onChangeListener?.settingsChanged() }, listener = model.onChangeListener!!, // must be installed at this point disabledExternally = { !(config.hintsEnabled(myLanguage) && config.hintsEnabledGlobally()) } ) myCasesPanel = casesPanel return casesPanel } private fun updateHints() { if (myBottomPanel.isVisible) { myEditorTextField.editor?.let { editor -> val model = myCurrentProvider val document = myEditorTextField.document val fileType = myLanguage.associatedFileType ?: PlainTextFileType.INSTANCE ReadAction.nonBlocking(Callable { val psiFile = model.createFile(myProject, fileType, document) myCurrentProvider.collectData(editor, psiFile) }) .finishOnUiThread(ModalityState.defaultModalityState()) { continuation -> ApplicationManager.getApplication().runWriteAction { continuation.run() } } .inSmartMode(myProject) .submit(AppExecutorUtil.getAppExecutorService()) } } } fun isModified(): Boolean { return myModels.any { it.isModified() } } fun apply() { for (model in myModels) { model.apply() } } fun reset() { for (model in myModels) { model.reset() } myCasesPanel?.updateFromSettings() updateWarningPanel() updateHints() } override fun performCopy(dataContext: DataContext) { val selectedIndex = myProviderList.selectedIndex if (selectedIndex < 0) return val selection = myProviderList.model.getElementAt(selectedIndex) CopyPasteManager.getInstance().setContents(StringSelection(selection.name)) } override fun isCopyEnabled(dataContext: DataContext): Boolean = !myProviderList.isSelectionEmpty override fun isCopyVisible(dataContext: DataContext): Boolean = false } internal val SETTINGS_EDITOR_MARKER: Key<Boolean> = Key.create("inlay.settings.editor") fun isInlaySettingsEditor(editor: Editor) : Boolean { return editor.getUserData(SETTINGS_EDITOR_MARKER) == true } fun createEditor(language: Language, project: Project, updateHints: (editor: Editor) -> Any): EditorTextField { val fileType: FileType = language.associatedFileType ?: FileTypes.PLAIN_TEXT val editorField = object : EditorTextField(null, project, fileType, true, false) { override fun createEditor(): EditorEx { val editor = super.createEditor() editor.putUserData(SETTINGS_EDITOR_MARKER, true) updateHints(editor) return editor } } editorField.font = EditorFontType.PLAIN.globalFont editorField.border = LineBorder(JBColor.border()) editorField.addSettingsProvider { editor -> editor.setVerticalScrollbarVisible(true) editor.setHorizontalScrollbarVisible(true) with(editor.settings) { additionalLinesCount = 0 isAutoCodeFoldingEnabled = false } // Sadly, but we can't use daemon here, because we need specific kind of settings instance here. editor.document.addDocumentListener(object : DocumentListener { override fun documentChanged(event: DocumentEvent) { updateHints(editor) } }) editor.backgroundColor = EditorFragmentComponent.getBackgroundColor(editor, false) editor.setBorder(JBUI.Borders.empty()) // If editor is created as not viewer, daemon is enabled automatically. But we want to collect hints manually with another settings. val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) if (psiFile != null) { DaemonCodeAnalyzer.getInstance(project).setHighlightingEnabled(psiFile, false) } } ReadAction.run<Throwable> { editorField.setCaretPosition(0) } return editorField }
apache-2.0
511a609ef95ef89a78ac192d7983d76d
34.641791
158
0.728894
4.734338
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/RemoveNullableFix.kt
3
3031
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType class RemoveNullableFix(element: KtNullableType, private val typeOfError: NullableKind) : KotlinPsiOnlyQuickFixAction<KtNullableType>(element) { enum class NullableKind(@Nls val message: String) { REDUNDANT(KotlinBundle.message("remove.redundant")), SUPERTYPE(KotlinBundle.message("text.remove.question")), USELESS(KotlinBundle.message("remove.useless")), PROPERTY(KotlinBundle.message("make.not.nullable")) } override fun getFamilyName() = KotlinBundle.message("text.remove.question") override fun getText() = typeOfError.message override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val type = element.innerType ?: error("No inner type ${element.text}, should have been rejected in createFactory()") element.replace(type) } companion object { val removeForRedundant = createFactory(NullableKind.REDUNDANT) val removeForSuperType = createFactory(NullableKind.SUPERTYPE) val removeForUseless = createFactory(NullableKind.USELESS) val removeForLateInitProperty = createFactory(NullableKind.PROPERTY) private fun createFactory(typeOfError: NullableKind): QuickFixesPsiBasedFactory<KtElement> { return quickFixesPsiBasedFactory { e -> when (typeOfError) { NullableKind.REDUNDANT, NullableKind.SUPERTYPE, NullableKind.USELESS -> { val nullType: KtNullableType? = when (e) { is KtTypeReference -> e.typeElement as? KtNullableType else -> e.getNonStrictParentOfType() } if (nullType?.innerType == null) return@quickFixesPsiBasedFactory emptyList() listOf(RemoveNullableFix(nullType, typeOfError)) } NullableKind.PROPERTY -> { val property = e as? KtProperty ?: return@quickFixesPsiBasedFactory emptyList() val typeReference = property.typeReference ?: return@quickFixesPsiBasedFactory emptyList() val typeElement = typeReference.typeElement as? KtNullableType ?: return@quickFixesPsiBasedFactory emptyList() if (typeElement.innerType == null) return@quickFixesPsiBasedFactory emptyList() listOf(RemoveNullableFix(typeElement, NullableKind.PROPERTY)) } } } } } }
apache-2.0
232feab2f7581e61d01080f5590833a5
50.372881
158
0.663807
5.422182
false
false
false
false
androidx/androidx
wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/ScalingLazyListLayoutInfoTest.kt
3
46833
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.requiredSize import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import kotlin.math.roundToInt import org.junit.Ignore @MediumTest @RunWith(AndroidJUnit4::class) public class ScalingLazyListLayoutInfoTest { @get:Rule val rule = createComposeRule() private var itemSizePx: Int = 50 private var itemSizeDp: Dp = Dp.Infinity private var defaultItemSpacingDp: Dp = 4.dp private var defaultItemSpacingPx = Int.MAX_VALUE @Before fun before() { with(rule.density) { itemSizeDp = itemSizePx.toDp() defaultItemSpacingPx = defaultItemSpacingDp.roundToPx() } } @Ignore("Awaiting fix for b/236217874") @Test fun visibleItemsAreCorrect() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), autoCentering = AutoCenteringParams() ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.centerItemIndex).isEqualTo(1) assertThat(state.centerItemScrollOffset).isEqualTo(0) state.layoutInfo.assertVisibleItems(count = 4) } } @Test fun centerItemIndexIsCorrectAfterScrolling() { lateinit var state: ScalingLazyListState var itemSpacingPx: Int = -1 val itemSpacingDp = 20.dp var scope: CoroutineScope? = null rule.setContent { scope = rememberCoroutineScope() itemSpacingPx = with(LocalDensity.current) { itemSpacingDp.roundToPx() } ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + itemSpacingDp * 2.5f ), verticalArrangement = Arrangement.spacedBy(itemSpacingDp), autoCentering = AutoCenteringParams() ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.centerItemIndex).isEqualTo(1) assertThat(state.centerItemScrollOffset).isEqualTo(0) state.layoutInfo.assertVisibleItems(count = 3, spacing = itemSpacingPx) } // Scroll so that the center item is just above the center line and check that it is still // the correct center item val scrollDistance = (itemSizePx / 2) + 1 scope!!.launch { state.animateScrollBy(scrollDistance.toFloat()) } rule.runOnIdle { assertThat(state.centerItemIndex).isEqualTo(1) assertThat(state.centerItemScrollOffset).isEqualTo(scrollDistance) } } @Test fun orientationIsCorrect() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), autoCentering = AutoCenteringParams(), contentPadding = PaddingValues(all = 0.dp) ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.layoutInfo.orientation).isEqualTo(Orientation.Vertical) } } @Test fun reverseLayoutIsCorrectWhenNotReversed() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), autoCentering = AutoCenteringParams(), contentPadding = PaddingValues(all = 0.dp) ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.layoutInfo.reverseLayout).isEqualTo(false) } } @Test fun reverseLayoutIsCorrectWhenReversed() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), autoCentering = AutoCenteringParams(), contentPadding = PaddingValues(all = 0.dp), reverseLayout = true ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.layoutInfo.reverseLayout).isEqualTo(true) } } @Test fun visibleItemsAreCorrectSetExplicitInitialItemIndex() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(initialCenterItemIndex = 0) .also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), autoCentering = AutoCenteringParams(itemIndex = 0) ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.centerItemIndex).isEqualTo(0) assertThat(state.centerItemScrollOffset).isEqualTo(0) state.layoutInfo.assertVisibleItems(count = 3) } } @Test fun visibleItemsAreCorrectNoAutoCentering() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), autoCentering = null ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 4) } } @Test fun visibleItemsAreCorrectForReverseLayout() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), reverseLayout = true, autoCentering = null ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.centerItemIndex).isEqualTo(1) state.layoutInfo.assertVisibleItems(count = 4) } } @Test fun visibleItemsAreCorrectForReverseLayoutWithAutoCentering() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(initialCenterItemIndex = 0) .also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), reverseLayout = true, autoCentering = AutoCenteringParams(itemIndex = 0) ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.centerItemIndex).isEqualTo(0) assertThat(state.centerItemScrollOffset).isEqualTo(0) state.layoutInfo.assertVisibleItems(count = 3) } } @Test fun visibleItemsAreCorrectAfterScrolling() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), autoCentering = null ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { runBlocking { state.scrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()) } state.layoutInfo.assertVisibleItems(count = 4, startIndex = 1) } } @Test fun itemsCorrectScrollPastStartEndAutoCenterItemZeroOddHeightViewportOddHeightItems() { visibleItemsAreCorrectAfterScrollingPastEndOfItems(0, 41, false) } @Test fun itemsCorrectScrollPastStartEndAutoCenterItemZeroOddHeightViewportEvenHeightItems() { visibleItemsAreCorrectAfterScrollingPastEndOfItems(0, 40, false) } @Test fun itemsCorrectScrollPastStartEndAutoCenterItemZeroEvenHeightViewportOddHeightItems() { visibleItemsAreCorrectAfterScrollingPastEndOfItems(0, 41, true) } @Test fun itemsCorrectScrollPastStartEndAutoCenterItemZeroEvenHeightViewportEvenHeightItems() { visibleItemsAreCorrectAfterScrollingPastEndOfItems(0, 40, true) } @Test fun itemsCorrectScrollPastStartEndAutoCenterItemOneOddHeightViewportOddHeightItems() { visibleItemsAreCorrectAfterScrollingPastEndOfItems(1, 41, false) } @Test fun itemsCorrectScrollPastStartEndAutoCenterItemOneOddHeightViewportEvenHeightItems() { visibleItemsAreCorrectAfterScrollingPastEndOfItems(1, 40, false) } @Test fun itemsCorrectScrollPastStartEndAutoCenterItemOneEvenHeightViewportOddHeightItems() { visibleItemsAreCorrectAfterScrollingPastEndOfItems(1, 41, true) } @Test fun itemsCorrectScrollPastStartEndAutoCenterItemOneEvenHeightViewportEvenHeightItems() { visibleItemsAreCorrectAfterScrollingPastEndOfItems(1, 40, true) } private fun visibleItemsAreCorrectAfterScrollingPastEndOfItems( autoCenterItem: Int, localItemSizePx: Int, viewPortSizeEven: Boolean ) { lateinit var state: ScalingLazyListState lateinit var scope: CoroutineScope rule.setContent { with(LocalDensity.current) { val viewportSizePx = (((localItemSizePx * 4 + defaultItemSpacingPx * 3) / 2) * 2) + if (viewPortSizeEven) 0 else 1 scope = rememberCoroutineScope() ScalingLazyColumn( state = rememberScalingLazyListState( initialCenterItemIndex = autoCenterItem ).also { state = it }, modifier = Modifier.requiredSize( viewportSizePx.toDp() ), autoCentering = AutoCenteringParams(itemIndex = autoCenterItem) ) { items(5) { Box(Modifier.requiredSize(localItemSizePx.toDp())) } } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } scope.launch { state.animateScrollBy(localItemSizePx.toFloat() * 10) } rule.waitUntil { !state.isScrollInProgress } assertThat(state.centerItemIndex).isEqualTo(4) assertThat(state.centerItemScrollOffset).isEqualTo(0) scope.launch { state.animateScrollBy(- localItemSizePx.toFloat() * 10) } rule.waitUntil { !state.isScrollInProgress } assertThat(state.centerItemIndex).isEqualTo(autoCenterItem) assertThat(state.centerItemScrollOffset).isEqualTo(0) } @Test fun largeItemLargerThanViewPortDoesNotGetScaled() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp ), autoCentering = null ) { items(5) { Box(Modifier.requiredSize(itemSizeDp * 5)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { runBlocking { state.scrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()) } val firstItem = state.layoutInfo.visibleItemsInfo.first() assertThat(firstItem.offset).isLessThan(0) assertThat(firstItem.offset + firstItem.size).isGreaterThan(itemSizePx) assertThat(state.layoutInfo.visibleItemsInfo.first().scale).isEqualTo(1.0f) } } @Test fun itemInsideScalingLinesDoesNotGetScaled() { lateinit var state: ScalingLazyListState val centerItemIndex = 2 rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(centerItemIndex).also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3 ), ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { // Get the middle item on the screen val centerScreenItem = state.layoutInfo.visibleItemsInfo.find { it.index == centerItemIndex } // and confirm its offset is 0 assertThat(centerScreenItem!!.offset).isEqualTo(0) // And that it is not scaled assertThat(centerScreenItem.scale).isEqualTo(1.0f) } } @Test fun itemOutsideScalingLinesDoesGetScaled() { lateinit var state: ScalingLazyListState val centerItemIndex = 2 rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(centerItemIndex).also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 4 + defaultItemSpacingDp * 3 ), ) { items(6) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { // Get the middle item on the screen val edgeScreenItem = state.layoutInfo.visibleItemsInfo.find { it.index == 0 } // And that it is it scaled assertThat(edgeScreenItem!!.scale).isLessThan(1.0f) } } @Test fun visibleItemsAreCorrectAfterScrollingReverseLayout() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), reverseLayout = true, autoCentering = null ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { runBlocking { state.scrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()) } state.layoutInfo.assertVisibleItems(count = 4, startIndex = 1) } } @Test fun visibleItemsAreCorrectCenterPivotNoOffset() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(2).also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 2f + defaultItemSpacingDp * 1f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f) ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 3, startIndex = 1) assertThat(state.centerItemIndex).isEqualTo(2) assertThat(state.centerItemScrollOffset).isEqualTo(0) } } @Test fun visibleItemsAreCorrectCenterPivotWithOffset() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(2, -5).also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 2f + defaultItemSpacingDp * 1f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f) ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 3, startIndex = 1) assertThat(state.centerItemIndex).isEqualTo(2) assertThat(state.centerItemScrollOffset).isEqualTo(-5) } } @Test fun visibleItemsAreCorrectCenterPivotNoOffsetReverseLayout() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(2).also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 2f + defaultItemSpacingDp * 1f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f), reverseLayout = true ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 3, startIndex = 1) assertThat(state.centerItemIndex).isEqualTo(2) assertThat(state.centerItemScrollOffset).isEqualTo(0) } } @Test fun visibleItemsAreCorrectCenterPivotWithOffsetReverseLayout() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(2, -5).also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 2f + defaultItemSpacingDp * 1f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f), reverseLayout = true ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 3, startIndex = 1) assertThat(state.centerItemIndex).isEqualTo(2) assertThat(state.centerItemScrollOffset).isEqualTo(-5) } } @Test fun visibleItemsAreCorrectNoScalingForReverseLayout() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(8).also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 4f + defaultItemSpacingDp * 3f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f), reverseLayout = true ) { items(15) { Box(Modifier.requiredSize(itemSizeDp).testTag("Item:$it")) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.waitForIdle() // Assert that items are being shown at the end of the parent as this is reverseLayout rule.onNodeWithTag(testTag = "Item:8").assertIsDisplayed() rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 5, startIndex = 6) } } @Test fun visibleItemsAreCorrectAfterScrollNoScaling() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(initialCenterItemIndex = 0) .also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f), autoCentering = AutoCenteringParams(itemIndex = 0) ) { items(5) { Box( Modifier .requiredSize(itemSizeDp) .testTag("Item:$it")) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.waitForIdle() rule.onNodeWithTag(testTag = "Item:0").assertIsDisplayed() val scrollAmount = (itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()).roundToInt() rule.runOnIdle { assertThat(state.centerItemIndex).isEqualTo(0) assertThat(state.centerItemScrollOffset).isEqualTo(0) runBlocking { state.scrollBy(scrollAmount.toFloat()) } state.layoutInfo.assertVisibleItems(count = 4) assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(-scrollAmount) } rule.runOnIdle { runBlocking { state.scrollBy(-scrollAmount.toFloat()) } state.layoutInfo.assertVisibleItems(count = 3) assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(0) } } @Test fun visibleItemsAreCorrectAfterScrollNoScalingForReverseLayout() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(8).also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 4f + defaultItemSpacingDp * 3f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f), reverseLayout = true ) { items(15) { Box(Modifier.requiredSize(itemSizeDp).testTag("Item:$it")) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.waitForIdle() rule.onNodeWithTag(testTag = "Item:8").assertIsDisplayed() val scrollAmount = (itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()).roundToInt() rule.runOnIdle { state.layoutInfo.assertVisibleItems(count = 5, startIndex = 6) assertThat(state.centerItemIndex).isEqualTo(8) assertThat(state.centerItemScrollOffset).isEqualTo(0) runBlocking { state.scrollBy(scrollAmount.toFloat()) } state.layoutInfo.assertVisibleItems(count = 5, startIndex = 7) } rule.runOnIdle { runBlocking { state.scrollBy(-scrollAmount.toFloat()) } state.layoutInfo.assertVisibleItems(count = 5, startIndex = 6) } } @Test fun visibleItemsAreCorrectAfterDispatchRawDeltaScrollNoScaling() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState(initialCenterItemIndex = 0) .also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f), autoCentering = AutoCenteringParams(itemIndex = 0) ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } val scrollAmount = itemSizePx.toFloat() + defaultItemSpacingPx.toFloat() rule.runOnIdle { runBlocking { state.dispatchRawDelta(scrollAmount) } state.layoutInfo.assertVisibleItems(count = 4, startIndex = 0) assertThat(state.layoutInfo.visibleItemsInfo.first().offset) .isEqualTo(-scrollAmount.roundToInt()) } rule.runOnIdle { runBlocking { state.dispatchRawDelta(-scrollAmount) } state.layoutInfo.assertVisibleItems(count = 3, startIndex = 0) assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(0) } } @Test fun visibleItemsAreCorrectAfterDispatchRawDeltaScrollNoScalingForReverseLayout() { lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize( itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f ), scalingParams = ScalingLazyColumnDefaults.scalingParams(1.0f, 1.0f), reverseLayout = true, autoCentering = null ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } val firstItemOffset = state.layoutInfo.visibleItemsInfo.first().offset rule.runOnIdle { runBlocking { state.dispatchRawDelta(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()) } state.layoutInfo.assertVisibleItems(count = 4, startIndex = 1) assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(firstItemOffset) } rule.runOnIdle { runBlocking { state.dispatchRawDelta(-(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat())) } state.layoutInfo.assertVisibleItems(count = 4, startIndex = 0) assertThat(state.layoutInfo.visibleItemsInfo.first().offset).isEqualTo(firstItemOffset) } } @Test fun visibleItemsAreCorrectWithCustomSpacing() { lateinit var state: ScalingLazyListState val spacing: Dp = 10.dp rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize(itemSizeDp * 3.5f + spacing * 2.5f), verticalArrangement = Arrangement.spacedBy(spacing), autoCentering = null ) { items(5) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { val spacingPx = with(rule.density) { spacing.roundToPx() } state.layoutInfo.assertVisibleItems( count = 4, spacing = spacingPx ) } } @Composable fun ObservingFun( state: ScalingLazyListState, currentInfo: StableRef<ScalingLazyListLayoutInfo?> ) { currentInfo.value = state.layoutInfo } @Test fun visibleItemsAreObservableWhenWeScroll() { lateinit var state: ScalingLazyListState val currentInfo = StableRef<ScalingLazyListLayoutInfo?>(null) rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f), autoCentering = null ) { items(6) { Box(Modifier.requiredSize(itemSizeDp)) } } ObservingFun(state, currentInfo) } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { // empty it here and scrolling should invoke observingFun again currentInfo.value = null runBlocking { state.scrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()) } } rule.runOnIdle { assertThat(currentInfo.value).isNotNull() currentInfo.value!!.assertVisibleItems(count = 4, startIndex = 1) } } @Test fun visibleItemsAreObservableWhenWeDispatchRawDeltaScroll() { lateinit var state: ScalingLazyListState val currentInfo = StableRef<ScalingLazyListLayoutInfo?>(null) rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f), autoCentering = null ) { items(6) { Box(Modifier.requiredSize(itemSizeDp)) } } ObservingFun(state, currentInfo) } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { // empty it here and scrolling should invoke observingFun again currentInfo.value = null runBlocking { state.dispatchRawDelta(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()) } } rule.runOnIdle { assertThat(currentInfo.value).isNotNull() currentInfo.value!!.assertVisibleItems(count = 4, startIndex = 1) } } @Composable fun ObservingIsScrollInProgressTrueFun( state: ScalingLazyListState, currentInfo: StableRef<Boolean?> ) { // If isScrollInProgress is ever true record it - otherwise leave the value as null if (state.isScrollInProgress) { currentInfo.value = true } } @Test fun isScrollInProgressIsObservableWhenWeScroll() { lateinit var state: ScalingLazyListState lateinit var scope: CoroutineScope val currentInfo = StableRef<Boolean?>(null) rule.setContent { scope = rememberCoroutineScope() ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f) ) { items(6) { Box(Modifier.requiredSize(itemSizeDp)) } } ObservingIsScrollInProgressTrueFun(state, currentInfo) } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } scope.launch { // empty it here and scrolling should invoke observingFun again currentInfo.value = null state.animateScrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()) } rule.runOnIdle { assertThat(currentInfo.value).isNotNull() assertThat(currentInfo.value).isTrue() } } @Composable fun ObservingCentralItemIndexFun( state: ScalingLazyListState, currentInfo: StableRef<Int?> ) { currentInfo.value = state.centerItemIndex } @Test fun isCentralListItemIndexObservableWhenWeScroll() { lateinit var state: ScalingLazyListState lateinit var scope: CoroutineScope val currentInfo = StableRef<Int?>(null) rule.setContent { scope = rememberCoroutineScope() ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it }, modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f), autoCentering = null ) { items(6) { Box(Modifier.requiredSize(itemSizeDp)) } } ObservingCentralItemIndexFun(state, currentInfo) } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } scope.launch { // empty it here and scrolling should invoke observingFun again currentInfo.value = null state.animateScrollBy(itemSizePx.toFloat() + defaultItemSpacingPx.toFloat()) } rule.runOnIdle { assertThat(currentInfo.value).isNotNull() assertThat(currentInfo.value).isEqualTo(2) } } @Test fun visibleItemsAreObservableWhenResize() { lateinit var state: ScalingLazyListState var size by mutableStateOf(itemSizeDp * 2) var currentInfo: ScalingLazyListLayoutInfo? = null @Composable fun observingFun() { currentInfo = state.layoutInfo } rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it } ) { item { Box(Modifier.requiredSize(size)) } } observingFun() } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(currentInfo).isNotNull() currentInfo!!.assertVisibleItems(count = 1, unscaledSize = itemSizePx * 2) currentInfo = null size = itemSizeDp } rule.runOnIdle { assertThat(currentInfo).isNotNull() currentInfo!!.assertVisibleItems(count = 1, unscaledSize = itemSizePx) } } @Test fun viewportOffsetsAndSizeAreCorrect() { val sizePx = 45 val sizeDp = with(rule.density) { sizePx.toDp() } lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( Modifier.requiredSize(sizeDp), state = rememberScalingLazyListState().also { state = it } ) { items(4) { Box(Modifier.requiredSize(sizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(0) assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(sizePx) assertThat(state.layoutInfo.viewportSize).isEqualTo(IntSize(sizePx, sizePx)) assertThat(state.layoutInfo.beforeContentPadding).isEqualTo(0) assertThat(state.layoutInfo.afterContentPadding).isEqualTo(0) assertThat(state.layoutInfo.beforeAutoCenteringPadding).isEqualTo(0) assertThat(state.layoutInfo.afterAutoCenteringPadding).isEqualTo(0) } } @Test fun viewportOffsetsAndSizeAreCorrectWithContentPadding() { val sizePx = 45 val startPaddingPx = 10 val endPaddingPx = 15 val sizeDp = with(rule.density) { sizePx.toDp() } val topPaddingDp = with(rule.density) { startPaddingPx.toDp() } val bottomPaddingDp = with(rule.density) { endPaddingPx.toDp() } lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( Modifier.requiredSize(sizeDp), contentPadding = PaddingValues(top = topPaddingDp, bottom = bottomPaddingDp), state = rememberScalingLazyListState().also { state = it } ) { items(4) { Box(Modifier.requiredSize(sizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(-startPaddingPx) assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(sizePx - startPaddingPx) assertThat(state.layoutInfo.viewportSize).isEqualTo(IntSize(sizePx, sizePx)) assertThat(state.layoutInfo.beforeContentPadding).isEqualTo(10) assertThat(state.layoutInfo.afterContentPadding).isEqualTo(15) assertThat(state.layoutInfo.beforeAutoCenteringPadding).isEqualTo(0) assertThat(state.layoutInfo.afterAutoCenteringPadding).isEqualTo(0) } } @Test fun viewportOffsetsAreCorrectWithAutoCentering() { val itemSizePx = 45 val itemSizeDp = with(rule.density) { itemSizePx.toDp() } val viewPortSizePx = itemSizePx * 4 val viewPortSizeDp = with(rule.density) { viewPortSizePx.toDp() } lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( Modifier.requiredSize(viewPortSizeDp), state = rememberScalingLazyListState( initialCenterItemIndex = 0 ).also { state = it }, autoCentering = AutoCenteringParams() ) { items(7) { Box(Modifier.requiredSize(itemSizeDp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.layoutInfo.viewportStartOffset).isEqualTo(0) assertThat(state.layoutInfo.viewportEndOffset).isEqualTo(viewPortSizePx) assertThat(state.layoutInfo.beforeContentPadding).isEqualTo(0) assertThat(state.layoutInfo.afterContentPadding).isEqualTo(0) assertThat(state.layoutInfo.beforeAutoCenteringPadding).isGreaterThan(0) assertThat(state.layoutInfo.afterAutoCenteringPadding).isEqualTo(0) runBlocking { state.scrollToItem(3) } assertThat(state.layoutInfo.beforeAutoCenteringPadding).isEqualTo(0) assertThat(state.layoutInfo.afterAutoCenteringPadding).isEqualTo(0) runBlocking { state.scrollToItem(5) } assertThat(state.layoutInfo.beforeAutoCenteringPadding).isEqualTo(0) assertThat(state.layoutInfo.afterAutoCenteringPadding).isGreaterThan(0) } } @Test fun totalCountIsCorrect() { var count by mutableStateOf(10) lateinit var state: ScalingLazyListState rule.setContent { ScalingLazyColumn( state = rememberScalingLazyListState().also { state = it } ) { items(count) { Box(Modifier.requiredSize(10.dp)) } } } // TODO(b/210654937): Remove the waitUntil once we no longer need 2 stage initialization rule.waitUntil { state.initialized.value } rule.runOnIdle { assertThat(state.layoutInfo.totalItemsCount).isEqualTo(10) count = 20 } rule.runOnIdle { assertThat(state.layoutInfo.totalItemsCount).isEqualTo(20) } } private fun ScalingLazyListLayoutInfo.assertVisibleItems( count: Int, startIndex: Int = 0, unscaledSize: Int = itemSizePx, spacing: Int = defaultItemSpacingPx, anchorType: ScalingLazyListAnchorType = ScalingLazyListAnchorType.ItemCenter ) { assertThat(visibleItemsInfo.size).isEqualTo(count) var currentIndex = startIndex var previousEndOffset = -1 visibleItemsInfo.forEach { assertThat(it.index).isEqualTo(currentIndex) assertThat(it.size).isEqualTo((unscaledSize * it.scale).roundToInt()) currentIndex++ val startOffset = it.startOffset(anchorType).roundToInt() if (previousEndOffset != -1) { assertThat(spacing).isEqualTo(startOffset - previousEndOffset) } previousEndOffset = startOffset + it.size } } } @Stable public class StableRef<T>(var value: T)
apache-2.0
00decb97c3f732f2b83f6ad4c390901f
36.557338
99
0.594794
5.281123
false
false
false
false
GunoH/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/util/psiUtils.kt
2
1962
// 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.util import com.intellij.psi.* import org.jetbrains.kotlin.load.java.JvmAnnotationNames import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun ValueArgument.findSingleLiteralStringTemplateText(): String? { return getArgumentExpression() ?.safeAs<KtStringTemplateExpression>() ?.entries ?.singleOrNull() ?.safeAs<KtLiteralStringTemplateEntry>() ?.text } @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("The function is ad-hoc, has arbitrary naming and does not support extension receivers") fun KtCallableDeclaration.numberOfArguments(countReceiver: Boolean = false): Int = valueParameters.size + (1.takeIf { countReceiver && receiverTypeReference != null } ?: 0) fun KtExpression.resultingWhens(): List<KtWhenExpression> = when (this) { is KtWhenExpression -> listOf(this) + entries.map { it.expression?.resultingWhens() ?: listOf() }.flatten() is KtIfExpression -> (then?.resultingWhens() ?: listOf()) + (`else`?.resultingWhens() ?: listOf()) is KtBinaryExpression -> (left?.resultingWhens() ?: listOf()) + (right?.resultingWhens() ?: listOf()) is KtUnaryExpression -> this.baseExpression?.resultingWhens() ?: listOf() is KtBlockExpression -> statements.lastOrNull()?.resultingWhens() ?: listOf() else -> listOf() } fun PsiClass.isSyntheticKotlinClass(): Boolean { if ('$' !in name!!) return false // optimization to not analyze annotations of all classes val metadata = modifierList?.findAnnotation(JvmAnnotationNames.METADATA_FQ_NAME.asString()) return (metadata?.findAttributeValue(JvmAnnotationNames.KIND_FIELD_NAME) as? PsiLiteral)?.value == KotlinClassHeader.Kind.SYNTHETIC_CLASS.id }
apache-2.0
4250934e5a2f664e918e0a600658ea9d
45.738095
120
0.737513
4.797066
false
false
false
false
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/rtmp/RtmpHandshake.kt
1
1286
package com.haishinkit.rtmp import java.nio.ByteBuffer import java.util.Random internal class RtmpHandshake { var c0C1Packet: ByteBuffer = ByteBuffer.allocate(SIGNAL_SIZE + 1) get() { if (field.position() == 0) { val random = Random() field.put(0x03) field.position(1 + 8) for (i in 0..SIGNAL_SIZE - 9) { field.put(random.nextInt().toByte()) } } return field } var c2Packet: ByteBuffer = ByteBuffer.allocate(SIGNAL_SIZE) var s0S1Packet: ByteBuffer = ByteBuffer.allocate(SIGNAL_SIZE + 1) set(value) { field = ByteBuffer.wrap(value.array(), 0, SIGNAL_SIZE + 1) c2Packet.clear() c2Packet.put(value.array(), 1, 4) c2Packet.position(8) c2Packet.put(value.array(), 9, SIGNAL_SIZE - 8) } var s2Packet: ByteBuffer = ByteBuffer.allocate(SIGNAL_SIZE) set(value) { field = ByteBuffer.wrap(value.array(), 0, SIGNAL_SIZE) } fun clear() { c0C1Packet.clear() s0S1Packet.clear() c2Packet.clear() s2Packet.clear() } companion object { const val SIGNAL_SIZE = 1536 } }
bsd-3-clause
4f29108378a3df27e804a46e3935642d
26.956522
70
0.541213
3.827381
false
false
false
false
Shurup228/brainfuck_kotlin
tests/ParserTest.kt
1
1291
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* import java.util.LinkedList internal class ParserTest { val parser = Parser("kek") @Test fun parse() { val code = "< > + - [ ] , ." val tokens = parser.parse(code) val expectedTokens = arrayOf( Move(-1), Move(1), ChangeValue(1), ChangeValue(-1), OpenLoop(), CloseLoop(), Write, Print ).toCollection(LinkedList()) assertEquals(tokens, expectedTokens) } @Test fun optimize() { val code = "++---.>>>" val tokens = parser.optimize(parser.parse(code)) val expectedTokens = arrayOf( ChangeValue(-1), Print, Move(3) ).toCollection(LinkedList()) assertEquals(expectedTokens, tokens) } @Test fun loopParse() { val code = "+[--[-]++]" val tokens = parser.loopParse(parser.optimize(parser.parse(code))) val expectedTokens = arrayOf( ChangeValue(1), OpenLoop(1, 7), ChangeValue(-2), OpenLoop(3, 5), ChangeValue(-1), CloseLoop(5, 3), ChangeValue(2), CloseLoop(7, 1) ).toCollection(LinkedList()) assertEquals(expectedTokens, tokens) } }
mit
9d972641456571f63e18a7dd2305e57b
29.046512
74
0.552285
4.164516
false
true
false
false
LouisCAD/Splitties
modules/mainthread/src/androidTest/kotlin/splitties/mainthread/MainThreadCheckingPerformanceTest.kt
1
4001
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.mainthread import android.os.Looper import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LIBRARY_IMPL import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOCAL_CACHED_THREAD_BY_ID import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOCAL_CACHED_THREAD_ID import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOCAL_CACHED_THREAD_REF import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOOPER import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.LOOPER_THREAD_REF import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.THREAD_EQUALS import splitties.mainthread.MainThreadCheckingPerformanceTest.MainThreadCheckTechnique.THREAD_ID import kotlin.system.measureNanoTime import kotlin.test.Test import kotlin.test.assertTrue class MainThreadCheckingPerformanceTest { private enum class MainThreadCheckTechnique { LOOPER, THREAD_ID, THREAD_EQUALS, LOCAL_CACHED_THREAD_BY_ID, LOCAL_CACHED_THREAD_ID, LOOPER_THREAD_REF, LOCAL_CACHED_THREAD_REF, LIBRARY_IMPL } @Test fun compareMainThreadChecks(): Unit = runBlocking(Dispatchers.Main) { val techniqueList = MainThreadCheckTechnique.values().asList() val results = mutableMapOf<MainThreadCheckTechnique, Long>().also { resultsMap -> val reverseList = techniqueList.reversed() repeat(100) { i -> val runList = (if (i % 2 == 0) techniqueList else reverseList) runList.onEach { technique -> val result = runBenchmark(technique) resultsMap[technique] = resultsMap.getOrElse(technique) { 0 } + result } } }.toList().sortedBy { (_, result) -> result } val techniqueNameLength = MainThreadCheckTechnique.values().maxBy { it.name.length }!!.name.length val tag = "MainThreadPerformanceTest" Log.i(tag, "Benchmark results below") results.forEach { (technique, result) -> val techName = technique.name.replace('_', ' ').toLowerCase().capitalize() .padEnd(techniqueNameLength) Log.d(tag, "$techName duration (in µs): $result") } assertTrue("Library implementation should be the fastest technique! Check logs.") { val (technique, _) = results.minBy { (_, result) -> result }!! technique == LIBRARY_IMPL } }.let { Unit } private fun runBenchmark(technique: MainThreadCheckTechnique): Long { val mainThread = mainLooper.thread val mainThreadId = mainThread.id return when (technique) { LIBRARY_IMPL -> benchmark { isMainThread } LOOPER -> benchmark { mainLooper == Looper.myLooper() } THREAD_ID -> benchmark { mainLooper.thread.id == Thread.currentThread().id } THREAD_EQUALS -> benchmark { mainLooper.thread == Thread.currentThread() } LOCAL_CACHED_THREAD_BY_ID -> benchmark { mainThread.id == Thread.currentThread().id } LOCAL_CACHED_THREAD_ID -> benchmark { mainThreadId == Thread.currentThread().id } LOOPER_THREAD_REF -> benchmark { mainLooper.thread === Thread.currentThread() } LOCAL_CACHED_THREAD_REF -> benchmark { mainThread == Thread.currentThread() // This seems to be the fastest technique. } } } private inline fun benchmark(runs: Int = 10_000, f: () -> Boolean): Long = measureNanoTime { repeat(runs) { check(f()) } } / 1000 }
apache-2.0
b16cef70670f0ceda19eb1471cc7e46f
46.058824
112
0.68375
4.744958
false
true
false
false
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/ui/editor/EditorView.kt
1
12678
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.ui.editor import android.app.Activity import android.content.Intent import android.content.res.ColorStateList import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.Bundle import android.support.v4.content.ContextCompat import android.text.Editable import android.text.TextWatcher import android.view.MotionEvent import android.view.View import android.view.ViewTreeObserver import cn.dreamtobe.kpswitch.util.KPSwitchConflictUtil import cn.dreamtobe.kpswitch.util.KeyboardUtil import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.linkedin.android.spyglass.mentions.MentionsEditable import com.linkedin.android.spyglass.suggestions.SuggestionsResult import com.linkedin.android.spyglass.suggestions.interfaces.Suggestible import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsResultListener import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsVisibilityManager import com.linkedin.android.spyglass.tokenization.QueryToken import com.linkedin.android.spyglass.tokenization.impl.WordTokenizer import com.linkedin.android.spyglass.tokenization.impl.WordTokenizerConfig import com.linkedin.android.spyglass.tokenization.interfaces.QueryTokenReceiver import com.sinyuk.fanfou.R import com.sinyuk.fanfou.base.AbstractFragment import com.sinyuk.fanfou.di.Injectable import com.sinyuk.fanfou.domain.DO.Player import com.sinyuk.fanfou.domain.STATUS_LIMIT import com.sinyuk.fanfou.domain.StatusCreation import com.sinyuk.fanfou.glide.GlideApp import com.sinyuk.fanfou.ui.QMUIRoundButtonDrawable import com.sinyuk.fanfou.util.PictureHelper import com.sinyuk.fanfou.util.obtainViewModelFromActivity import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory import com.sinyuk.fanfou.viewmodel.PlayerViewModel import com.sinyuk.myutils.system.ToastUtils import kotlinx.android.synthetic.main.editor_picture_list_item.view.* import kotlinx.android.synthetic.main.editor_view.* import javax.inject.Inject /** * Created by sinyuk on 2018/1/16. * */ class EditorView : AbstractFragment(), Injectable, QueryTokenReceiver, SuggestionsResultListener, SuggestionsVisibilityManager { companion object { fun newInstance(id: String? = null, content: MentionsEditable? = null, action: Int, screenName: String? = null) = EditorView().apply { arguments = Bundle().apply { putString("id", id) putParcelable("content", content) putInt("action", action) putString("screenName", screenName) } } const val OPEN_PICTURE_REQUEST_CODE = 0X123 } override fun layoutId() = R.layout.editor_view @Inject lateinit var factory: FanfouViewModelFactory private val queryMap = mutableMapOf<String, String?>() private val playerViewModel by lazy { obtainViewModelFromActivity(factory, PlayerViewModel::class.java) } override fun onEnterAnimationEnd(savedInstanceState: Bundle?) { super.onEnterAnimationEnd(savedInstanceState) closeButton.setOnClickListener { pop() } setupKeyboard() setupEditor() renderUI() val action = arguments!!.getInt("action") when (action) { StatusCreation.CREATE_NEW -> { actionButton.text = "发送" } StatusCreation.REPOST_STATUS -> { arguments!!.getParcelable<MentionsEditable>("content")?.let { contentEt.text = it } arguments!!.getString("id")?.let { queryMap["repost_status_id"] = it } actionButton.text = "转发" } else -> TODO() } onFormValidation(0) } private val config = WordTokenizerConfig.Builder().setExplicitChars("@").setThreshold(1).setWordBreakChars(" ").build() private fun setupEditor() { contentEt.tokenizer = WordTokenizer(config) contentEt.setAvoidPrefixOnTap(true) contentEt.setQueryTokenReceiver(this) contentEt.setSuggestionsVisibilityManager(this) contentEt.setAvoidPrefixOnTap(true) textCountProgress.max = STATUS_LIMIT if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) textCountProgress.min = 0 // contentEt.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(STATUS_LIMIT)) contentEt.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { onTextCountUpdated(s?.length ?: 0) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) } /** * @param count 字数 */ private fun onTextCountUpdated(count: Int) { onFormValidation(count) textCountProgress.progress = count textCount.text = count.toString() } private fun renderUI() { actionButton.setOnClickListener { } addPictureButton.setOnClickListener { startActivityForResult(PictureHelper.fileSearchIntent(), OPEN_PICTURE_REQUEST_CODE) } pictureItem.image.setOnClickListener { startActivityForResult(PictureHelper.fileSearchIntent(), OPEN_PICTURE_REQUEST_CODE) } pictureItem.deleteButton.setOnClickListener { viewAnimator.displayedChildId = R.id.emptyLayout uri = null GlideApp.with(this).clear(pictureItem.image) onFormValidation(contentEt.text.length) } pictureItem.editButton.setOnClickListener { val editIntent = Intent(Intent.ACTION_EDIT) editIntent.setDataAndType(uri, "image/*") editIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION startActivity(Intent.createChooser(editIntent, null)) } } private var keyboardListener: ViewTreeObserver.OnGlobalLayoutListener? = null private fun setupKeyboard() { nestedScrollView.setOnTouchListener { _, event -> if (event.action == MotionEvent.ACTION_UP) KPSwitchConflictUtil.hidePanelAndKeyboard(panelRoot) return@setOnTouchListener false } keyboardListener = KeyboardUtil.attach(activity, panelRoot, { panelRoot.visibility = if (it) { if (contentEt.requestFocus()) contentEt.setSelection(contentEt.text.length) View.VISIBLE } else { contentEt.clearFocus() View.GONE } }) } @Suppress("PrivatePropertyName") private val BUCKET = "player-mentioned" override fun onQueryReceived(queryToken: QueryToken): MutableList<String> { val data = playerViewModel.filter(queryToken.keywords) onReceiveSuggestionsResult(SuggestionsResult(queryToken, data), BUCKET) return arrayOf(BUCKET).toMutableList() } override fun onReceiveSuggestionsResult(result: SuggestionsResult, bucket: String) { val data = result.suggestions displaySuggestions(data?.isNotEmpty() == true) if (data?.isEmpty() != false) return if (findChildFragment(MentionListView::class.java) == null) { val fragment = MentionListView.newInstance(data.toTypedArray()) fragment.onItemClickListener = object : MentionListView.OnItemClickListener { override fun onItemClick(position: Int, item: Suggestible) { (item as Player).let { contentEt.insertMention(it) displaySuggestions(false) playerViewModel.updateMentionedAt(it) // onTextCountUpdated(contentEt.text.length) contentEt.requestFocus() contentEt.setSelection(contentEt.text.length) } } } loadRootFragment(R.id.mentionLayout, fragment) } else { findChildFragment(MentionListView::class.java)?.apply { showHideFragment(this) setData(data = data) } } } override fun displaySuggestions(display: Boolean) { viewAnimator.displayedChildId = if (display) { R.id.mentionLayout } else { if (uri == null) { R.id.emptyLayout } else { R.id.pictureLayout } } } private fun onFormValidation(count: Int) { if (count in 1..STATUS_LIMIT || isPictureValid()) { if (actionButton.isEnabled) return (actionButton.background as QMUIRoundButtonDrawable).color = ColorStateList.valueOf(ContextCompat.getColor(context!!, R.color.colorControlActivated)) actionButton.isEnabled = true } else { if (!actionButton.isEnabled) return (actionButton.background as QMUIRoundButtonDrawable).color = ColorStateList.valueOf(ContextCompat.getColor(context!!, R.color.colorControlDisable)) actionButton.isEnabled = false } } private fun isPictureValid() = uri != null override fun isDisplayingSuggestions() = viewAnimator.displayedChildId == R.id.mentionLayout override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // The ACTION_OPEN_DOCUMENT intent was sent with the request code // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the // response to some other intent, and the code below shouldn't run at all. if (requestCode == OPEN_PICTURE_REQUEST_CODE && resultCode == Activity.RESULT_OK) { // The document selected by the user won't be returned in the intent. // Instead, a URI to that document will be contained in the return intent // provided to this method as a parameter. // Pull that URI using resultData.getData(). data?.let { showImage(it.data) } } } @Inject lateinit var toast: ToastUtils private var uri: Uri? = null private fun showImage(data: Uri?) { if (data == null) { uri = null onFormValidation(contentEt.text.length) GlideApp.with(this).clear(pictureItem.image) viewAnimator.displayedChildId = R.id.emptyLayout } else { GlideApp.with(this).asBitmap().load(data).listener(object : RequestListener<Bitmap> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean { toast.toastShort(e?.message ?: "( ˉ ⌓ ˉ ๑)图片加载失败") viewAnimator.displayedChildId = if (uri == null) { R.id.emptyLayout } else { R.id.pictureLayout } onFormValidation(contentEt.text.length) return false } override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean { uri = data onFormValidation(contentEt.text.length) viewAnimator.displayedChildId = R.id.pictureLayout return false } }).into(pictureItem.image) } } override fun onDestroy() { keyboardListener?.let { KeyboardUtil.detach(activity, it) } activity?.currentFocus?.let { KeyboardUtil.hideKeyboard(it) } super.onDestroy() } }
mit
c4d6e7c523e73fd33a145dd6accc77ae
37.330303
163
0.652435
4.751315
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/lang-api/src/com/intellij/execution/configurations/LogFileOptions.kt
3
4327
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.execution.configurations import com.intellij.openapi.components.BaseState import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.util.SmartList import com.intellij.util.containers.SmartHashSet import com.intellij.util.xmlb.Converter import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Tag import java.io.File import java.nio.charset.Charset import java.util.regex.Pattern /** * The information about a single log file displayed in the console when the configuration * is run. * * @since 5.1 */ @Tag("log_file") class LogFileOptions : BaseState { companion object { @JvmStatic fun collectMatchedFiles(root: File, pattern: Pattern, files: MutableList<File>) { val dirs = root.listFiles() ?: return dirs.filterTo(files) { pattern.matcher(it.name).matches() && it.isFile } } @JvmStatic fun areEqual(options1: LogFileOptions?, options2: LogFileOptions?): Boolean { return if (options1 == null || options2 == null) { options1 === options2 } else options1.name == options2.name && options1.pathPattern == options2.pathPattern && !options1.isShowAll == !options2.isShowAll && options1.isEnabled == options2.isEnabled && options1.isSkipContent == options2.isSkipContent } } @get:Attribute("alias") var name by string() @get:Attribute(value = "path", converter = PathConverter::class) var pathPattern by string() @get:Attribute("checked") var isEnabled by property(true) @get:Attribute("skipped") var isSkipContent by property(true) @get:Attribute("show_all") var isShowAll by property(false) @get:Attribute(value = "charset", converter = CharsetConverter::class) var charset: Charset by property(Charset.defaultCharset()) fun getPaths(): Set<String> { val logFile = File(pathPattern!!) if (logFile.exists()) { return setOf(pathPattern!!) } val dirIndex = pathPattern!!.lastIndexOf(File.separator) if (dirIndex == -1) { return emptySet() } val files = SmartList<File>() collectMatchedFiles(File(pathPattern!!.substring(0, dirIndex)), Pattern.compile(FileUtil.convertAntToRegexp(pathPattern!!.substring(dirIndex + File.separator.length))), files) if (files.isEmpty()) { return emptySet() } if (isShowAll) { val result = SmartHashSet<String>() result.ensureCapacity(files.size) files.mapTo(result) { it.path } return result } else { var lastFile: File? = null for (file in files) { if (lastFile != null) { if (file.lastModified() > lastFile.lastModified()) { lastFile = file } } else { lastFile = file } } assert(lastFile != null) return setOf(lastFile!!.path) } } //read external constructor() @JvmOverloads constructor(name: String?, path: String?, enabled: Boolean = true, skipContent: Boolean = true, showAll: Boolean = false) : this(name, path, null, enabled, skipContent, showAll) @JvmOverloads constructor(name: String?, path: String?, charset: Charset?, enabled: Boolean = true, skipContent: Boolean = true, showAll: Boolean = false) { this.name = name pathPattern = path isEnabled = enabled isSkipContent = skipContent isShowAll = showAll this.charset = charset ?: Charset.defaultCharset() } fun setLast(last: Boolean) { isShowAll = !last } } private class PathConverter : Converter<String>() { override fun fromString(value: String): String? { return FileUtilRt.toSystemDependentName(value) } override fun toString(value: String): String { return FileUtilRt.toSystemIndependentName(value) } } private class CharsetConverter : Converter<Charset>() { override fun fromString(value: String): Charset? { return try { Charset.forName(value) } catch (ignored: Exception) { Charset.defaultCharset() } } override fun toString(value: Charset): String { return value.name() } }
apache-2.0
48e916318ac6c7d556d4a1b440b5b002
27.662252
179
0.671828
4.101422
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Widget/GatherDialogFragment.kt
1
5705
package stan.androiddemo.project.petal.Widget import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.widget.* import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import stan.androiddemo.R import stan.androiddemo.project.petal.API.OperateAPI import stan.androiddemo.project.petal.Base.BaseDialogFragment import stan.androiddemo.project.petal.Event.OnDialogInteractionListener import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient import stan.androiddemo.project.petal.Module.ImageDetail.GatherInfoBean import stan.androiddemo.tool.Logger /** * Created by stanhu on 14/8/2017. */ class GatherDialogFragment: BaseDialogFragment() { lateinit var mEditTextDescribe: EditText lateinit var mTVGatherWarning: TextView lateinit var mSpinnerBoardTitle: Spinner lateinit var mContext: Context lateinit var mViaId: String lateinit var mDescribeText: String lateinit var mBoardTitleArray: ArrayList<String> private var mSelectPosition = 0//默认的选中项 var mListener:OnDialogInteractionListener? = null override fun getTAGInfo(): String { return this.toString() } companion object { private val KEYAUTHORIZATION = "keyAuthorization" private val KEYVIAID = "keyViaId" private val KEYDESCRIBE = "keyDescribe" private val KEYBOARDTITLEARRAY = "keyBoardTitleArray" fun create(authorization:String,viaId:String,describe:String,boardTitleArray:ArrayList<String>):GatherDialogFragment{ val bundle = Bundle() bundle.putString(KEYAUTHORIZATION,authorization) bundle.putString(KEYVIAID,viaId) bundle.putString(KEYDESCRIBE,describe) bundle.putStringArrayList(KEYBOARDTITLEARRAY,boardTitleArray) val fragment = GatherDialogFragment() fragment.arguments = bundle return fragment } } override fun onAttach(context: Context?) { super.onAttach(context) mContext = context!! if (context is OnDialogInteractionListener){ mListener = context } else{ throwRuntimeException(context) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mAuthorization = arguments.getString(KEYAUTHORIZATION) mViaId = arguments.getString(KEYVIAID) mDescribeText = arguments.getString(KEYDESCRIBE) mBoardTitleArray = arguments.getStringArrayList(KEYBOARDTITLEARRAY) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(mContext) builder.setTitle(resources.getString(R.string.dialog_title_gather)) val inflate = LayoutInflater.from(mContext) val dialogView = inflate.inflate(R.layout.petal_dialog_gather,null) initView(dialogView) builder.setView(dialogView) builder.setNegativeButton(resources.getString(R.string.dialog_negative),null) builder.setPositiveButton(resources.getString(R.string.dialog_gather_positive),DialogInterface.OnClickListener { dialogInterface, i -> var input = mEditTextDescribe.text.toString().trim() if (input.isNullOrEmpty()){ input = mEditTextDescribe.hint.toString() } mListener?.onDialogClick(true, hashMapOf("describe" to input,"position" to mSelectPosition)) }) addSubscription(getGatherInfo()) return builder.create() } fun initView(view: View){ mEditTextDescribe = view.findViewById(R.id.edit_describe) mTVGatherWarning = view.findViewById(R.id.tv_gather_warning) mSpinnerBoardTitle = view.findViewById(R.id.spinner_title) val adapter = ArrayAdapter<String>(context,R.layout.support_simple_spinner_dropdown_item,mBoardTitleArray) if (!mDescribeText.isNullOrEmpty()){ mEditTextDescribe.hint = mDescribeText } else{ mEditTextDescribe.hint = resources.getString(R.string.text_image_describe_null) } mSpinnerBoardTitle.adapter = adapter mSpinnerBoardTitle.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { Logger.d("position=" + position) mSelectPosition = position } override fun onNothingSelected(parent: AdapterView<*>) { } } } fun getGatherInfo():Subscription{ return RetrofitClient.createService(OperateAPI::class.java).httpsGatherInfo(mAuthorization,mViaId,true) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object:Subscriber<GatherInfoBean>(){ override fun onNext(t: GatherInfoBean?) { if (t?.exist_pin != null){ val format = resources.getString(R.string.text_gather_warning) mTVGatherWarning.visibility = View.VISIBLE mTVGatherWarning.text = String.format(format,t!!.exist_pin!!.board?.title) } } override fun onError(e: Throwable?) { } override fun onCompleted() { } }) } }
mit
fd5f3aa34d2843f61c5879b919d6e46d
37.214765
142
0.671702
4.94184
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/ast/optimize/ast_optimize.kt
1
10987
package com.jtransc.ast.optimize import com.jtransc.ast.* import com.jtransc.log.log //const val DEBUG = false //const val DEBUG = true // @TODO: rewrite using method.transformInplace class AstOptimizer(val flags: AstBodyFlags) : AstVisitor() { val types: AstTypes = flags.types private var stm: AstStm? = null override fun visit(stm: AstStm?) { super.visit(stm) this.stm = stm } val METHODS_TO_STRIP = setOf<AstMethodRef>( AstMethodRef("kotlin.jvm.internal.Intrinsics".fqname, "checkParameterIsNotNull", AstType.METHOD(AstType.VOID, listOf(AstType.OBJECT, AstType.STRING))) ) private val invertComparisons = mapOf( AstBinop.LT to AstBinop.GE, AstBinop.LE to AstBinop.GT, AstBinop.EQ to AstBinop.NE, AstBinop.NE to AstBinop.EQ, AstBinop.GT to AstBinop.LE, AstBinop.GE to AstBinop.LT ) override fun visit(expr: AstExpr.BINOP) { super.visit(expr) val box = expr.box val left = expr.left.value val right = expr.right.value when (expr.op) { AstBinop.EQ, AstBinop.NE -> { if ((left is AstExpr.CAST) && (right is AstExpr.LITERAL)) { if (left.from == AstType.BOOL && left.to == AstType.INT && right.value is Int) { //println("optimize") val leftExpr = left.subject.value val toZero = right.value == 0 val equals = expr.op == AstBinop.EQ box.value = if (toZero xor equals) leftExpr else AstExpr.UNOP(AstUnop.NOT, leftExpr) AstAnnotateExpressions.visitExprWithStm(stm, box) } } } AstBinop.LT, AstBinop.LE, AstBinop.GT, AstBinop.GE -> { if (!flags.strictfp && (left is AstExpr.BINOP) && (right is AstExpr.LITERAL)) { when (left.op) { AstBinop.CMPG, AstBinop.CMPL -> { val l = left.left val r = left.right val op = expr.op val compareValue = right.value if (compareValue == 0) { box.value = AstExpr.UNOP(AstUnop.NOT, AstExpr.BINOP(AstType.BOOL, l.value, invertComparisons[op]!!, r.value)) } else { log.warn("WARNING: Unhandled float comparison (because compareValue != 0)! op = ${expr.op} :: compareValue = $compareValue") } } else -> Unit } } } else -> Unit } } override fun visit(expr: AstExpr.CALL_BASE) { //println("CALL_BASE:$expr:${expr.method}") super.visit(expr) } override fun visit(expr: AstExpr.CALL_STATIC) { super.visit(expr) if (expr.method in METHODS_TO_STRIP) { //println("STRIP:${expr.method}") expr.stm?.box?.value = AstStm.NOP("method to strip") } else { //println("NO_STRIP:${expr.method}") } } override fun visit(body: AstBody?) { if (body == null) return // @TODO: this should be easier when having the SSA form for (local in body.locals) { if (local.writes.size == 1) { val write = local.writes[0] var writeExpr2 = write.expr.value while (writeExpr2 is AstExpr.CAST) writeExpr2 = writeExpr2.subject.value val writeExpr = writeExpr2 //println("Single write: $local = $writeExpr") when (writeExpr) { is AstExpr.PARAM, is AstExpr.THIS -> { // LITERALS! for (read in local.reads) { //println(" :: read: $read") read.box.value = write.expr.value.clone() } write.box.value = AstStm.NOP("optimized literal") local.writes.clear() local.reads.clear() } } //println("Written once! $local") } } super.visit(body) // REMOVE UNUSED VARIABLES //body.locals = body.locals.filter { it.isUsed } val unoptstms = body.stm.expand() //if (unoptstms.any { it is AstStm.NOP }) { // println("done") //} val optstms = unoptstms.filter { it !is AstStm.NOP } body.stm = optstms.stm() //if (unoptstms.any { it is AstStm.NOP }) { // println("done") //} val stms = body.stm.expand().map { it.box } var n = 0 while (n < stms.size) { val startStmIndex = n val abox = stms[n++] val a = abox.value if ((a is AstStm.SET_ARRAY) && (a.index.value is AstExpr.LITERAL) && (a.array.value is AstExpr.CAST) && ((a.array.value as AstExpr.CAST).subject.value is AstExpr.LOCAL)) { val exprs = arrayListOf<AstExpr.Box>() val alocal = ((a.array.value as AstExpr.CAST).subject.value as AstExpr.LOCAL).local val baseindex = (a.index.value as AstExpr.LITERAL).value as Int var lastindex = baseindex exprs += a.expr while (n < stms.size) { val bbox = stms[n++] val b = bbox.value if ((b is AstStm.SET_ARRAY) && (b.index.value is AstExpr.LITERAL) && (b.array.value is AstExpr.CAST) && ((b.array.value as AstExpr.CAST).subject.value is AstExpr.LOCAL)) { val blocal = ((b.array.value as AstExpr.CAST).subject.value as AstExpr.LOCAL).local val nextindex = (b.index.value as AstExpr.LITERAL).value as Int if (alocal == blocal && nextindex == lastindex + 1) { exprs += b.expr //println("$baseindex, $lastindex, $nextindex") lastindex = nextindex continue } } n-- break } if (baseindex != lastindex) { for (m in startStmIndex until n) stms[m].value = AstStm.NOP("array_literals") stms[startStmIndex].value = AstStm.SET_ARRAY_LITERALS(a.array.value, baseindex, exprs) //println("ranged: $baseindex, $lastindex") } } } } override fun visit(stm: AstStm.STMS) { super.visit(stm) for (n in 1 until stm.stms.size) { val abox = stm.stms[n - 1] val bbox = stm.stms[n - 0] val a = abox.value val b = bbox.value //println("${a.javaClass}") if (a is AstStm.SET_LOCAL && b is AstStm.SET_LOCAL) { val alocal = a.local.local val blocal = b.local.local val aexpr = a.expr.value val bexpr = b.expr.value if (aexpr is AstExpr.LOCAL && bexpr is AstExpr.LOCAL) { //println("double set locals! $alocal = ${aexpr.local} :: ${blocal} == ${bexpr.local}") if ((alocal == bexpr.local) && (aexpr.local == blocal)) { //println("LOCAL[a]:" + alocal) blocal.writes.remove(b) alocal.reads.remove(bexpr) val aold = a abox.value = AstStm.NOP("optimized set local") bbox.value = aold //println("LOCAL[b]:" + alocal) //println("double set! CROSS!") } } } if (a is AstStm.SET_LOCAL && a.expr.value is AstExpr.LOCAL) { //val blocal = a.expr.value as AstExpr.LOCAL val alocal = a.local.local if (alocal.writesCount == 1 && alocal.readCount == 1 && alocal.reads.first().stm == b) { alocal.reads.first().box.value = a.expr.value abox.value = AstStm.NOP("optimized set local 2") alocal.writes.clear() alocal.reads.clear() } } } val finalStms = stm.stms.filter { it.value !is AstStm.NOP } if (finalStms.size == 1) { stm.box.value = finalStms.first().value } } override fun visit(expr: AstExpr.UNOP) { super.visit(expr) if (expr.op == AstUnop.NOT) { val right = expr.right.value when (right) { is AstExpr.BINOP -> { val newop = when (right.op) { AstBinop.NE -> AstBinop.EQ AstBinop.EQ -> AstBinop.NE AstBinop.LT -> AstBinop.GE AstBinop.LE -> AstBinop.GT AstBinop.GT -> AstBinop.LE AstBinop.GE -> AstBinop.LT else -> null } if (newop != null) expr.box.value = AstExpr.BINOP(right.type, right.left.value, newop, right.right.value) } is AstExpr.UNOP -> { if (right.op == AstUnop.NOT) { // negate twice! expr.box.value = right.right.value } } } } } override fun visit(stm: AstStm.SET_LOCAL) { super.visit(stm) val box = stm.box val expr = stm.expr.value val storeLocal = stm.local.local if (expr is AstExpr.LOCAL) { // FIX: Assigning a value to itself if (storeLocal == expr.local) { storeLocal.writes.remove(stm) storeLocal.reads.remove(expr) box.value = AstStm.NOP("assign to itself") return } } // Do not assign and remove variables that are not going to be used! if (storeLocal.readCount == 0 && storeLocal.writesCount == 1) { box.value = AstStm.STM_EXPR(stm.expr.value) storeLocal.writes.clear() visit(box) return } // Dummy cast if (expr is AstExpr.CAST && stm.local.type == expr.from) { val exprBox = expr.box exprBox.value = expr.subject.value AstAnnotateExpressions.visitExprWithStm(stm, exprBox) return } } override fun visit(stm: AstStm.IF) { super.visit(stm) val strue = stm.strue.value if (strue is AstStm.IF) { val cond = AstExpr.BINOP(AstType.BOOL, stm.cond.value, AstBinop.BAND, strue.cond.value) stm.box.value = AstStm.IF(cond, strue.strue.value) } } override fun visit(stm: AstStm.IF_ELSE) { super.visit(stm) val cond = stm.cond.value val strue = stm.strue.value val sfalse = stm.sfalse.value if ((strue is AstStm.SET_LOCAL) && (sfalse is AstStm.SET_LOCAL) && (strue.local.local == sfalse.local.local)) { val local = strue.local // TERNARY OPERATOR //println("ternary!") local.local.writes.remove(strue) local.local.writes.remove(sfalse) val newset = local.setTo(AstExpr.TERNARY(cond, strue.expr.value, sfalse.expr.value, types)) stm.box.value = newset local.local.writes.add(newset) } } override fun visit(stm: AstStm.STM_EXPR) { // Remove unnecessary cast while (stm.expr.value is AstExpr.CAST) { //println(stm.expr.value) stm.expr.value = (stm.expr.value as AstExpr.CAST).subject.value } super.visit(stm) if (stm.expr.value.isPure()) { stm.box.value = AstStm.NOP("pure stm") } } } object AstAnnotateExpressions : AstVisitor() { private var stm: AstStm? = null fun visitExprWithStm(stm: AstStm?, box: AstExpr.Box) { this.stm = stm visit(box) } override fun visit(stm: AstStm?) { this.stm = stm super.visit(stm) } override fun visit(expr: AstExpr?) { expr?.stm = stm super.visit(expr) } } val OPTIMIZATIONS = listOf( { AstCastOptimizer() } ) val STM_OPTIMIZATIONS = listOf( { AstLocalTyper() } ) fun AstBody.optimize() = this.apply { AstAnnotateExpressions.visit(this) AstOptimizer(this.flags).visit(this) for (opt in OPTIMIZATIONS) opt().transformAndFinish(this) for (opt in STM_OPTIMIZATIONS) opt().transformAndFinish(this) invalidate() } fun AstStm.Box.optimize(flags: AstBodyFlags) = this.apply { AstAnnotateExpressions.visit(this) AstOptimizer(flags).visit(this) for (opt in OPTIMIZATIONS) opt().transformAndFinish(this) for (opt in STM_OPTIMIZATIONS) opt().transformAndFinish(this) } fun AstExpr.Box.optimize(types: AstTypes, strictfp: Boolean = true) = this.optimize(AstBodyFlags(types, strictfp)) fun AstExpr.Box.optimize(flags: AstBodyFlags) = this.apply { AstAnnotateExpressions.visit(this) AstOptimizer(flags).visit(this) for (opt in OPTIMIZATIONS) opt().transformAndFinish(this) } fun AstStm.optimize(types: AstTypes, strictfp: Boolean = true): AstStm = this.let { this.box.optimize(AstBodyFlags(types, strictfp)).value } fun AstStm.optimize(flags: AstBodyFlags): AstStm = this.let { this.box.optimize(flags).value } fun AstExpr.optimize(flags: AstBodyFlags): AstExpr = this.let { this.box.optimize(flags).value }
apache-2.0
1245b76b33dba98c766669e99922931a
28.143236
176
0.650405
2.95986
false
false
false
false
intrigus/jtransc
jtransc-utils/src/com/jtransc/util/NumberExt.kt
2
4408
@file:Suppress("NOTHING_TO_INLINE") package com.jtransc.util inline fun Int.mask(): Int = (1 shl this) - 1 inline fun Long.mask(): Long = (1L shl this.toInt()) - 1L fun Int.toUInt(): Long = this.toLong() and 0xFFFFFFFFL fun Int.getBits(offset: Int, count: Int): Int = (this ushr offset) and count.mask() fun Int.extract(offset: Int, count: Int): Int = (this ushr offset) and count.mask() fun Int.extract8(offset: Int): Int = (this ushr offset) and 0xFF fun Int.extract(offset: Int): Boolean = ((this ushr offset) and 1) != 0 fun Int.extractScaled(offset: Int, count: Int, scale: Int): Int { val mask = count.mask() return (extract(offset, count) * scale) / mask } fun Int.extractScaledf01(offset: Int, count: Int): Double { val mask = count.mask().toDouble() return extract(offset, count).toDouble() / mask } fun Int.extractScaledFF(offset: Int, count: Int): Int = extractScaled(offset, count, 0xFF) fun Int.extractScaledFFDefault(offset: Int, count: Int, default: Int): Int = if (count == 0) default else extractScaled(offset, count, 0xFF) fun Int.insert(value: Int, offset: Int, count: Int): Int { val mask = count.mask() val clearValue = this and (mask shl offset).inv() return clearValue or ((value and mask) shl offset) } fun Int.insert8(value: Int, offset: Int): Int = insert(value, offset, 8) fun Int.insert(value: Boolean, offset: Int): Int = this.insert(if (value) 1 else 0, offset, 1) fun Int.insertScaled(value: Int, offset: Int, count: Int, scale: Int): Int { val mask = count.mask() return insert((value * mask) / scale, offset, count) } fun Int.insertScaledFF(value: Int, offset: Int, count: Int): Int = if (count == 0) this else this.insertScaled(value, offset, count, 0xFF) fun Long.nextAlignedTo(align: Long) = if (this % align == 0L) { this } else { (((this / align) + 1) * align) } fun Int.clamp(min: Int, max: Int): Int = if (this < min) min else if (this > max) max else this fun Double.clamp(min: Double, max: Double): Double = if (this < min) min else if (this > max) max else this fun Long.clamp(min: Long, max: Long): Long = if (this < min) min else if (this > max) max else this fun Long.toIntSafe(): Int { if (this.toInt().toLong() != this) throw IllegalArgumentException("Long doesn't fit Integer") return this.toInt() } fun Long.toIntClamp(min: Int = Int.MIN_VALUE, max: Int = Int.MAX_VALUE): Int { if (this < min) return min if (this > max) return max return this.toInt() } fun Long.toUintClamp(min: Int = 0, max: Int = Int.MAX_VALUE) = this.toIntClamp(0, Int.MAX_VALUE) fun String.toDoubleOrNull2(): Double? = try { this.toDouble() } catch (e: NumberFormatException) { null } fun String.toLongOrNull2(): Long? = try { this.toLong() } catch (e: NumberFormatException) { null } fun String.toIntOrNull2(): Int? = try { this.toInt() } catch (e: NumberFormatException) { null } fun String.toNumber(): Number = this.toIntOrNull2() as Number? ?: this.toLongOrNull2() as Number? ?: this.toDoubleOrNull2() as Number? ?: 0 fun Byte.toUnsigned() = this.toInt() and 0xFF fun Int.toUnsigned() = this.toLong() and 0xFFFFFFFFL fun Int.signExtend(bits: Int) = (this shl (32 - bits)) shr (32 - bits) fun Long.signExtend(bits: Int) = (this shl (64 - bits)) shr (64 - bits) infix fun Int.umod(other: Int): Int { val remainder = this % other return when { remainder < 0 -> remainder + other else -> remainder } } fun Double.convertRange(srcMin: Double, srcMax: Double, dstMin: Double, dstMax: Double): Double { val ratio = (this - srcMin) / (srcMax - srcMin) return (dstMin + (dstMax - dstMin) * ratio) } fun Long.convertRange(srcMin: Long, srcMax: Long, dstMin: Long, dstMax: Long): Long { val ratio = (this - srcMin).toDouble() / (srcMax - srcMin).toDouble() return (dstMin + (dstMax - dstMin) * ratio).toLong() } object Bits { @JvmStatic fun mask(count: Int): Int = (1 shl count) - 1 @JvmStatic fun extract(data: Int, offset: Int, length: Int): Int { return (data ushr offset) and mask(length) } @JvmStatic fun extractBool(data: Int, offset: Int): Boolean = extract(data, offset, 1) != 0 } fun Int.extractBool(offset: Int): Boolean = Bits.extractBool(this, offset) fun Int.hasBitmask(mask: Int): Boolean = (this and mask) == mask fun Int.withBool(offset: Int): Int { val v = (1 shl offset) return (this and v.inv()) or (v) } fun Int.withoutBool(offset: Int): Int { val v = (1 shl offset) return (this and v.inv()) }
apache-2.0
c63fb84b27144f25ab40ae4abb1d12e6
31.411765
140
0.681488
3.031637
false
false
false
false
deviant-studio/energy-meter-scanner
app/src/main/java/ds/meterscanner/mvvm/view/ChartsActivity.kt
1
4380
package ds.meterscanner.mvvm.view import android.app.Activity import android.content.Intent import android.view.Menu import android.view.MenuItem import ds.bindingtools.withBindable import ds.meterscanner.R import ds.meterscanner.mvvm.BindableActivity import ds.meterscanner.mvvm.ChartsView import ds.meterscanner.mvvm.viewmodel.ChartsViewModel import ds.meterscanner.mvvm.viewmodel.Period import ds.meterscanner.util.FileTools import kotlinx.android.synthetic.main.activity_charts.* import kotlinx.android.synthetic.main.toolbar.* import lecho.lib.hellocharts.gesture.ZoomType import lecho.lib.hellocharts.model.ColumnChartData import lecho.lib.hellocharts.model.Viewport import lecho.lib.hellocharts.util.ChartUtils class ChartsActivity : BindableActivity<ChartsViewModel>(), ChartsView { override fun provideViewModel(): ChartsViewModel = defaultViewModelOf() override fun getLayoutId(): Int = R.layout.activity_charts override fun bindView() { super.bindView() toolbar.title = getString(R.string.charts) columnsChart.isScrollEnabled = false columnsChart.isZoomEnabled = false linesChart.isScrollEnabled = false linesChart.isZoomEnabled = false previewChart.setViewportChangeListener(ViewportListener(columnsChart, linesChart)) radioGroup.setOnCheckedChangeListener { _, checkedId -> viewModel.onCheckedChanged(checkedId) } withBindable(viewModel) { bind(::linesData, { linesChart.lineChartData = it val v = Viewport(linesChart.maximumViewport.left, 30f, linesChart.maximumViewport.right, -30f) linesChart.maximumViewport = v }) bind(::columnsData, columnsChart::setColumnChartData) bind(::columnsData, { val previewData = ColumnChartData(it) previewData .columns .flatMap { it.values } .forEach { it.color = ChartUtils.DEFAULT_DARKEN_COLOR } previewData.axisYLeft = null previewData.axisXBottom = null previewChart.columnChartData = previewData val tempViewport = Viewport(columnsChart.maximumViewport) val visibleItems = 20 tempViewport.left = tempViewport.right - visibleItems previewChart.currentViewport = tempViewport previewChart.zoomType = ZoomType.HORIZONTAL }) bind(this::checkedButtonId, radioGroup::check, radioGroup::getCheckedRadioButtonId) bind(::showProgress, { radioGroup.isEnabled = !it }) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.charts, menu) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu): Boolean { menu.findItem(when (viewModel.period) { Period.ALL -> R.id.action_period_all Period.YEAR -> R.id.action_period_year Period.LAST_SEASON -> R.id.action_period_season }).isChecked = true menu.findItem(R.id.action_correction).isChecked = viewModel.positiveCorrection menu.findItem(R.id.action_show_temp).isChecked = viewModel.tempVisible return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.isCheckable) item.isChecked = !item.isChecked when (item.itemId) { R.id.action_correction -> viewModel.toggleCorection(item.isChecked) R.id.action_show_temp -> viewModel.toggleTemperature(item.isChecked) R.id.action_period_all -> viewModel.period = Period.ALL R.id.action_period_year -> viewModel.period = Period.YEAR R.id.action_period_season -> viewModel.period = Period.LAST_SEASON R.id.action_export_csv -> FileTools.chooseDir(this, FileTools.CSV_FILE_NAME) } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == Requests.SAVE_FILE && resultCode == Activity.RESULT_OK) { viewModel.onDirectoryChoosen(contentResolver, data!!.data) } } }
mit
cfe75c38604e7e38018ba0aede19fe4d
41.941176
110
0.676941
4.5625
false
false
false
false
Duke1/UnrealMedia
UnrealMedia/app/src/main/java/com/qfleng/um/util/Extension.kt
1
3761
package com.qfleng.um.util import android.content.Context import android.text.TextUtils import com.google.gson.* import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken import com.google.gson.stream.JsonWriter import java.io.IOException import java.lang.annotation.ElementType import java.lang.annotation.Retention import java.lang.annotation.RetentionPolicy import java.lang.annotation.Target import java.lang.reflect.Type class StringConverter : JsonSerializer<String>, JsonDeserializer<String> { override fun serialize(src: String?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return if (src == null) { JsonPrimitive("") } else { JsonPrimitive(src.toString()) } } @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): String { return json .asJsonPrimitive .asString } } class StringAdapter : TypeAdapter<String>() { @Throws(IOException::class) override fun read(reader: JsonReader): String { if (reader.peek() == JsonToken.NULL) { reader.nextNull() return "" } return reader.nextString() } @Throws(IOException::class) override fun write(writer: JsonWriter, value: String?) { if (value == null) { writer.jsonValue("\"\"") return } writer.value(value) } } /** * Gson扩展 */ fun <T> Context.objectFrom(tClass: Class<T>, str: String): T? { if (TextUtils.isEmpty(str)) return null return gsonObjectFrom(tClass, str) } fun <T> gsonObjectFrom(tClass: Class<T>, str: String): T? { if (TextUtils.isEmpty(str)) return null try { return GsonBuilder() .serializeNulls() .registerTypeAdapter(String::class.java, StringConverter()) .create() .fromJson(str, tClass) } catch (e: Exception) { e.printStackTrace() return null } } fun Any?.toJsonString(fast: Boolean = false): String { if (null == this) return "" try { return if (fast) { GsonBuilder() .addSerializationExclusionStrategy(object : ExclusionStrategy { override fun shouldSkipField(f: FieldAttributes): Boolean { return null != f.getAnnotation(ObjectFieldExclude::class.java) } override fun shouldSkipClass(clazz: Class<*>): Boolean { return false } }) .create().toJson(this) } else { GsonBuilder() .serializeNulls() .addSerializationExclusionStrategy(object : ExclusionStrategy { override fun shouldSkipField(f: FieldAttributes): Boolean { return null != f.getAnnotation(ObjectFieldExclude::class.java) } override fun shouldSkipClass(clazz: Class<*>): Boolean { return false } }) .registerTypeAdapter(String::class.java, StringAdapter()) // .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()) .create() .toJson(this) } } catch (e: Exception) { e.printStackTrace() return "" } } /** * Created by Duke . */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) annotation class ObjectFieldExclude
mit
d60a0262181a29612d0f8326545ca19b
29.056
109
0.56987
5.056528
false
false
false
false
quran/quran_android
app/src/main/java/com/quran/labs/androidquran/database/SuraTimingDatabaseHandler.kt
2
3094
package com.quran.labs.androidquran.database import android.database.Cursor import android.database.DefaultDatabaseErrorHandler import android.database.SQLException import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabaseCorruptException import timber.log.Timber import java.io.File import java.lang.Exception import java.util.HashMap class SuraTimingDatabaseHandler private constructor(path: String) { private var database: SQLiteDatabase? = null object TimingsTable { const val TABLE_NAME = "timings" const val COL_SURA = "sura" const val COL_AYAH = "ayah" const val COL_TIME = "time" } object PropertiesTable { const val TABLE_NAME = "properties" const val COL_PROPERTY = "property" const val COL_VALUE = "value" } companion object { private val databaseMap: MutableMap<String, SuraTimingDatabaseHandler> = HashMap() @JvmStatic @Synchronized fun getDatabaseHandler(path: String): SuraTimingDatabaseHandler { var handler = databaseMap[path] if (handler == null) { handler = SuraTimingDatabaseHandler(path) databaseMap[path] = handler } return handler } @Synchronized fun clearDatabaseHandlerIfExists(databasePath: String) { try { val handler = databaseMap.remove(databasePath) if (handler != null) { handler.database?.close() databaseMap.remove(databasePath) } } catch (e: Exception) { Timber.e(e) } } } init { Timber.d("opening gapless data file, %s", path) database = try { SQLiteDatabase.openDatabase( path, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS, DefaultDatabaseErrorHandler() ) } catch (sce: SQLiteDatabaseCorruptException) { Timber.d("database corrupted: %s", path) null } catch (se: SQLException) { Timber.d("database at $path ${if (File(path).exists()) "exists " else "doesn 't exist"}") Timber.e(se) null } } private fun validDatabase(): Boolean = database?.isOpen ?: false fun getAyahTimings(sura: Int): Cursor? { if (!validDatabase()) return null return try { database?.query( TimingsTable.TABLE_NAME, arrayOf( TimingsTable.COL_SURA, TimingsTable.COL_AYAH, TimingsTable.COL_TIME ), TimingsTable.COL_SURA + "=" + sura, null, null, null, TimingsTable.COL_AYAH + " ASC" ) } catch (e: Exception) { null } } fun getVersion(): Int { if (!validDatabase()) { return -1 } var cursor: Cursor? = null return try { cursor = database?.query( PropertiesTable.TABLE_NAME, arrayOf(PropertiesTable.COL_VALUE), PropertiesTable.COL_PROPERTY + "= 'version'", null, null, null, null ) if (cursor != null && cursor.moveToFirst()) { cursor.getInt(0) } else { 1 } } catch (e: Exception) { 1 } finally { DatabaseUtils.closeCursor(cursor) } } }
gpl-3.0
e4a5211698653232a4ddb8c255139766
26.140351
95
0.631222
4.279391
false
false
false
false
line/armeria
examples/context-propagation/kotlin/src/main/kotlin/example/armeria/contextpropagation/kotlin/Main.kt
3
1558
/* * Copyright 2020 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * 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 example.armeria.contextpropagation.kotlin import com.linecorp.armeria.client.WebClient import com.linecorp.armeria.common.HttpResponse import com.linecorp.armeria.common.HttpStatus import com.linecorp.armeria.server.Server fun main() { val backend = Server.builder() .service("/square/{num}") { ctx, _ -> val num = ctx.pathParam("num")?.toLong() if (num != null) { HttpResponse.of((num * num).toString()) } else { HttpResponse.of(HttpStatus.BAD_REQUEST) } } .http(8081) .build() val backendClient = WebClient.of("http://localhost:8081") val frontend = Server.builder() .http(8080) .serviceUnder("/", MainService(backendClient)) .build() backend.closeOnJvmShutdown() frontend.closeOnJvmShutdown() backend.start().join() frontend.start().join() }
apache-2.0
853c954496c72e1ef40df9c6adb758b0
30.795918
78
0.667522
4.256831
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/SingleAction.kt
1
11330
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.action import android.os.Parcel import android.os.Parcelable import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport import jp.hazuki.yuzubrowser.legacy.action.item.* import jp.hazuki.yuzubrowser.legacy.action.item.startactivity.StartActivitySingleAction import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo import java.io.IOException open class SingleAction : Parcelable { val id: Int override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(id) } protected constructor(source: Parcel) { this.id = source.readInt() } //for extended class protected constructor(id: Int) { this.id = id //if(id < 0) throw new IllegalArgumentException(); } //node can be null @Throws(IOException::class) private constructor(id: Int, reader: JsonReader?) : this(id) { reader?.skipValue() } @Throws(IOException::class) open fun writeIdAndData(writer: JsonWriter) { writer.value(id) writer.nullValue() } open fun showMainPreference(context: ActionActivity): StartActivityInfo? { return null } open fun showSubPreference(context: ActionActivity): StartActivityInfo? { return null } open fun toString(nameArray: ActionNameArray): String? { for ((i, value) in nameArray.actionValues.withIndex()) { if (value == id) return nameArray.actionList[i] } return null } companion object { const val GO_BACK = 1000 const val GO_FORWARD = 1001 const val WEB_RELOAD_STOP = 1005 const val WEB_RELOAD = 1006 const val WEB_STOP = 1007 const val GO_HOME = 1020 const val ZOOM_IN = 1205 const val ZOOM_OUT = 1206 const val PAGE_UP = 1207 const val PAGE_DOWN = 1208 const val PAGE_TOP = 1209 const val PAGE_BOTTOM = 1210 const val PAGE_SCROLL = 1215 const val PAGE_FAST_SCROLL = 1216 const val PAGE_AUTO_SCROLL = 1217 const val FOCUS_UP = 1220 const val FOCUS_DOWN = 1221 const val FOCUS_LEFT = 1222 const val FOCUS_RIGHT = 1223 const val FOCUS_CLICK = 1224 const val TOGGLE_JS = 2000 const val TOGGLE_IMAGE = 2001 const val TOGGLE_COOKIE = 2002 const val TOGGLE_USERJS = 2200 const val TOGGLE_NAV_LOCK = 2300 const val PAGE_INFO = 5000 const val COPY_URL = 5001 const val COPY_TITLE = 5002 const val COPY_TITLE_URL = 5003 const val TAB_HISTORY = 5010 const val MOUSE_POINTER = 5015 const val FIND_ON_PAGE = 5020 const val SAVE_SCREENSHOT = 5030 const val SHARE_SCREENSHOT = 5031 const val SAVE_PAGE = 5035 const val OPEN_URL = 5200 const val TRANSLATE_PAGE = 5300 const val NEW_TAB = 10000 const val CLOSE_TAB = 10001 const val CLOSE_ALL = 10002 const val CLOSE_OTHERS = 10003 const val CLOSE_AUTO_SELECT = 10100 const val LEFT_TAB = 10005 const val RIGHT_TAB = 10006 const val SWAP_LEFT_TAB = 10007 const val SWAP_RIGHT_TAB = 10008 const val TAB_LIST = 10010 const val CLOSE_ALL_LEFT = 10015 const val CLOSE_ALL_RIGHT = 10016 const val RESTORE_TAB = 10020 const val REPLICATE_TAB = 10021 const val SHOW_SEARCHBOX = 35000 const val PASTE_SEARCHBOX = 35001 const val PASTE_GO = 35002 const val SHOW_BOOKMARK = 35010 const val SHOW_HISTORY = 35011 const val SHOW_DOWNLOADS = 35012 const val SHOW_SETTINGS = 35013 const val OPEN_SPEED_DIAL = 35014 const val ADD_BOOKMARK = 35020 const val ADD_SPEED_DIAL = 35021 const val ADD_PATTERN = 35022 const val ADD_TO_HOME = 35023 const val SUB_GESTURE = 35031 const val CLEAR_DATA = 35300 const val SHOW_PROXY_SETTING = 35301 const val ORIENTATION_SETTING = 35302 const val OPEN_LINK_SETTING = 35304 const val USERAGENT_SETTING = 35305 const val TEXTSIZE_SETTING = 35306 const val USERJS_SETTING = 35307 const val WEB_ENCODE_SETTING = 35308 const val DEFALUT_USERAGENT_SETTING = 35309 const val RENDER_ALL_SETTING = 35400 const val RENDER_SETTING = 35401 const val TOGGLE_VISIBLE_TAB = 38000 const val TOGGLE_VISIBLE_URL = 38001 const val TOGGLE_VISIBLE_PROGRESS = 38002 const val TOGGLE_VISIBLE_CUSTOM = 38003 const val TOGGLE_WEB_TITLEBAR = 38010 const val TOGGLE_WEB_GESTURE = 38100 const val TOGGLE_FLICK = 38101 const val TOGGLE_QUICK_CONTROL = 38102 const val TOGGLE_MULTI_FINGER_GESTURE = 38103 const val TOGGLE_AD_BLOCK = 38200 const val OPEN_BLACK_LIST = 38210 const val OPEN_WHITE_LIST = 38211 const val OPEN_WHITE_PATE_LIST = 38212 const val ADD_WHITE_LIST_PAGE = 38220 const val SHARE_WEB = 50000 const val OPEN_OTHER = 50001 const val START_ACTIVITY = 50005 const val TOGGLE_FULL_SCREEN = 50100 const val OPEN_OPTIONS_MENU = 50120 const val CUSTOM_MENU = 80000 const val FINISH = 90001 const val MINIMIZE = 90005 const val CUSTOM_ACTION = 100000 const val VIBRATION = 100100 const val TOAST = 100101 const val PRIVATE = 100110 const val VIEW_SOURCE = 101000 const val PRINT = 101010 const val TAB_PINNING = 101020 const val ALL_ACTION = 101030 const val READER_MODE = 101040 const val READ_IT_LATER = 101050 const val READ_IT_LATER_LIST = 101051 const val WEB_THEME = 101060 const val LPRESS_OPEN = -10 const val LPRESS_OPEN_NEW = -11 const val LPRESS_OPEN_BG = -12 const val LPRESS_OPEN_NEW_RIGHT = -13 const val LPRESS_OPEN_BG_RIGHT = -14 const val LPRESS_SHARE = -50 const val LPRESS_OPEN_OTHERS = -51 const val LPRESS_COPY_URL = -52 const val LPRESS_SAVE_PAGE_AS = -53 const val LPRESS_SAVE_PAGE = -54 const val LPRESS_OPEN_IMAGE = -110 const val LPRESS_OPEN_IMAGE_NEW = -111 const val LPRESS_OPEN_IMAGE_BG = -112 const val LPRESS_OPEN_IMAGE_NEW_RIGHT = -113 const val LPRESS_OPEN_IMAGE_BG_RIGHT = -114 const val LPRESS_SHARE_IMAGE_URL = -150 const val LPRESS_OPEN_IMAGE_OTHERS = -151 const val LPRESS_COPY_IMAGE_URL = -152 const val LPRESS_SAVE_IMAGE_AS = -153 const val LPRESS_GOOGLE_IMAGE_SEARCH = -154 const val LPRESS_IMAGE_RES_BLOCK = -155 const val LPRESS_PATTERN_MATCH = -156 const val LPRESS_COPY_LINK_TEXT = -157 const val LPRESS_SHARE_IMAGE = -158 const val LPRESS_SAVE_IMAGE = -159 const val LPRESS_ADD_BLACK_LIST = -160 const val LPRESS_ADD_IMAGE_BLACK_LIST = -161 const val LPRESS_ADD_WHITE_LIST = -162 const val LPRESS_ADD_IMAGE_WHITE_LIST = -163 @JvmStatic fun makeInstance(id: Int): SingleAction { try { return makeInstance(id, null) } catch (e: IOException) { ErrorReport.printAndWriteLog(e) } throw IllegalStateException() } @JvmField val CREATOR: Parcelable.Creator<SingleAction> = object : Parcelable.Creator<SingleAction> { override fun createFromParcel(source: Parcel): SingleAction { return SingleAction(source) } override fun newArray(size: Int): Array<SingleAction?> { return arrayOfNulls(size) } } @Throws(IOException::class) fun makeInstance(id: Int, parser: JsonReader?): SingleAction { return when (id) { GO_BACK -> GoBackSingleAction(id, parser) PAGE_SCROLL -> WebScrollSingleAction(id, parser) PAGE_AUTO_SCROLL -> AutoPageScrollAction(id, parser) MOUSE_POINTER -> MousePointerSingleAction(id, parser) FIND_ON_PAGE -> FindOnPageAction(id, parser) SAVE_SCREENSHOT -> SaveScreenshotSingleAction(id, parser) SHARE_SCREENSHOT -> ShareScreenshotSingleAction(id, parser) OPEN_URL -> OpenUrlSingleAction(id, parser) TRANSLATE_PAGE -> TranslatePageSingleAction(id, parser) CLOSE_TAB -> CloseTabSingleAction(id, parser) LEFT_TAB, RIGHT_TAB -> LeftRightTabSingleAction(id, parser) TAB_LIST -> TabListSingleAction(id, parser) SHOW_SEARCHBOX -> ShowSearchBoxAction(id, parser) PASTE_SEARCHBOX -> PasteSearchBoxAction(id, parser) PASTE_GO -> PasteGoSingleAction(id, parser) TOGGLE_AD_BLOCK, PRIVATE -> WithToastAction(id, parser) START_ACTIVITY -> StartActivitySingleAction(id, parser) OPEN_OPTIONS_MENU -> OpenOptionsMenuAction(id, parser) CUSTOM_MENU -> CustomMenuSingleAction(id, parser) FINISH -> FinishSingleAction(id, parser) CUSTOM_ACTION -> CustomSingleAction(id, parser) VIBRATION -> VibrationSingleAction(id, parser) TOAST -> ToastAction(id, parser) CLOSE_AUTO_SELECT -> CloseAutoSelectAction(id, parser) else -> SingleAction(id, parser) } } fun checkSubPreference(id: Int): Boolean { return when (id) { GO_BACK, PAGE_SCROLL, PAGE_AUTO_SCROLL, MOUSE_POINTER, FIND_ON_PAGE, SAVE_SCREENSHOT, SHARE_SCREENSHOT, OPEN_URL, TRANSLATE_PAGE, CLOSE_TAB, LEFT_TAB, RIGHT_TAB, TAB_LIST, SHOW_SEARCHBOX, PASTE_SEARCHBOX, PASTE_GO, TOGGLE_AD_BLOCK, START_ACTIVITY, OPEN_OPTIONS_MENU, CUSTOM_MENU, FINISH, CUSTOM_ACTION, VIBRATION, TOAST, PRIVATE, CLOSE_AUTO_SELECT -> true else -> false } } } }
apache-2.0
fccb79c48cc8fa34887412e2d3013385
36.392739
99
0.601412
4.265813
false
false
false
false
fuzhouch/qbranch
core/src/main/kotlin/net/dummydigit/qbranch/protocols/CompactBinaryReader.kt
1
5478
// Licensed under the MIT license. See LICENSE file in the project root // for full license information. package net.dummydigit.qbranch.protocols import net.dummydigit.qbranch.* import java.io.InputStream import java.nio.ByteBuffer import java.nio.charset.Charset import net.dummydigit.qbranch.exceptions.EndOfStreamException import net.dummydigit.qbranch.exceptions.UnsupportedVersionException import net.dummydigit.qbranch.utils.VariableLength import net.dummydigit.qbranch.utils.ZigZag /** * Reader to process CompactBinary protocols (v1 only) */ class CompactBinaryReader(inputStream : InputStream, version : Int, charset: Charset) : TaggedProtocolReader { private val input = inputStream private val defaultStringCharset = charset constructor(inputStream : InputStream) : this(inputStream, 1, Charsets.UTF_8) constructor(inputStream : InputStream, version : Int) : this(inputStream, version, Charsets.UTF_8) init { if (version != 1) { throw UnsupportedVersionException("protocol=CompactBinary:version=$version") } } override fun readBool() : Boolean = input.read() == 0 override fun readInt8() : Byte = input.read().toByte() override fun readUInt8() : UnsignedByte = UnsignedByte(input.read().toShort()) override fun readInt16() : Short = ZigZag.unsignedToSigned16(readUInt16()) override fun readUInt16(): UnsignedShort = VariableLength.decodeVarUInt16(input) override fun readUInt32(): UnsignedInt = VariableLength.decodeVarUInt32(input) override fun readInt32(): Int = ZigZag.unsignedToSigned32(readUInt32()) override fun readInt64(): Long = ZigZag.unsignedToSigned64(readUInt64()) override fun readUInt64(): UnsignedLong = VariableLength.decodeVarUInt64(input) override fun readByteString(): ByteString { val rawBytes = readRawStringBytes(1) ?: return ByteString("", defaultStringCharset) return ByteString(rawBytes, defaultStringCharset) } override fun readUTF16LEString(): String { // Following C#/Windows convention, we assume // we read UTF16 bytes. However, it may not be portable // on non-Windows platforms. val rawBytes = readRawStringBytes(2) ?: return "" return String(rawBytes, Charsets.UTF_16LE) } override fun readFloat(): Float { val floatAsBytes = ByteArray(4) val bytesRead = input.read(floatAsBytes) if (bytesRead != 4) { throw EndOfStreamException(4, bytesRead) } floatAsBytes.reverse() return ByteBuffer.wrap(floatAsBytes).float } override fun readDouble(): Double { val doubleAsBytes = ByteArray(8) val bytesRead = input.read(doubleAsBytes) if (bytesRead != 8) { throw EndOfStreamException(8, bytesRead) } doubleAsBytes.reverse() return ByteBuffer.wrap(doubleAsBytes).double } override fun readContainerHeader() : ContainerHeaderInfo { return CompactBinaryFieldInfo.decodeContainerHeaderV1(input) } override fun readKvpContainerHeader() : KvpContainerHeaderInfo { return CompactBinaryFieldInfo.decodeKvpContainerHeaderV1(input) } override fun skipField(dataType : BondDataType) { when (dataType) { BondDataType.BT_BOOL -> input.read() BondDataType.BT_UINT8 -> input.read() BondDataType.BT_UINT16 -> readUInt16() BondDataType.BT_UINT32 -> readUInt32() BondDataType.BT_UINT64 -> readUInt64() BondDataType.BT_FLOAT -> readFloat() BondDataType.BT_DOUBLE -> readDouble() BondDataType.BT_STRING -> readByteString() BondDataType.BT_INT8 -> input.read() BondDataType.BT_INT16 -> readInt16() BondDataType.BT_INT32 -> readInt32() BondDataType.BT_INT64 -> readInt64() BondDataType.BT_WSTRING -> readUTF16LEString() // TODO Implement container type in next version. BondDataType.BT_STRUCT -> skipStruct() BondDataType.BT_STOP_BASE -> {} BondDataType.BT_LIST -> skipContainer() BondDataType.BT_SET -> skipContainer() BondDataType.BT_MAP -> skipMap() else -> throw IllegalStateException("skip=$dataType") } } private fun skipMap() { val header = readKvpContainerHeader() for (i in 0 until header.kvpCount) { skipField(header.keyType) skipField(header.valueType) } } private fun skipContainer() { val header = readContainerHeader() for(i in 0 until header.elementCount) { skipField(header.elementType) } } private fun skipStruct() { var fieldInfo = parseNextField() while (fieldInfo.typeId != BondDataType.BT_STOP) { skipField(fieldInfo.typeId) fieldInfo = parseNextField() } } private fun readRawStringBytes(charLen : Int) : ByteArray? { val stringLength = readUInt32().value.toInt() if (stringLength == 0) { return null } val rawBytes = ByteArray(stringLength * charLen) val bytesRead = input.read(rawBytes) if (bytesRead != stringLength * charLen) { throw EndOfStreamException(stringLength * charLen, bytesRead) } return rawBytes } override fun parseNextField() = CompactBinaryFieldInfo(input) }
mit
2d2f7e80e81f1d4c300f891538644c86
37.314685
110
0.661555
4.519802
false
false
false
false
duftler/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ContinueParentStageHandlerTest.kt
1
9674
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.FAILED_CONTINUE import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.ext.beforeStages import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.CompleteStage import com.netflix.spinnaker.orca.q.ContinueParentStage import com.netflix.spinnaker.orca.q.StartTask import com.netflix.spinnaker.orca.q.buildAfterStages import com.netflix.spinnaker.orca.q.buildBeforeStages import com.netflix.spinnaker.orca.q.buildTasks import com.netflix.spinnaker.orca.q.stageWithParallelAfter import com.netflix.spinnaker.orca.q.stageWithSyntheticBefore import com.netflix.spinnaker.orca.q.stageWithSyntheticBeforeAndNoTasks import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyZeroInteractions import com.nhaarman.mockito_kotlin.whenever import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.api.lifecycle.CachingMode import org.jetbrains.spek.subject.SubjectSpek import java.time.Duration object ContinueParentStageHandlerTest : SubjectSpek<ContinueParentStageHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val retryDelay = Duration.ofSeconds(5) subject(CachingMode.GROUP) { ContinueParentStageHandler(queue, repository, retryDelay.toMillis()) } fun resetMocks() = reset(queue, repository) listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status -> describe("running a parent stage after its before stages complete with $status") { given("other before stages are not yet complete") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticBefore.type stageWithSyntheticBefore.buildBeforeStages(this) stageWithSyntheticBefore.buildTasks(this) } } val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE) beforeGroup { pipeline.stageByRef("1<1").status = status pipeline.stageByRef("1<2").status = RUNNING whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("re-queues the message for later evaluation") { verify(queue).push(message, retryDelay) } } given("another before stage failed") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticBefore.type stageWithSyntheticBefore.buildBeforeStages(this) stageWithSyntheticBefore.buildTasks(this) } } val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE) beforeGroup { pipeline.stageByRef("1<1").status = status pipeline.stageByRef("1<2").status = TERMINAL whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("does not re-queue the message") { verifyZeroInteractions(queue) } } given("the parent stage has tasks") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticBefore.type stageWithSyntheticBefore.buildBeforeStages(this) stageWithSyntheticBefore.buildTasks(this) } } val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE) beforeGroup { pipeline.stageByRef("1").beforeStages().forEach { it.status = status } } and("they have not started yet") { beforeGroup { whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("runs the parent stage's first task") { verify(queue).push(StartTask(pipeline.stageByRef("1"), "1")) } } and("they have already started") { beforeGroup { pipeline.stageByRef("1").tasks.first().status = RUNNING whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("ignores the message") { verifyZeroInteractions(queue) } } } given("the parent stage has no tasks") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticBeforeAndNoTasks.type stageWithSyntheticBeforeAndNoTasks.buildBeforeStages(this) stageWithSyntheticBeforeAndNoTasks.buildTasks(this) } } val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE) beforeGroup { pipeline.stageByRef("1").beforeStages().forEach { it.status = status } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("completes the stage with $status") { verify(queue).push(CompleteStage(pipeline.stageByRef("1"))) } } } } listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status -> describe("running a parent stage after its after stages complete with $status") { given("other after stages are not yet complete") { val pipeline = pipeline { stage { refId = "1" type = stageWithParallelAfter.type stageWithParallelAfter.buildTasks(this) stageWithParallelAfter.buildAfterStages(this) } } val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER) beforeGroup { pipeline.stageByRef("1>1").status = status pipeline.stageByRef("1>2").status = RUNNING whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("re-queues the message for later evaluation") { verify(queue).push(message, retryDelay) } } given("another after stage failed") { val pipeline = pipeline { stage { refId = "1" type = stageWithParallelAfter.type stageWithParallelAfter.buildTasks(this) stageWithParallelAfter.buildAfterStages(this) } } val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER) beforeGroup { pipeline.stageByRef("1>1").status = status pipeline.stageByRef("1>2").status = TERMINAL whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("tells the stage to complete") { verify(queue).push(CompleteStage(pipeline.stageByRef("1"))) } } given("all after stages completed") { val pipeline = pipeline { stage { refId = "1" type = stageWithParallelAfter.type stageWithParallelAfter.buildTasks(this) stageWithParallelAfter.buildAfterStages(this) } } val message = ContinueParentStage(pipeline.stageByRef("1"), STAGE_AFTER) beforeGroup { pipeline.stageByRef("1>1").status = status pipeline.stageByRef("1>2").status = SUCCEEDED whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("tells the stage to complete") { verify(queue).push(CompleteStage(pipeline.stageByRef("1"))) } } } } })
apache-2.0
6b2b554aa1d1523ab80f4510c7f50307
31.572391
86
0.651747
4.851555
false
false
false
false
googlecodelabs/android-compose-codelabs
AdaptiveUICodelab/app/src/main/java/com/example/reply/ui/ReplyHomeViewModel.kt
1
1838
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.reply.data.Email import com.example.reply.data.EmailsRepository import com.example.reply.data.EmailsRepositoryImpl import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch class ReplyHomeViewModel(private val emailsRepository: EmailsRepository = EmailsRepositoryImpl()): ViewModel() { // UI state exposed to the UI private val _uiState = MutableStateFlow(ReplyHomeUIState(loading = true)) val uiState: StateFlow<ReplyHomeUIState> = _uiState init { observeEmails() } private fun observeEmails() { viewModelScope.launch { emailsRepository.getAllEmails() .catch { ex -> _uiState.value = ReplyHomeUIState(error = ex.message) } .collect { emails -> _uiState.value = ReplyHomeUIState(emails = emails) } } } } data class ReplyHomeUIState( val emails : List<Email> = emptyList(), val loading: Boolean = false, val error: String? = null )
apache-2.0
51a45692c5689bf9dbb18f51b55c44cb
31.839286
112
0.700218
4.572139
false
false
false
false
Geobert/Efficio
app/src/main/kotlin/fr/geobert/efficio/widget/TaskListWidgetFactory.kt
1
2991
package fr.geobert.efficio.widget import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import android.os.Binder import android.util.Log import android.widget.RemoteViews import android.widget.RemoteViewsService import fr.geobert.efficio.R import fr.geobert.efficio.data.Task import fr.geobert.efficio.db.TaskTable import fr.geobert.efficio.db.WidgetTable import fr.geobert.efficio.extensions.map import java.util.* import kotlin.properties.Delegates class TaskListWidgetFactory(val ctx: Context, intent: Intent) : RemoteViewsService.RemoteViewsFactory { val TAG = "TaskListWidgetFactory" val widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) var tasksList: MutableList<Task> = LinkedList() var storeId: Long by Delegates.notNull() var opacity: Float by Delegates.notNull() var storeName: String by Delegates.notNull() override fun getLoadingView(): RemoteViews? { return null // todo a true loading view? } override fun getViewAt(position: Int): RemoteViews? { val t = tasksList[position] val rv = RemoteViews(ctx.packageName, R.layout.widget_task_row) rv.setTextViewText(R.id.name, t.item.name) rv.setTextViewText(R.id.qty_txt, t.qty.toString()) val intent = Intent() intent.putExtra("taskId", t.id) rv.setOnClickFillInIntent(R.id.task_btn, intent) return rv } override fun getViewTypeCount(): Int { return 1 } override fun onCreate() { } private fun fetchWidgetInfo(widgetId: Int): Boolean { val cursor = WidgetTable.getWidgetInfo(ctx, widgetId) if (cursor != null && cursor.count > 0 && cursor.moveToFirst()) { storeId = cursor.getLong(0) opacity = cursor.getFloat(1) storeName = cursor.getString(2) //Log.d(TAG, "fetchWidgetInfo: storeId:$storeId, opacity:$opacity") return true } Log.e(TAG, "fetchWidgetInfo: failed") return false } private fun fetchStoreTask(storeId: Long) { val token = Binder.clearCallingIdentity() try { val cursor = TaskTable.getAllNotDoneTasksForStore(ctx, storeId) if (cursor != null && cursor.count > 0) { tasksList = cursor.map(::Task) } else { tasksList = LinkedList() } cursor?.close() } finally { Binder.restoreCallingIdentity(token) } } override fun getItemId(position: Int): Long { return tasksList[position].id } override fun onDataSetChanged() { if (fetchWidgetInfo(widgetId)) fetchStoreTask(storeId) } override fun hasStableIds(): Boolean { return false } override fun getCount(): Int { return tasksList.count() } override fun onDestroy() { } }
gpl-2.0
de650d6b97a95712ff7ed853c563af63
28.623762
103
0.64995
4.424556
false
false
false
false
saru95/DSA
Kotlin/Dijkstra.kt
1
1657
class Dijkstra { // Dijkstra's algorithm to find shortest path from s to all other nodes fun dijkstra(G: WeightedGraph, s: Int): IntArray { val dist = IntArray(G.size()) // shortest known distance from "s" val pred = IntArray(G.size()) // preceeding node in path val visited = BooleanArray(G.size()) // all false initially for (i in dist.indices) { dist[i] = Integer.MAX_VALUE } dist[s] = 0 for (i in dist.indices) { val next = minVertex(dist, visited) visited[next] = true // The shortest path to next is dist[next] and via pred[next]. val n = G.neighbors(next) for (j in n.indices) { val v = n[j] val d = dist[next] + G.getWeight(next, v) if (dist[v] > d) { dist[v] = d pred[v] = next } } } return pred // (ignore pred[s]==0!) } private fun minVertex(dist: IntArray, v: BooleanArray): Int { var x = Integer.MAX_VALUE var y = -1 // graph not connected, or no unvisited vertices for (i in dist.indices) { if (!v[i] && dist[i] < x) { y = i x = dist[i] } } return y } fun printPath(G: WeightedGraph, pred: IntArray, s: Int, e: Int) { val path = java.util.ArrayList() var x = e while (x != s) { path.add(0, G.getLabel(x)) x = pred[x] } path.add(0, G.getLabel(s)) System.out.println(path) } }
mit
2064087062ef4b008c3cdfd8b828aa88
28.607143
75
0.475558
3.75737
false
true
false
false
agilie/SwipeToDelete
app/src/main/java/agilie/example/swipe2delete/kotlin/UsersActivity.kt
1
2393
package agilie.example.swipe2delete.kotlin import agilie.example.swipe2delete.prepareContactList import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.helper.ItemTouchHelper import android.view.Menu import android.view.MenuItem import android.widget.LinearLayout.VERTICAL import android.widget.Toast import kotlinx.android.synthetic.main.activity_java.* import kotlinx.android.synthetic.main.recycler_view.* import test.alexzander.swipetodelete.R import test.alexzander.swipetodelete.R.layout.activity_main class UsersActivity : android.support.v7.app.AppCompatActivity() { var adapter: UserAdapter? = null override fun onCreate(savedInstanceState: android.os.Bundle?) { super.onCreate(savedInstanceState) setContentView(activity_main) setSupportActionBar(toolbar) initRecyclerView() } fun initRecyclerView() { adapter = UserAdapter(prepareContactList(60)) { user -> Toast.makeText(this, user.toString(), Toast.LENGTH_SHORT).show() } adapter?.swipeToDeleteDelegate?.pending = true recyclerView.adapter = adapter val dividerItemDecoration = DividerItemDecoration(this, VERTICAL) recyclerView.addItemDecoration(dividerItemDecoration) val itemTouchHelper = ItemTouchHelper(adapter?.swipeToDeleteDelegate?.itemTouchCallBack) itemTouchHelper.attachToRecyclerView(recyclerView) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem?) = when (item?.itemId) { R.id.action_undo_animation -> { item.isChecked = !item.isChecked adapter?.animationEnabled = item.isChecked true } R.id.action_bottom_container -> { item.isChecked = !item.isChecked adapter?.bottomContainer = item.isChecked true } R.id.action_pending -> { item.isChecked = !item.isChecked adapter?.swipeToDeleteDelegate?.pending = item.isChecked true } else -> super.onOptionsItemSelected(item) } }
mit
261b1cd3f0a62dd27711a723bd0da0c6
35.257576
96
0.652319
5.037895
false
false
false
false
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/goods/types/Omelet.kt
1
2812
package cn.luo.yuan.maze.model.goods.types import cn.luo.yuan.maze.model.Parameter import cn.luo.yuan.maze.model.goods.BatchUseGoods import cn.luo.yuan.maze.model.goods.GoodsProperties import cn.luo.yuan.maze.model.goods.UsableGoods import cn.luo.yuan.maze.service.InfoControlInterface import cn.luo.yuan.maze.utils.Field /** * * Created by luoyuan on 2017/7/16. */ class Omelet() : UsableGoods(), BatchUseGoods { companion object { private const val serialVersionUID: Long = Field.SERVER_VERSION } override fun perform(properties: GoodsProperties): Boolean { val context = properties["context"] as InfoControlInterface val hero = properties.hero var count = properties[Parameter.COUNT] as Int var msg = "" while (getCount() >= count && count > 0) { count-=1 val index = context.random.nextInt(6) when (index) { 0 -> { hero.hp = (hero.maxHp * 0.6).toLong() msg += "使用煎蛋恢复了60%的生命值。" } 1 -> { hero.hp = hero.upperHp hero.pets.forEach { it.hp = it.maxHp } msg += "使用煎蛋恢复了全部的生命值并且复活了所有宠物。" } 2 -> { msg += "使用煎蛋恢复了复活了所有宠物。" hero.pets.forEach { it.hp = it.maxHp } } 3 -> { msg += "食用煎蛋肚子疼,导致生命值减少50%。" hero.hp -= (hero.upperHp * 0.5).toLong() } 4 -> { msg += "食用了一个黑乎乎的煎蛋,导致生命值变为1。" hero.hp = hero.hp - hero.currentHp + 1L } 5 -> { msg += "使用煎蛋后掉进了一个洞" if (context.random.nextInt(100) > 3) { msg += ",不知道怎么跑到最高层了" context.maze.level = context.maze.maxLevel } else { val level = context.random.nextLong(context.maze.maxLevel - 1000) msg += ",不知道怎么着就跑到" + level + "层了" context.maze.level = level } } } msg += "<br>" } context.showPopup(msg) return true } override var desc: String = "传说中的煎蛋。吃下去之后发生随机事件。" override var name: String = "煎蛋" override var price: Long = 9000L }
bsd-3-clause
9aa19d7ba5018d106f8074d97d18d8c2
33.22973
89
0.466825
3.669565
false
false
false
false
skydoves/WaterDrink
app/src/main/java/com/skydoves/waterdays/ui/fragments/main/DailyFragment.kt
1
6984
/* * Copyright (C) 2016 skydoves * * 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.skydoves.waterdays.ui.fragments.main import android.annotation.SuppressLint import android.content.Context import android.content.DialogInterface import android.content.res.Configuration import android.os.Bundle import android.text.InputType import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.skydoves.waterdays.R import com.skydoves.waterdays.WDApplication import com.skydoves.waterdays.consts.CapacityDrawable import com.skydoves.waterdays.events.rx.RxUpdateMainEvent import com.skydoves.waterdays.models.Drink import com.skydoves.waterdays.persistence.sqlite.SqliteManager import com.skydoves.waterdays.ui.adapters.DailyDrinkAdapter import com.skydoves.waterdays.ui.viewholders.DailyDrinkViewHolder import com.skydoves.waterdays.utils.DateUtils import io.reactivex.android.schedulers.AndroidSchedulers import kotlinx.android.synthetic.main.layout_dailyrecord.* import javax.inject.Inject /** * Created by skydoves on 2016-10-15. * Updated by skydoves on 2017-08-17. * Copyright (c) 2017 skydoves rights reserved. */ class DailyFragment : Fragment() { @Inject lateinit var sqliteManager: SqliteManager private var rootView: View? = null private val adapter: DailyDrinkAdapter by lazy { DailyDrinkAdapter(delegate) } private var dateCount = 0 override fun onAttach(context: Context) { WDApplication.component.inject(this) super.onAttach(context) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { this.rootView = inflater.inflate(R.layout.layout_dailyrecord, container, false) return rootView } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) initializeUI() } @SuppressLint("CheckResult") private fun initializeUI() { dailyrecord_listview.adapter = adapter addItems(DateUtils.getFarDay(0)) previous.setOnClickListener { dateMoveButton(it) } next.setOnClickListener { dateMoveButton(it) } RxUpdateMainEvent.getInstance().observable .observeOn(AndroidSchedulers.mainThread()) .subscribe { adapter.clear() addItems(DateUtils.getFarDay(0)) } } /** * daily drink viewHolder delegate */ private val delegate = object : DailyDrinkViewHolder.Delegate { override fun onClick(view: View, drink: Drink) { val alert = AlertDialog.Builder(context!!) alert.setTitle(getString(R.string.title_edit_capacity)) val input = EditText(context) input.inputType = InputType.TYPE_CLASS_NUMBER input.setRawInputType(Configuration.KEYBOARD_12KEY) alert.setView(input) alert.setPositiveButton(getString(R.string.yes)) { _: DialogInterface, _: Int -> try { val amount = Integer.parseInt(input.text.toString()) if (amount in 1..2999) { sqliteManager.updateRecordAmount(drink.index, amount) val drink_edited = Drink(drink.index, amount.toString() + "ml", drink.date, ContextCompat.getDrawable(context!!, CapacityDrawable.getLayout(amount))!!) val position = adapter.getPosition(drink) if (position != -1) { adapter.updateDrinkItem(position, drink_edited) RxUpdateMainEvent.getInstance().sendEvent() Toast.makeText(context, R.string.msg_edited_capacity, Toast.LENGTH_SHORT).show() } } else Toast.makeText(context, R.string.msg_invalid_input, Toast.LENGTH_SHORT).show() } catch (e: Exception) { e.printStackTrace() } } alert.setNegativeButton(getString(R.string.no)) { _: DialogInterface, _: Int -> } alert.show() val mgr = context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager mgr.showSoftInputFromInputMethod(input.applicationWindowToken, InputMethodManager.SHOW_FORCED) } override fun onConfirm(drink: Drink) { sqliteManager.deleteRecord(drink.index) adapter.remove(drink) RxUpdateMainEvent.getInstance().sendEvent() } } private fun dateMoveButton(v: View) { when (v.id) { R.id.previous -> { dateCount-- addItems(DateUtils.getFarDay(dateCount)) } R.id.next -> if (dateCount < 0) { dateCount++ addItems(DateUtils.getFarDay(dateCount)) } else Toast.makeText(context, "내일의 기록은 볼 수 없습니다.", Toast.LENGTH_SHORT).show() } } /** * add items * @param date now date value */ private fun addItems(date: String) { val tv_todayDate = rootView!!.findViewById(R.id.dailyrecord_tv_todaydate) as TextView tv_todayDate.text = date // append day of week Label if (dateCount == 0) { tv_todayDate.append(" (오늘)") } else { val dayOfWeek = DateUtils.getDayofWeek(date, DateUtils.dateFormat) tv_todayDate.append(DateUtils.getIndexofDayNameHead(dayOfWeek)) } // clear adapter.clear() // add items val cursor = sqliteManager.readableDatabase.rawQuery("select * from RecordList where recorddate >= datetime(date('$date','localtime')) and recorddate < datetime(date('$date', 'localtime', '+1 day'))", null) if (cursor != null && cursor.count > 0 && cursor.moveToLast()) { do { val drinkAmount = cursor.getInt(2) val mainicon: Int val datetime = cursor.getString(1).split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() mainicon = CapacityDrawable.getLayout(drinkAmount) // add listItem val drink = Drink(cursor.getInt(0), Integer.toString(drinkAmount) + "ml", datetime[0] + ":" + datetime[1], ContextCompat.getDrawable(context!!, mainicon)!!) adapter.addDrinkItem(drink) } while (cursor.moveToPrevious()) cursor.close() } // if no cursor exist val tv_message = rootView!!.findViewById(R.id.dailyrecord_tv_message) as TextView if (cursor!!.count == 0) tv_message.visibility = View.VISIBLE else tv_message.visibility = View.INVISIBLE } }
apache-2.0
db1411e978afe0bb071b18b424355592
35.041451
210
0.706153
4.190361
false
false
false
false
lttng/lttng-scope
javeltrace/src/main/kotlin/com/efficios/jabberwocky/javeltrace/XYChartExample.kt
2
2002
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ @file:JvmName("XYChartExample") package com.efficios.jabberwocky.javeltrace import com.efficios.jabberwocky.analysis.eventstats.EventStatsXYChartProvider import com.efficios.jabberwocky.common.TimeRange import com.efficios.jabberwocky.ctf.trace.CtfTrace import com.efficios.jabberwocky.project.TraceProject import com.efficios.jabberwocky.views.xychart.view.json.XYChartJsonOutput import java.nio.file.Files import java.nio.file.Paths /** * Example of a standalone program generating the JSON for the Threads * timegraph model for a given trace and time range. */ fun main(args: Array<String>) { /* Parse the command-line parameters */ if (args.size < 2) { printUsage() return } val tracePath = args[0] val nbPoints = args[1].toIntOrNull() if (nbPoints == null) { printUsage() return } /* Create the trace project */ val projectPath = Files.createTempDirectory("project") val trace = CtfTrace(Paths.get(tracePath)) val project = TraceProject.ofSingleTrace("MyProject", projectPath, trace) val range = TimeRange.of(project.startTime, project.endTime) /* Query for a XY chart render for the whole trace */ val provider = EventStatsXYChartProvider() provider.traceProject = project val renders = provider.generateSeriesRenders(range, nbPoints, null) XYChartJsonOutput.printRenderTo(System.out, renders) /* Cleanup */ projectPath.toFile().deleteRecursively() } private fun printUsage() { System.err.println("Cannot parse command-line arguments.") System.err.println("Usage: java -jar <jarname>.jar [TRACE PATH] [NB OF DATA POINTS]") }
epl-1.0
42c6e9aa30a032caf455771820e07415
31.306452
89
0.731768
4.102459
false
false
false
false
ysl3000/PathfindergoalAPI
Pathfinder_1_15/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_15_R1/pathfinding/CraftPathfinderManager.kt
1
1159
package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_15_R1.pathfinding import com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_15_R1.entity.CraftInsentient import com.github.ysl3000.bukkit.pathfinding.entity.Insentient import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderManagerMob import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderPlayer import org.bukkit.entity.* class CraftPathfinderManager : PathfinderManagerMob { override fun getPathfinderGoalEntity(creature: Creature): Insentient = CraftInsentient(creature) override fun getPathfinderGoalEntity(mob: Mob): Insentient = CraftInsentient(mob) override fun getPathfinderGoalEntity(flying: Flying): Insentient = CraftInsentient(flying) override fun getPathfinderGoalEntity(ambient: Ambient): Insentient = CraftInsentient(ambient) override fun getPathfinderGoalEntity(slime: Slime): Insentient = CraftInsentient(slime) override fun getPathfinderGoalEntity(enderDragon: EnderDragon): Insentient = CraftInsentient(enderDragon) override fun getPathfinderPlayer(player: Player): PathfinderPlayer = CraftPathfinderPlayer(player) }
mit
fff420498f09bb4ed15a8d33456b1d70
47.333333
109
0.830889
4.406844
false
false
false
false
DadosAbertosBrasil/android-radar-politico
app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/controllers/MainActivity.kt
1
2063
package br.edu.ifce.engcomp.francis.radarpolitico.controllers import android.content.res.ColorStateList import android.os.Bundle import android.support.v4.app.FragmentTabHost import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.View import android.widget.TabWidget import android.widget.TextView import br.edu.ifce.engcomp.francis.radarpolitico.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initToolbar() initTabHost() } private fun initToolbar() { val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) } private fun initTabHost() { val mainTabHost = findViewById(R.id.main_tabHost) as FragmentTabHost mainTabHost.setup(this, supportFragmentManager, android.R.id.tabcontent) val votacoesTab = mainTabHost.newTabSpec("votacoes") val politicosTab = mainTabHost.newTabSpec("politicos") votacoesTab.setIndicator("VOTAÇÕES") politicosTab.setIndicator("POLÍTICOS") mainTabHost.addTab(votacoesTab, VotacoesTabFragment::class.java, null) mainTabHost.addTab(politicosTab, DeputadosSeguidosTabFragment::class.java, null) mainTabHost.currentTab = 0 stylizeTabs(mainTabHost) } private fun stylizeTabs(tabHost: FragmentTabHost) { val tabTextColors: ColorStateList val tabWidget: TabWidget var tabTextView: TextView var tabView: View val tabAmount: Int tabWidget = tabHost.tabWidget tabTextColors = this.resources.getColorStateList(R.color.tab_text_selector) tabAmount = tabWidget.tabCount for (i in 0..tabAmount - 1) { tabView = tabWidget.getChildTabViewAt(i) tabTextView = tabView.findViewById(android.R.id.title) as TextView tabTextView.setTextColor(tabTextColors) } } }
gpl-2.0
1bbb5e26d2d07e29368e8405d3f3594d
31.1875
88
0.712136
4.291667
false
false
false
false
Ekito/koin
koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/article/ArticleScreen.kt
1
8636
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetnews.ui.article import android.content.Context import android.content.Intent import androidx.compose.foundation.Icon import androidx.compose.foundation.Text import androidx.compose.foundation.contentColor import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.preferredHeight import androidx.compose.material.AlertDialog import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Surface import androidx.compose.material.TextButton import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material.icons.filled.Share import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.savedinstancestate.savedInstanceState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.ContextAmbient import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.dp import androidx.ui.tooling.preview.Preview import com.example.jetnews.R import com.example.jetnews.data.Result import com.example.jetnews.data.posts.PostsRepository import com.example.jetnews.data.posts.impl.BlockingFakePostsRepository import com.example.jetnews.data.posts.impl.post3 import com.example.jetnews.model.Post import com.example.jetnews.ui.ThemedPreview import com.example.jetnews.ui.home.BookmarkButton import com.example.jetnews.utils.launchUiStateProducer import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking /** * Stateful Article Screen that manages state using [launchUiStateProducer] * * @param postId (state) the post to show * @param postsRepository data source for this screen * @param onBack (event) request back navigation */ @Suppress("DEPRECATION") // allow ViewModelLifecycleScope call @Composable fun ArticleScreen( postId: String, postsRepository: PostsRepository, onBack: () -> Unit ) { val (post) = launchUiStateProducer(postsRepository, postId) { getPost(postId) } // TODO: handle errors when the repository is capable of creating them val postData = post.value.data ?: return // [collectAsState] will automatically collect a Flow<T> and return a State<T> object that // updates whenever the Flow emits a value. Collection is cancelled when [collectAsState] is // removed from the composition tree. val favorites by postsRepository.observeFavorites().collectAsState(setOf()) val isFavorite = favorites.contains(postId) // Returns a [CoroutineScope] that is scoped to the lifecycle of [ArticleScreen]. When this // screen is removed from composition, the scope will be cancelled. val coroutineScope = rememberCoroutineScope() ArticleScreen( post = postData, onBack = onBack, isFavorite = isFavorite, onToggleFavorite = { coroutineScope.launch { postsRepository.toggleFavorite(postId) } } ) } /** * Stateless Article Screen that displays a single post. * * @param post (state) item to display * @param onBack (event) request navigate back * @param isFavorite (state) is this item currently a favorite * @param onToggleFavorite (event) request that this post toggle it's favorite state */ @Composable fun ArticleScreen( post: Post, onBack: () -> Unit, isFavorite: Boolean, onToggleFavorite: () -> Unit ) { var showDialog by savedInstanceState { false } if (showDialog) { FunctionalityNotAvailablePopup { showDialog = false } } Scaffold( topBar = { TopAppBar( title = { Text( text = "Published in: ${post.publication?.name}", style = MaterialTheme.typography.subtitle2, color = contentColor() ) }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.Filled.ArrowBack) } } ) }, bodyContent = { innerPadding -> val modifier = Modifier.padding(innerPadding) PostContent(post, modifier) }, bottomBar = { BottomBar( post = post, onUnimplementedAction = { showDialog = true }, isFavorite = isFavorite, onToggleFavorite = onToggleFavorite ) } ) } /** * Bottom bar for Article screen * * @param post (state) used in share sheet to share the post * @param onUnimplementedAction (event) called when the user performs an unimplemented action * @param isFavorite (state) if this post is currently a favorite * @param onToggleFavorite (event) request this post toggle it's favorite status */ @Composable private fun BottomBar( post: Post, onUnimplementedAction: () -> Unit, isFavorite: Boolean, onToggleFavorite: () -> Unit ) { Surface(elevation = 2.dp) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .preferredHeight(56.dp) .fillMaxWidth() ) { IconButton(onClick = onUnimplementedAction) { Icon(Icons.Filled.FavoriteBorder) } BookmarkButton( isBookmarked = isFavorite, onClick = onToggleFavorite ) val context = ContextAmbient.current IconButton(onClick = { sharePost(post, context) }) { Icon(Icons.Filled.Share) } Spacer(modifier = Modifier.weight(1f)) IconButton(onClick = onUnimplementedAction) { Icon(vectorResource(R.drawable.ic_text_settings)) } } } } /** * Display a popup explaining functionality not available. * * @param onDismiss (event) request the popup be dismissed */ @Composable private fun FunctionalityNotAvailablePopup(onDismiss: () -> Unit) { AlertDialog( onDismissRequest = onDismiss, text = { Text( text = "Functionality not available \uD83D\uDE48", style = MaterialTheme.typography.body2 ) }, confirmButton = { TextButton(onClick = onDismiss) { Text(text = "CLOSE") } } ) } /** * Show a share sheet for a post * * @param post to share * @param context Android context to show the share sheet in */ private fun sharePost(post: Post, context: Context) { val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TITLE, post.title) putExtra(Intent.EXTRA_TEXT, post.url) } context.startActivity(Intent.createChooser(intent, "Share post")) } @Preview("Article screen") @Composable fun PreviewArticle() { ThemedPreview { val post = loadFakePost(post3.id) ArticleScreen(post, {}, false, {}) } } @Preview("Article screen dark theme") @Composable fun PreviewArticleDark() { ThemedPreview(darkTheme = true) { val post = loadFakePost(post3.id) ArticleScreen(post, {}, false, {}) } } @Composable private fun loadFakePost(postId: String): Post { val context = ContextAmbient.current val post = runBlocking { (BlockingFakePostsRepository(context).getPost(postId) as Result.Success).data } return post }
apache-2.0
bf15a233c7b3d9996b17017849925123
32.088123
96
0.679597
4.650512
false
false
false
false
zensum/franz
src/main/kotlin/engine/kafka_one/JobStatuses.kt
1
2518
package franz.engine.kafka_one import franz.JobStatus import org.apache.kafka.clients.consumer.ConsumerRecord import org.apache.kafka.clients.consumer.OffsetAndMetadata import org.apache.kafka.common.TopicPartition import java.lang.IllegalStateException private fun <K, V> Map<K, V>.getOrFail(k: K): V = get(k) ?: throw IllegalStateException("Got null when trying to access value for key $k in map ${this.keys}") private fun findCommittableOffsets(x: Map<JobId, JobStatus>) = x .toList() .groupBy { it.first.first } .map { (_, values) -> values.sortedBy { (key, _) -> key.second } .takeWhile { (_, status) -> status.isDone() } .lastOrNull()?.first } .filterNotNull() .toMap() .mapValues { (_, v) -> OffsetAndMetadata(v + 1) } data class JobStatuses<T, U>( private val jobStatuses: Map<JobId, JobStatus> = emptyMap<JobId, JobStatus>(), private val records: Map<JobId, ConsumerRecord<T, U>> = emptyMap() ) { fun update(updates: Map<JobId, JobStatus>) = copy(jobStatuses = jobStatuses + updates) fun committableOffsets() = findCommittableOffsets(jobStatuses) fun removeCommitted(committed: Map<TopicPartition, OffsetAndMetadata>) = if (committed.isEmpty()) this else copy( jobStatuses = jobStatuses.filterKeys { (topicPartition, offset) -> val committedOffset = committed[topicPartition]?.offset() ?: -1 offset >= committedOffset }, records = records.filterValues { val committedOffset = committed[it.topicPartition()]?.offset() ?: -1 it.offset() >= committedOffset } ) fun stateCounts() = jobStatuses.values.map { it::class.java.name!! }.groupBy { it }.mapValues { it.value.count() } private fun changeBatch(jobs: Iterable<JobId>, status: JobStatus) = update(jobs.map { it to status }.toMap()) fun addJobs(jobs: Iterable<ConsumerRecord<T, U>>) = changeBatch(jobs.map { it.jobId() }, JobStatus.Incomplete) .copy(records = records + jobs.map { it.jobId() to it }) fun rescheduleTransientFailures(): Pair<JobStatuses<T, U>, List<ConsumerRecord<T, U>>> = jobStatuses .filterValues { it.mayRetry() } .keys.let { jobIds: Set<JobId> -> changeBatch(jobIds, JobStatus.Retry) to jobIds.map(records::getOrFail) } }
mit
899e8dcab1f09ad270d0b58ca8d74190
46.509434
118
0.615568
4.196667
false
false
false
false
mrebollob/LoteriadeNavidad
androidApp/src/main/java/com/mrebollob/loteria/android/presentation/platform/ui/components/LotterySnackbarHost.kt
1
1151
package com.mrebollob.loteria.android.presentation.platform.ui.components import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.Snackbar import androidx.compose.material.SnackbarData import androidx.compose.material.SnackbarHost import androidx.compose.material.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.google.accompanist.insets.systemBarsPadding import com.mrebollob.loteria.android.presentation.platform.ui.theme.Grey7 @Composable fun LotterySnackbarHost( hostState: SnackbarHostState, modifier: Modifier = Modifier, snackbar: @Composable (SnackbarData) -> Unit = { Snackbar( backgroundColor = Grey7, snackbarData = it ) } ) { SnackbarHost( hostState = hostState, modifier = modifier .systemBarsPadding() .wrapContentWidth(align = Alignment.Start) .widthIn(max = 550.dp), snackbar = snackbar ) }
apache-2.0
68cd934d862b66a83019941c57ae9a40
31.885714
73
0.74457
4.56746
false
false
false
false
notion/Plumb
compiler/src/test/kotlin/rxjoin/internal/codegen/validator/InValidatorTest.kt
2
3440
package rxjoin.internal.codegen.validator import org.assertj.core.api.Assertions import org.junit.Before import org.junit.Test import org.mockito.Mockito.any import org.mockito.Mockito.mock import javax.lang.model.element.ElementKind.FIELD import javax.lang.model.element.ElementKind.METHOD import javax.lang.model.type.DeclaredType import javax.lang.model.type.TypeKind.DECLARED import javax.lang.model.type.TypeMirror import org.mockito.Mockito.`when` as mockWhen class InValidatorTest : ValidatorTest() { private val mockObservableDeclaredType = mock(DeclaredType::class.java) private val mockStringType = mock(TypeMirror::class.java) private val mockBehaviorSubjectDeclaredType = mock(DeclaredType::class.java) private val mockBehaviorSubjectTypeMirror = mock(TypeMirror::class.java) @Before override fun setUp() { super.setUp() mockWhen(mockBehaviorSubjectTypeMirror.kind).thenReturn(DECLARED) mockWhen(mockBehaviorSubjectTypeMirror.toString()).thenReturn("rx.subjects.BehaviorSubject") mockWhen(mockBehaviorSubjectDeclaredType.enclosingType).thenReturn( mockBehaviorSubjectTypeMirror) mockWhen(mockBehaviorSubjectDeclaredType.typeArguments).thenReturn( mutableListOf(mockStringType)) mockWhen(mockBehaviorSubjectDeclaredType.kind).thenReturn(DECLARED) mockWhen(mockObservableDeclaredType.typeArguments).thenReturn( mutableListOf(mockStringType, mockStringType)) mockWhen(mockObservableDeclaredType.kind).thenReturn(DECLARED) } @Test fun test_Field_isValid() { mockWhen(mockedTypes.isAssignable(any(), any())).thenReturn(true) val field = makeMockedInElement(FIELD, mockBehaviorSubjectDeclaredType, "foo") val model = getJoinerModelWithEntryIds(arrayOf("foo")) Assertions.assertThat(InValidator.validate(field, getMockedModelWithJoinerModels(model))) .isTrue() } @Test fun testMethod_isInvalid() { val field = makeMockedInElement(METHOD, mockBehaviorSubjectDeclaredType, "foo") val model = getJoinerModelWithEntryIds(arrayOf("foo")) Assertions.assertThatThrownBy { InValidator.validate(field, getMockedModelWithJoinerModels(model)) } .isInstanceOf(Exception::class.java) .hasMessage(InValidator.elementNotFieldError(field)) } @Test fun test_Observable_isInvalid() { val field = makeMockedInElement(FIELD, mockObservableDeclaredType, "foo") val model = getJoinerModelWithEntryIds(arrayOf("bar")) Assertions.assertThatThrownBy { InValidator.validate(field, getMockedModelWithJoinerModels(model)) } .isInstanceOf(Exception::class.java) .hasMessage(InValidator.fieldNotSubjectError(field)) } @Test fun test_inValue_withNoMatchingJoiner_isInvalid() { mockWhen(mockedTypes.isAssignable(any(), any())).thenReturn(true) val field = makeMockedInElement(FIELD, mockBehaviorSubjectDeclaredType, "foo") val model = getJoinerModelWithEntryIds(arrayOf("bar")) Assertions.assertThatThrownBy { InValidator.validate(field, getMockedModelWithJoinerModels(model)) } .isInstanceOf(Exception::class.java) .hasMessage(InValidator.noCorrespondingRegistryError(field)) } }
apache-2.0
7be67e7508c4a7ef68abaf4c01ecd025
39.470588
100
0.719767
4.858757
false
true
false
false
mazine/infer-hierarchy-type-parameter
src/main/kotlin/org/jetbrains/mazine/infer/type/parameter/InferHierarchyType.kt
1
2847
package org.jetbrains.mazine.infer.type.parameter import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.lang.reflect.TypeVariable /** * Calculates types in `inheritedClass` that relate to type parameters of the `baseClass`. */ fun <B, T : B> inferTypeParameters(baseClass: Class<B>, inheritedClass: Class<T>): Map<TypeVariable<*>, Type> { val hierarchy = generateSequence<Class<*>>(inheritedClass) { it.superclass } val initialMapping = hierarchy.first() .typeParameters .map { it to it }.toMap<TypeVariable<*>, Type>() return hierarchy .takeWhile { it != baseClass } .fold(initialMapping) { mapping, type -> val parameters = type.superclass.typeParameters val arguments = (type.genericSuperclass as? ParameterizedType)?.actualTypeArguments if (parameters.isNotEmpty() && arguments != null) { (parameters zip arguments).map { (parameter, argument) -> parameter to if (argument is TypeVariable<*> && argument in mapping.keys) { mapping[argument]!! } else { argument } }.toMap() } else { emptyMap() } } } /** * Calculates type argument in `inheritedClass` that relates to a type parameter of the `baseClass` named `typeVariableName`. */ fun <B, T : B> inferTypeParameter(baseClass: Class<B>, typeVariableName: String, inheritedClass: Class<T>): Type { val typeVariable = (baseClass.typeParameters.firstOrNull { it.name == typeVariableName } ?: throw IllegalArgumentException("Class ${baseClass.name} has no type parameter $typeVariableName")) return inferTypeParameters(baseClass, inheritedClass)[typeVariable]!! } /** * Calculates type argument in `inheritedClass` that relates to a type parameter of the `baseClass` named `typeVariableName` * and expects it to be an instance of `java.util.Class<V>`. */ fun <B, T : B, V : Any> inferTypeParameterClass(baseClass: Class<B>, typeVariableName: String, inheritedClass: Class<T>): Class<V> { val typeParameter = inferTypeParameter(baseClass, typeVariableName, inheritedClass) val clazz = when (typeParameter) { is Class<*> -> typeParameter is ParameterizedType -> typeParameter.rawType as? Class<*> else -> null } @Suppress("UNCHECKED_CAST") return ((clazz as? Class<V>) ?: throw IllegalArgumentException("Cannot infer class for type parameter \"$typeVariableName\" of " + "${baseClass.canonicalName}<${baseClass.typeParameters.joinToString { it.name }}> " + "for ${inheritedClass.canonicalName}")) }
apache-2.0
b180456cbcc06387fb618a5feaddc228
44.206349
132
0.630488
4.951304
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/hazelcast/serializers/DataExpirationStreamSerializer.kt
1
2075
package com.openlattice.hazelcast.serializers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer import com.openlattice.data.DataExpiration import com.openlattice.data.DeleteType import com.openlattice.edm.set.ExpirationBase import com.openlattice.hazelcast.StreamSerializerTypeIds import org.springframework.stereotype.Component @Component class DataExpirationStreamSerializer : SelfRegisteringStreamSerializer<DataExpiration> { companion object { private val expirationTypes = ExpirationBase.values() private val deleteTypes = DeleteType.values() @JvmStatic fun serialize(out: ObjectDataOutput, obj: DataExpiration) { out.writeLong(obj.timeToExpiration) out.writeInt(obj.expirationBase.ordinal) out.writeInt(obj.deleteType.ordinal) OptionalStreamSerializers.serialize(out, obj.startDateProperty, UUIDStreamSerializerUtils::serialize) } @JvmStatic fun deserialize(input: ObjectDataInput): DataExpiration { val timeToExpiration = input.readLong() val expirationType = expirationTypes[input.readInt()] val deleteType = deleteTypes[input.readInt()] val startDateProperty = OptionalStreamSerializers.deserialize(input, UUIDStreamSerializerUtils::deserialize) return DataExpiration(timeToExpiration, expirationType, deleteType, startDateProperty) } } override fun getTypeId(): Int { return StreamSerializerTypeIds.DATA_EXPIRATION.ordinal } override fun destroy() {} override fun getClazz(): Class<out DataExpiration> { return DataExpiration::class.java } override fun write(out: ObjectDataOutput, obj: DataExpiration) { serialize(out, obj) } override fun read(input: ObjectDataInput): DataExpiration { return deserialize(input) } }
gpl-3.0
ce28b8ab311c53ca9a97833787edadf6
36.071429
120
0.740723
5.320513
false
false
false
false
JanYoStudio/WhatAnime
app/src/main/java/pw/janyo/whatanime/base/BaseComposeActivity.kt
1
4981
package pw.janyo.whatanime.base import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.StringRes import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.google.accompanist.systemuicontroller.rememberSystemUiController import org.koin.core.component.KoinComponent import pw.janyo.whatanime.R import pw.janyo.whatanime.ui.theme.WhatAnimeTheme import pw.janyo.whatanime.ui.theme.isDarkMode import kotlin.reflect.KClass abstract class BaseComposeActivity : ComponentActivity(), KoinComponent { private var toast: Toast? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initIntent() setContent { BuildContentWindow() } } open fun initIntent() {} @Composable open fun BuildContentWindow() { WhatAnimeTheme { // Remember a SystemUiController val systemUiController = rememberSystemUiController() val systemBarColor = MaterialTheme.colorScheme.background val useDarkIcons = !isDarkMode() DisposableEffect(systemUiController, useDarkIcons) { systemUiController.setSystemBarsColor( color = systemBarColor, darkIcons = useDarkIcons ) onDispose {} } BuildContent() } } @Composable open fun BuildContent() { } fun <T : Activity> intentTo( clazz: KClass<T>, block: Intent.() -> Unit = {}, ) { startActivity(Intent(this, clazz.java).apply(block)) } fun String.toast(showLong: Boolean = false) = newToast( this@BaseComposeActivity, this, if (showLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT ) protected fun String.notBlankToast(showLong: Boolean = false) { if (this.isNotBlank()) { newToast( this@BaseComposeActivity, this, if (showLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT ) } } fun @receiver:StringRes Int.toast(showLong: Boolean = false) = asString().toast(showLong) private fun newToast(context: Context, message: String?, length: Int) { toast?.cancel() toast = Toast.makeText(context, message, length) toast?.show() } fun @receiver:StringRes Int.asString(): String = getString(this) @Composable protected fun ShowProgressDialog( show: Boolean, text: String, fontSize: TextUnit = TextUnit.Unspecified, ) { val compositionLoading by rememberLottieComposition( LottieCompositionSpec.RawRes(R.raw.animation_loading) ) if (!show) { return } Dialog( onDismissRequest = { }, DialogProperties( dismissOnBackPress = false, dismissOnClickOutside = false, ) ) { Card( shape = RoundedCornerShape(16.dp), ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(32.dp), ) { LottieAnimation( composition = compositionLoading, iterations = LottieConstants.IterateForever, modifier = Modifier.size(196.dp) ) Spacer(modifier = Modifier.height(16.dp)) Text( text = text, fontSize = fontSize, color = MaterialTheme.colorScheme.onBackground ) } } } } }
apache-2.0
fca107d9fceadbbd211d7c6705b901cc
31.562092
75
0.635816
5.051724
false
false
false
false
openhab/openhab.android
mobile/src/full/java/org/openhab/habdroid/core/FcmMessageListenerService.kt
1
2907
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.core import android.util.Log import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import kotlinx.coroutines.runBlocking import org.openhab.habdroid.model.CloudNotification import org.openhab.habdroid.model.toOH2IconResource class FcmMessageListenerService : FirebaseMessagingService() { private lateinit var notifHelper: NotificationHelper override fun onCreate() { Log.d(TAG, "onCreate()") super.onCreate() notifHelper = NotificationHelper(this) } override fun onNewToken(token: String) { Log.d(TAG, "onNewToken()") super.onNewToken(token) FcmRegistrationWorker.scheduleRegistration(this) } override fun onMessageReceived(message: RemoteMessage) { val data = message.data Log.d(TAG, "onMessageReceived with data $data") val messageType = data["type"] ?: return val notificationId = data["notificationId"]?.toInt() ?: 1 when (messageType) { "notification" -> { val cloudNotification = CloudNotification( data["persistedId"].orEmpty(), data["message"].orEmpty(), // Older versions of openhab-cloud didn't send the notification generation // timestamp, so use the (undocumented) google.sent_time as a time reference // in that case. If that also isn't present, don't show time at all. data["timestamp"]?.toLong() ?: message.sentTime, data["icon"].toOH2IconResource(), data["severity"] ) runBlocking { val context = this@FcmMessageListenerService notifHelper.showNotification( notificationId, cloudNotification, FcmRegistrationWorker.createHideNotificationIntent(context, notificationId), FcmRegistrationWorker.createHideNotificationIntent( context, NotificationHelper.SUMMARY_NOTIFICATION_ID ) ) } } "hideNotification" -> { notifHelper.cancelNotification(notificationId) } } } companion object { private val TAG = FcmMessageListenerService::class.java.simpleName } }
epl-1.0
603812fd345a36ace2e3d5e4ffe83450
35.797468
100
0.607843
5.275862
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/crossing_island/AddCrossingIsland.kt
1
2431
package de.westnordost.streetcomplete.quests.crossing_island import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.mapdata.Element import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BLIND import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN import de.westnordost.streetcomplete.ktx.toYesNo import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment class AddCrossingIsland : OsmElementQuestType<Boolean> { private val crossingFilter by lazy { """ nodes with highway = crossing and foot != no and crossing and crossing != island and !crossing:island """.toElementFilterExpression()} private val excludedWaysFilter by lazy { """ ways with highway and access ~ private|no or railway or highway = service or highway and oneway and oneway != no """.toElementFilterExpression()} override val commitMessage = "Add whether pedestrian crossing has an island" override val wikiLink = "Key:crossing:island" override val icon = R.drawable.ic_quest_pedestrian_crossing_island override val questTypeAchievements = listOf(PEDESTRIAN, BLIND) override fun getTitle(tags: Map<String, String>) = R.string.quest_pedestrian_crossing_island override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> { val excludedWayNodeIds = mutableSetOf<Long>() mapData.ways .filter { excludedWaysFilter.matches(it) } .flatMapTo(excludedWayNodeIds) { it.nodeIds } return mapData.nodes .filter { crossingFilter.matches(it) && it.id !in excludedWayNodeIds } } override fun isApplicableTo(element: Element): Boolean? = if (!crossingFilter.matches(element)) false else null override fun createForm() = YesNoQuestAnswerFragment() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { changes.add("crossing:island", answer.toYesNo()) } }
gpl-3.0
096a85e1236c2098bb56a2fb836829bc
40.20339
96
0.74167
4.90121
false
false
false
false
CarrotCodes/Pellet
server/src/test/kotlin/dev/pellet/server/codec/mime/MediaTypeParserTests.kt
1
2950
package dev.pellet.server.codec.mime import dev.pellet.assertFailureIs import dev.pellet.assertSuccess import dev.pellet.server.codec.ParseException import kotlin.test.Test class MediaTypeParserTests { @Test fun `empty media type fails`() { val testCase = "" val result = MediaTypeParser.parse(testCase) assertFailureIs<ParseException>(result) } @Test fun `simple media type`() { val testCase = "text/plain" val result = MediaTypeParser.parse(testCase) val expected = MediaType( type = "text", subtype = "plain", parameters = listOf() ) assertSuccess(expected, result) } @Test fun `simple media type with parameter`() { val testCase = "application/json; charset=utf-8" val result = MediaTypeParser.parse(testCase) val expected = MediaType( type = "application", subtype = "json", parameters = listOf( "charset" to "utf-8" ) ) assertSuccess(expected, result) } @Test fun `optional whitespace doesn't affect output`() { val testCase = "application/json ; charset=utf-8; something=else" val result = MediaTypeParser.parse(testCase) val expected = MediaType( type = "application", subtype = "json", parameters = listOf( "charset" to "utf-8", "something" to "else" ) ) assertSuccess(expected, result) } @Test fun `quotation marks for parameter value`() { val testCase = "application/json; charset=\"utf-8\"" val result = MediaTypeParser.parse(testCase) val expected = MediaType( type = "application", subtype = "json", parameters = listOf( "charset" to "utf-8", ) ) assertSuccess(expected, result) } @Test fun `mismatched quotation marks for parameter value are preserved`() { val testCase = "application/json; charset=\"utf-8" val result = MediaTypeParser.parse(testCase) val expected = MediaType( type = "application", subtype = "json", parameters = listOf( "charset" to "\"utf-8", ) ) assertSuccess(expected, result) } @Test fun `invalid media types`() { val testCases = listOf( " ", "text/plain/something", "text plain;", "text/plain;;;", "text/plain;==", "text/plain;a=", "text/", "/plain", ";", ";/", "/;", ) testCases.forEach { testCase -> val result = MediaTypeParser.parse(testCase) assertFailureIs<ParseException>(result) } } }
apache-2.0
1f575e90ad6cb61230d20e673e32d7bc
26.830189
77
0.527119
4.71246
false
true
false
false
strykeforce/thirdcoast
src/main/kotlin/org/strykeforce/trapper/ActionCommand.kt
1
699
package org.strykeforce.trapper import edu.wpi.first.wpilibj2.command.CommandBase abstract class ActionCommand @JvmOverloads constructor( var action: Action = Action(), val trapperSubsystem: TrapperSubsystem ) : CommandBase() { constructor(name: String, trapperSubsystem: TrapperSubsystem) : this( Action(name), trapperSubsystem ) init { addRequirements(trapperSubsystem) } val traces = mutableListOf<Trace>() abstract val trace: Trace override fun execute() = if (trapperSubsystem.enabled) traces += trace else Unit fun postWith(session: OkHttpSession) = if (trapperSubsystem.enabled) session.post(traces) else Unit }
mit
be3d5200c72eb41561af67d9c5187830
24
84
0.709585
4.040462
false
false
false
false
JotraN/shows-to-watch-android
app/src/main/java/io/josephtran/showstowatch/shows/ShowsPresenter.kt
1
3120
package io.josephtran.showstowatch.shows import android.content.Context import android.util.Log import io.josephtran.showstowatch.api.STWClientWrapper import io.josephtran.showstowatch.api.STWShow import rx.Subscriber import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers class ShowsPresenter(context: Context, val view: ShowsView) { private val client = STWClientWrapper(context) companion object { val ALL_SHOWS = "All" val IN_PROGRESS_SHOWS = "In Progress" val ABANDONED_SHOWS = "Abandoned" val COMPLETED_SHOWS = "Completed" val SHOWS_TYPES = arrayOf(ALL_SHOWS, IN_PROGRESS_SHOWS, ABANDONED_SHOWS, COMPLETED_SHOWS) fun getShowsType(typeIndex: Int): String { if (typeIndex > SHOWS_TYPES.size || typeIndex < 0) return "" return SHOWS_TYPES.get(typeIndex) } fun getShowsTypesNum(): Int = SHOWS_TYPES.size fun getTypeIndex(showsType: String) = SHOWS_TYPES.indexOf(showsType) } fun downloadShows(index: Int) { val showsType = getShowsType(index) when (showsType) { ALL_SHOWS -> downloadAllShows() IN_PROGRESS_SHOWS -> downloadInProgressShows() ABANDONED_SHOWS -> downloadAbandonedShows() COMPLETED_SHOWS -> downloadCompletedShows() else -> downloadAllShows() } } private fun downloadAllShows() { view.showProgress(true) client.getShows() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(STWShowsSubscriber(view)) } private fun downloadInProgressShows() { view.showProgress(true) client.getInProgressShows() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(STWShowsSubscriber(view)) } private fun downloadAbandonedShows() { view.showProgress(true) client.getAbandonedShows() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(STWShowsSubscriber(view)) } private fun downloadCompletedShows() { view.showProgress(true) client.getCompletedShows() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(STWShowsSubscriber(view)) } class STWShowsSubscriber(val view: ShowsView) : Subscriber<List<STWShow>>() { private val errorMessage = "Error downloading shows." override fun onNext(shows: List<STWShow>?) { if (shows == null) view.showError(errorMessage) else view.addShows(shows.sortedByDescending(STWShow::updatedAt)) } override fun onCompleted() { view.showProgress(false) } override fun onError(e: Throwable?) { view.showProgress(false) view.showError(errorMessage) Log.e(javaClass.name, errorMessage, e) } } }
mit
0752fe8791b201c3af9367f8f6209026
32.55914
97
0.629167
4.489209
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/entity/vanilla/PigEntityProtocol.kt
1
1440
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.entity.vanilla import org.lanternpowered.api.data.Keys import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.key.minecraftKey import org.lanternpowered.server.entity.LanternEntity import org.lanternpowered.server.network.entity.parameter.ParameterList class PigEntityProtocol<E : LanternEntity>(entity: E) : AnimalEntityProtocol<E>(entity) { companion object { private val TYPE = minecraftKey("pig") } private var lastSaddled = false override val mobType: NamespacedKey get() = TYPE override fun spawn(parameterList: ParameterList) { super.spawn(parameterList) parameterList.add(EntityParameters.Pig.HAS_SADDLE, this.entity.get(Keys.IS_SADDLED).orElse(false)) } override fun update(parameterList: ParameterList) { super.update(parameterList) val saddled = this.entity.get(Keys.IS_SADDLED).orElse(false) if (this.lastSaddled != saddled) { parameterList.add(EntityParameters.Pig.HAS_SADDLE, saddled) this.lastSaddled = saddled } } }
mit
42840db70f72a5df4d8839091a1c56ce
33.285714
106
0.722222
3.84
false
false
false
false
sabi0/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/ide/scripting.kt
2
5161
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.plugins.groovy.ide import com.intellij.execution.ExecutionManager import com.intellij.execution.console.* import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.execution.ui.RunContentDescriptor import com.intellij.execution.ui.actions.CloseAction import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.runReadAction import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import groovy.lang.Binding import groovy.lang.GroovySystem import org.codehaus.groovy.tools.shell.Interpreter import org.jetbrains.plugins.groovy.GroovyLanguage import java.awt.BorderLayout import java.io.PrintWriter import java.io.StringWriter import java.text.SimpleDateFormat import java.util.* import javax.swing.JPanel class GroovyScriptingShellAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return initConsole(project) } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = ApplicationManager.getApplication().isInternal } } object MyConsoleRootType : ConsoleRootType("groovy.scripting.shell", null) private val TITLE = "Groovy IDE Scripting Shell" private val defaultImports = listOf( "com.intellij.openapi.application.*", "com.intellij.openapi.project.*", "com.intellij.openapi.module.*", "com.intellij.openapi.vfs.*", "com.intellij.psi.*", "com.intellij.psi.search.*", "com.intellij.psi.stubs.*", "com.intellij.util.indexing.*" ) private val defaultImportStatements = defaultImports.map { "import $it" } private fun initConsole(project: Project) { val console = LanguageConsoleImpl(project, TITLE, GroovyLanguage) val action = ConsoleExecuteAction(console, createExecuteHandler(project)) action.registerCustomShortcutSet(action.shortcutSet, console.consoleEditor.component) ConsoleHistoryController(MyConsoleRootType, null, console).install() val consoleComponent = console.component val toolbarActions = DefaultActionGroup() val toolbar = ActionManager.getInstance().createActionToolbar("GroovyScriptingConsole", toolbarActions, false) toolbar.setTargetComponent(consoleComponent) val panel = JPanel(BorderLayout()) panel.add(consoleComponent, BorderLayout.CENTER) panel.add(toolbar.component, BorderLayout.WEST) val descriptor = object : RunContentDescriptor(console, null, panel, TITLE) { override fun isContentReuseProhibited() = true } toolbarActions.addAll(*console.createConsoleActions()) val executor = DefaultRunExecutor.getRunExecutorInstance() toolbarActions.add(CloseAction(executor, descriptor, project)) ExecutionManager.getInstance(project).contentManager.showRunContent(executor, descriptor) val appInfo = ApplicationInfo.getInstance() val namesInfo = ApplicationNamesInfo.getInstance() val buildDate = SimpleDateFormat("dd MMM yy HH:ss", Locale.US).format(appInfo.buildDate.time) console.print( "Welcome!\n${namesInfo.fullProductName} (build #${appInfo.build}, $buildDate); Groovy: ${GroovySystem.getVersion()}\n", ConsoleViewContentType.SYSTEM_OUTPUT ) console.print( "'application', 'project', 'facade' and 'allScope' variables are available at the top level. \n", ConsoleViewContentType.SYSTEM_OUTPUT ) console.print( "Default imports:\n${defaultImports.joinToString(separator = ",\n") { "\t$it" }}\n\n", ConsoleViewContentType.SYSTEM_OUTPUT ) } private fun createExecuteHandler(project: Project) = object : BaseConsoleExecuteActionHandler(false) { val interpreter: Interpreter by lazy { val binding = Binding(mapOf( "application" to ApplicationManager.getApplication(), "project" to project, "facade" to JavaPsiFacade.getInstance(project), "allScope" to GlobalSearchScope.allScope(project) )) Interpreter(Interpreter::class.java.classLoader, binding) } override fun execute(text: String, console: LanguageConsoleView) { ApplicationManager.getApplication().executeOnPooledThread { runReadAction { try { val result: Any? = interpreter.evaluate(defaultImportStatements + "" + "" + text) console.print("Returned: ", ConsoleViewContentType.SYSTEM_OUTPUT) console.print("$result\n", ConsoleViewContentType.NORMAL_OUTPUT) } catch (e: Throwable) { val errors = StringWriter() e.printStackTrace(PrintWriter(errors)) console.print("Error: $errors", ConsoleViewContentType.ERROR_OUTPUT) } } } } }
apache-2.0
bcf67e6bae91ef85079a800fe427247c
37.514925
140
0.770393
4.595726
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/movies/SyncUpdatedMovies.kt
1
3500
/* * Copyright (C) 2015 Simon Vig Therkildsen * * 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 net.simonvt.cathode.actions.movies import android.content.ContentProviderOperation import android.content.ContentValues import android.content.Context import android.text.format.DateUtils import androidx.work.WorkManager import net.simonvt.cathode.actions.PagedAction import net.simonvt.cathode.actions.PagedResponse import net.simonvt.cathode.api.entity.UpdatedItem import net.simonvt.cathode.api.service.MoviesService import net.simonvt.cathode.api.util.TimeUtils import net.simonvt.cathode.provider.DatabaseContract.MovieColumns import net.simonvt.cathode.provider.ProviderSchematic.Movies import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.MovieDatabaseHelper import net.simonvt.cathode.settings.Timestamps import net.simonvt.cathode.work.enqueueUniqueNow import net.simonvt.cathode.work.movies.SyncPendingMoviesWorker import retrofit2.Call import javax.inject.Inject class SyncUpdatedMovies @Inject constructor( private val context: Context, private val workManager: WorkManager, private val moviesService: MoviesService, private val movieHelper: MovieDatabaseHelper ) : PagedAction<Unit, UpdatedItem>() { private val currentTime = System.currentTimeMillis() override fun key(params: Unit): String = "SyncUpdatedMovies" override fun getCall(params: Unit, page: Int): Call<List<UpdatedItem>> { val lastUpdated = Timestamps.get(context).getLong(Timestamps.MOVIES_LAST_UPDATED, currentTime) val millis = lastUpdated - 12 * DateUtils.HOUR_IN_MILLIS val updatedSince = TimeUtils.getIsoTime(millis) return moviesService.updated(updatedSince, page, LIMIT) } override suspend fun handleResponse( params: Unit, pagedResponse: PagedResponse<Unit, UpdatedItem> ) { val ops = arrayListOf<ContentProviderOperation>() var page: PagedResponse<Unit, UpdatedItem>? = pagedResponse do { for (item in page!!.response) { val updatedAt = item.updated_at.timeInMillis val movie = item.movie!! val traktId = movie.ids.trakt!! val movieId = movieHelper.getId(traktId) if (movieId != -1L) { if (movieHelper.isUpdated(traktId, updatedAt)) { val values = ContentValues() values.put(MovieColumns.NEEDS_SYNC, true) ops.add( ContentProviderOperation.newUpdate(Movies.withId(movieId)) .withValues(values) .build() ) } } } page = page.nextPage() } while (page != null) context.contentResolver.batch(ops) } override fun onDone() { workManager.enqueueUniqueNow(SyncPendingMoviesWorker.TAG, SyncPendingMoviesWorker::class.java) Timestamps.get(context) .edit() .putLong(Timestamps.MOVIES_LAST_UPDATED, currentTime) .apply() } companion object { private const val LIMIT = 100 } }
apache-2.0
76d5b1f85a6ec23587e0bf1d26ab623c
33.653465
98
0.732286
4.305043
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/MainActivity.kt
1
8914
/***************************************************************************** * MainActivity.java * * Copyright © 2011-2019 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.gui import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Activity import android.content.Intent import android.os.Build import android.os.Bundle import android.util.TypedValue import android.view.KeyEvent import android.view.MenuItem import android.view.View import androidx.appcompat.view.ActionMode import androidx.fragment.app.Fragment import kotlinx.android.synthetic.main.toolbar.* import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.libvlc.util.AndroidUtil import org.videolan.medialibrary.interfaces.Medialibrary import org.videolan.resources.* import org.videolan.tools.* import org.videolan.vlc.BuildConfig import org.videolan.vlc.R import org.videolan.vlc.StartActivity import org.videolan.vlc.extensions.ExtensionManagerService import org.videolan.vlc.extensions.ExtensionsManager import org.videolan.vlc.gui.audio.AudioBrowserFragment import org.videolan.vlc.gui.browser.BaseBrowserFragment import org.videolan.vlc.gui.browser.ExtensionBrowser import org.videolan.vlc.gui.helpers.INavigator import org.videolan.vlc.gui.helpers.Navigator import org.videolan.vlc.gui.helpers.UiTools import org.videolan.vlc.gui.video.VideoGridFragment import org.videolan.vlc.interfaces.Filterable import org.videolan.vlc.interfaces.IRefreshable import org.videolan.vlc.media.MediaUtils import org.videolan.vlc.reloadLibrary import org.videolan.vlc.util.Permissions import org.videolan.vlc.util.Util private const val TAG = "VLC/MainActivity" @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi class MainActivity : ContentActivity(), ExtensionManagerService.ExtensionManagerActivity, INavigator by Navigator() { var refreshing: Boolean = false set(value) { mainLoading.visibility = if (value) View.VISIBLE else View.GONE field = value } private lateinit var mediaLibrary: Medialibrary private var scanNeeded = false @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Util.checkCpuCompatibility(this) /*** Start initializing the UI */ setContentView(R.layout.main) initAudioPlayerContainerActivity() setupNavigation(savedInstanceState) if (savedInstanceState == null) Permissions.checkReadStoragePermission(this) /* Set up the action bar */ prepareActionBar() /* Reload the latest preferences */ scanNeeded = savedInstanceState == null && settings.getBoolean(KEY_MEDIALIBRARY_AUTO_RESCAN, true) if (BuildConfig.DEBUG) extensionsManager = ExtensionsManager.getInstance() mediaLibrary = Medialibrary.getInstance() val color = TypedValue().run { theme.resolveAttribute(R.attr.progress_indeterminate_tint, this, true) data } mainLoadingProgress.indeterminateDrawable.setColorFilter(color, android.graphics.PorterDuff.Mode.SRC_IN) } private fun prepareActionBar() { supportActionBar?.run { setDisplayHomeAsUpEnabled(false) setHomeButtonEnabled(false) setDisplayShowTitleEnabled(!AndroidDevices.isPhone) } } override fun onStart() { super.onStart() if (mediaLibrary.isInitiated) { /* Load media items from database and storage */ if (scanNeeded && Permissions.canReadStorage(this)) this.reloadLibrary() } } override fun onStop() { super.onStop() if (changingConfigurations == 0) { /* Check for an ongoing scan that needs to be resumed during onResume */ scanNeeded = mediaLibrary.isWorking } } override fun onSaveInstanceState(outState: Bundle) { val current = currentFragment if (current !is ExtensionBrowser) supportFragmentManager.putFragment(outState, "current_fragment", current!!) outState.putInt(EXTRA_TARGET, currentFragmentId) super.onSaveInstanceState(outState) } override fun onRestart() { super.onRestart() /* Reload the latest preferences */ reloadPreferences() } @TargetApi(Build.VERSION_CODES.N) override fun onBackPressed() { /* Close playlist search if open or Slide down the audio player if it is shown entirely. */ if (isAudioPlayerReady && (audioPlayer.backPressed() || slideDownAudioPlayer())) return // If it's the directory view, a "backpressed" action shows a parent. val fragment = currentFragment if (fragment is BaseBrowserFragment && fragment.goBack()) { return } else if (fragment is ExtensionBrowser) { fragment.goBack() return } if (AndroidUtil.isNougatOrLater && isInMultiWindowMode) { UiTools.confirmExit(this) return } finish() } override fun startSupportActionMode(callback: ActionMode.Callback): ActionMode? { appBarLayout.setExpanded(true) return super.startSupportActionMode(callback) } /** * Handle onClick form menu buttons */ override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId != R.id.ml_menu_filter) UiTools.setKeyboardVisibility(appBarLayout, false) // Handle item selection return when (item.itemId) { // Refresh R.id.ml_menu_refresh -> { forceRefresh() true } android.R.id.home -> // Slide down the audio player or toggle the sidebar slideDownAudioPlayer() else -> super.onOptionsItemSelected(item) } } override fun onMenuItemActionExpand(item: MenuItem): Boolean { return if (currentFragment is Filterable) { (currentFragment as Filterable).allowedToExpand() } else false } fun forceRefresh() { forceRefresh(currentFragment) } private fun forceRefresh(current: Fragment?) { if (!mediaLibrary.isWorking) { if (current != null && current is IRefreshable) (current as IRefreshable).refresh() else reloadLibrary() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == ACTIVITY_RESULT_PREFERENCES) { when (resultCode) { RESULT_RESCAN -> this.reloadLibrary() RESULT_RESTART, RESULT_RESTART_APP -> { val intent = Intent(this@MainActivity, if (resultCode == RESULT_RESTART_APP) StartActivity::class.java else MainActivity::class.java) finish() startActivity(intent) } RESULT_UPDATE_SEEN_MEDIA -> for (fragment in supportFragmentManager.fragments) if (fragment is VideoGridFragment) fragment.updateSeenMediaMarker() RESULT_UPDATE_ARTISTS -> { val fragment = currentFragment if (fragment is AudioBrowserFragment) fragment.viewModel.refresh() } } } else if (requestCode == ACTIVITY_RESULT_OPEN && resultCode == Activity.RESULT_OK) { MediaUtils.openUri(this, data!!.data) } else if (requestCode == ACTIVITY_RESULT_SECONDARY) { if (resultCode == RESULT_RESCAN) { forceRefresh(currentFragment) } } } // Note. onKeyDown will not occur while moving within a list override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_SEARCH) { toolbar.menu.findItem(R.id.ml_menu_filter).expandActionView() } return super.onKeyDown(keyCode, event) } }
gpl-2.0
8ed5c0e22dfa41790b06ffdb61f3c664
36.1375
153
0.664984
4.993277
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/map/overlay/FadeOverlay.kt
1
1351
/* Copyright 2015 Andreas Würl 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.blitzortung.android.map.overlay import android.graphics.Canvas import android.graphics.Paint import com.google.android.maps.MapView import com.google.android.maps.Overlay import org.blitzortung.android.map.overlay.color.ColorHandler class FadeOverlay(private val colorHandler: ColorHandler) : Overlay() { private var alphaValue = 0 override fun draw(canvas: Canvas?, mapView: MapView?, shadow: Boolean) { if (!shadow) { val rect = canvas!!.clipBounds val paint = Paint() paint.color = colorHandler.backgroundColor paint.alpha = alphaValue canvas.drawRect(rect, paint) } } fun setAlpha(alphaValue: Int) { this.alphaValue = alphaValue } }
apache-2.0
b8d27558ac5dde16c47aded090989a66
29.681818
76
0.707407
4.5
false
false
false
false
JDA-Applications/Kotlin-JDA
src/main/kotlin/club/minnced/kjda/KJDAClientBuilder.kt
1
4628
/* * Copyright 2016 - 2017 Florian Spieß * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("KJDAClientBuilder") package club.minnced.kjda import com.neovisionaries.ws.client.WebSocketFactory import net.dv8tion.jda.core.AccountType import net.dv8tion.jda.core.JDA import net.dv8tion.jda.core.JDABuilder import net.dv8tion.jda.core.OnlineStatus import net.dv8tion.jda.core.audio.factory.IAudioSendFactory import net.dv8tion.jda.core.entities.Game import net.dv8tion.jda.core.hooks.IEventManager import okhttp3.OkHttpClient /** * Constructs a new [JDABuilder] and applies the specified * init function `() -> Unit` to that receiver. * This uses [JDABuilder.buildAsync] * * The token is not required here, however needs to be configured in the given function! * * @param[accountType] * The [AccountType] for the account being issued for creation * @param[init] * The function which uses the constructed JDABuilder as receiver to setup * the JDA information before building it * * @sample client * * @see JDABuilder */ fun client(accountType: AccountType, init: JDABuilder.() -> Unit): JDA { val builder = JDABuilder(accountType) builder.init() return builder.buildAsync() } /** Lazy infix overload for [JDABuilder.setToken] */ infix inline fun <reified T: JDABuilder> T.token(lazyToken: () -> String): T = this.setToken(lazyToken()) as T /** Lazy infix overload for [JDABuilder.setGame] */ infix inline fun <reified T: JDABuilder> T.game(lazy: () -> String): T = this.setGame(Game.of(lazy())) as T /** Lazy infix overload for [JDABuilder.setStatus] */ infix inline fun <reified T: JDABuilder> T.status(lazy: () -> OnlineStatus): T = this.setStatus(lazy()) as T /** Lazy infix overload for [JDABuilder.setEventManager] */ infix inline fun <reified T: JDABuilder> T.manager(lazy: () -> IEventManager): T = this.setEventManager(lazy()) as T /** Lazy infix overload for [JDABuilder.addEventListener] */ infix inline fun <reified T: JDABuilder> T.listener(lazy: () -> Any): T = this.addEventListener(lazy()) as T /** Lazy infix overload for [JDABuilder.setAudioSendFactory] */ infix inline fun <reified T: JDABuilder> T.audioSendFactory(lazy: () -> IAudioSendFactory): T = this.setAudioSendFactory(lazy()) as T /** Infix overload for [JDABuilder.setIdle] */ infix inline fun <reified T: JDABuilder> T.idle(lazy: Boolean): T = this.setIdle(lazy) as T /** Infix overload for [JDABuilder.setEnableShutdownHook] */ infix inline fun <reified T: JDABuilder> T.shutdownHook(lazy: Boolean): T = this.setEnableShutdownHook(lazy) as T /** Infix overload for [JDABuilder.setAudioEnabled] */ infix inline fun <reified T: JDABuilder> T.audio(lazy: Boolean): T = this.setAudioEnabled(lazy) as T /** Infix overload for [JDABuilder.setAutoReconnect] */ infix inline fun <reified T: JDABuilder> T.autoReconnect(lazy: Boolean): T = this.setAutoReconnect(lazy) as T /** * Provides new WebSocketFactory and calls the provided lazy * initializer to allow setting options like timeouts */ infix inline fun <reified T: JDABuilder> T.websocketSettings(init: WebSocketFactory.() -> Unit): T { val factory = WebSocketFactory() factory.init() setWebsocketFactory(factory) return this } /** * Provides new OkHttpClient.Builder and calls the provided lazy * initializer to allow setting options like timeouts */ infix inline fun <reified T: JDABuilder> T.httpSettings(init: OkHttpClient.Builder.() -> Unit): T { val builder = OkHttpClient.Builder() builder.init() setHttpClientBuilder(builder) return this } /** Overload for [JDABuilder.addEventListener] */ inline fun <reified T: JDABuilder> T.listener(vararg listener: Any): T = this.addEventListener(*listener) as T /** Overload for [JDABuilder.removeEventListener] */ inline fun <reified T: JDABuilder> T.removeListener(vararg listener: Any): T = this.removeEventListener(*listener) as T /** Operator overload for [JDABuilder.addEventListener] */ inline operator fun <reified T: JDABuilder> T.plusAssign(other: Any) { listener(other) }
apache-2.0
f3a62aac1abae65cb3afb68dc8740b0d
39.234783
100
0.731359
3.839834
false
false
false
false
adrcotfas/Goodtime
app/src/main/java/com/apps/adrcotfas/goodtime/statistics/SessionViewModel.kt
1
2755
/* * Copyright 2016-2019 Adrian Cotfas * * 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.apps.adrcotfas.goodtime.statistics import com.apps.adrcotfas.goodtime.database.SessionDao import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.apps.adrcotfas.goodtime.database.AppDatabase import com.apps.adrcotfas.goodtime.database.Session import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.time.LocalDate import java.time.ZoneId import javax.inject.Inject @HiltViewModel class SessionViewModel @Inject constructor( database: AppDatabase ) : ViewModel() { private val dao: SessionDao = database.sessionModel() val allSessions: LiveData<List<Session>> get() = dao.allSessions val allSessionsUnlabeled: LiveData<List<Session>> get() = dao.allSessionsUnlabeled val allSessionsUnarchived: LiveData<List<Session>> get() = dao.allSessionsUnarchived fun getAllSessionsUnarchived(startMillis: Long, endMillis: Long): LiveData<List<Session>> = dao.getAllSessionsUnarchived(startMillis, endMillis) fun getSession(id: Long): LiveData<Session> { return dao.getSession(id) } fun addSession(session: Session) { viewModelScope.launch(Dispatchers.IO) { dao.addSession(session) } } fun editSession(session: Session) { viewModelScope.launch(Dispatchers.IO) { dao.editSession( session.id, session.timestamp, session.duration, session.label ) } } fun editLabel(id: Long?, label: String?) { viewModelScope.launch(Dispatchers.IO) { dao.editLabel( id!!, label ) } } fun deleteSession(id: Long) { viewModelScope.launch(Dispatchers.IO) { dao.deleteSession(id) } } fun deleteSessionsFinishedAfter(timestamp: Long) { viewModelScope.launch(Dispatchers.IO) { dao.deleteSessionsAfter(timestamp) } } fun getSessions(label: String): LiveData<List<Session>> { return dao.getSessions(label) } }
apache-2.0
a5f4187fbc65190c5c23d4d60be71ee5
30.318182
128
0.69873
4.42926
false
false
false
false
ofalvai/BPInfo
app/src/main/java/com/ofalvai/bpinfo/api/bkkfutar/RouteContract.kt
1
1019
/* * Copyright 2018 Olivér Falvai * * 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.ofalvai.bpinfo.api.bkkfutar internal interface RouteContract { companion object { const val ROUTE_ID = "id" const val ROUTE_SHORT_NAME = "shortName" const val ROUTE_LONG_NAME = "longName" const val ROUTE_DESC = "description" const val ROUTE_TYPE = "type" const val ROUTE_COLOR = "color" const val ROUTE_TEXT_COLOR = "textColor" } }
apache-2.0
fa4a730cd36da44ac1f1a5074b79f0cf
26.540541
75
0.687623
3.961089
false
false
false
false
goodwinnk/intellij-community
platform/platform-impl/src/com/intellij/internal/heatmap/actions/ShowHeatMapAction.kt
1
22686
// 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.heatmap.actions import com.intellij.internal.heatmap.fus.* import com.intellij.internal.heatmap.settings.ClickMapSettingsDialog import com.intellij.internal.statistic.beans.ConvertUsagesUtil import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionMenu import com.intellij.openapi.actionSystem.impl.ActionMenuItem import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.openapi.wm.impl.IdeFrameImpl import com.intellij.ui.JBColor import com.intellij.ui.PopupMenuListenerAdapter import com.intellij.util.PlatformUtils import com.intellij.util.ui.UIUtil import java.awt.Color import java.awt.Graphics import java.awt.Graphics2D import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.io.IOException import java.text.DecimalFormat import java.text.SimpleDateFormat import java.util.* import javax.swing.JComponent import javax.swing.MenuSelectionManager import javax.swing.event.PopupMenuEvent private val BUTTON_EMPTY_STATS_COLOR: Color = JBColor.GRAY.brighter() val LOG = Logger.getInstance(ShowHeatMapAction::class.java) class ShowHeatMapAction : AnAction(), DumbAware { companion object MetricsCache { private val toolbarsAllMetrics = mutableListOf<MetricEntity>() private val mainMenuAllMetrics = mutableListOf<MetricEntity>() private val toolbarsMetrics = hashMapOf<String, List<MetricEntity>>() private val mainMenuMetrics = hashMapOf<String, List<MetricEntity>>() private val toolbarsTotalMetricsUsers = hashMapOf<String, Int>() private val mainMenuTotalMetricsUsers = hashMapOf<String, Int>() //settings private var myEndStartDate: Pair<Date, Date>? = null private var myShareType: ShareType? = null private var myServiceUrl: String? = null private val myBuilds = mutableListOf<String>() private var myIncludeEap = false private var myColor = Color.RED private val ourIdeBuildInfos = mutableListOf<ProductBuildInfo>() fun getOurIdeBuildInfos(): List<ProductBuildInfo> = ourIdeBuildInfos fun getSelectedServiceUrl(): String = (myServiceUrl ?: DEFAULT_SERVICE_URLS.first()).trimEnd('/') } @Volatile private var myToolBarProgress = false @Volatile private var myMainMenuProgress = false private val ourBlackList = HashMap<String, String>() private val PRODUCT_CODE = getProductCode() init { ourBlackList["com.intellij.ide.ReopenProjectAction"] = "Reopen Project" } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isInProgress().not() super.update(e) } private fun isInProgress(): Boolean = myToolBarProgress || myMainMenuProgress override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return if (ourIdeBuildInfos.isEmpty()) ourIdeBuildInfos.addAll(getProductBuildInfos(PRODUCT_CODE)) askSettingsAndPaintUI(project) } private fun askSettingsAndPaintUI(project: Project) { val frame = WindowManagerEx.getInstance().getIdeFrame(project) if (frame == null) return val askSettings = ClickMapSettingsDialog(project) val ok = askSettings.showAndGet() if (ok.not()) return val serviceUrl = askSettings.getServiceUrl() if (serviceUrl == null) { showWarnNotification("Statistics fetch failed", "Statistic Service url is not specified", project) return } val startEndDate = askSettings.getStartEndDate() val shareType = askSettings.getShareType() val ideBuilds = askSettings.getBuilds() val isIncludeEap = askSettings.getIncludeEap() if (settingsChanged(startEndDate, shareType, serviceUrl, ideBuilds, isIncludeEap)) { clearCache() } myServiceUrl = serviceUrl myBuilds.clear() myBuilds.addAll(ideBuilds) myEndStartDate = startEndDate myIncludeEap = isIncludeEap myShareType = shareType myColor = askSettings.getColor() if (toolbarsAllMetrics.isNotEmpty()) { paintVisibleToolBars(project, frame.component, shareType, toolbarsAllMetrics) } else { val accessToken = askSettings.getAccessToken() if (StringUtil.isEmpty(accessToken)) { showWarnNotification("Statistics fetch failed", "access token is not specified", project) return } val startDate = getDateString(startEndDate.first) val endDate = getDateString(startEndDate.second) ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Fetching statistics for toolbar clicks", false) { override fun run(indicator: ProgressIndicator) { myToolBarProgress = true val toolBarAllStats = fetchStatistics(startDate, endDate, PRODUCT_CODE, myBuilds, arrayListOf(TOOLBAR_GROUP), accessToken!!) LOG.debug("\nGot Tool bar clicks stat: ${toolBarAllStats.size} rows:") toolBarAllStats.forEach { LOG.debug("Entity: $it") } if (toolBarAllStats.isNotEmpty()) toolbarsAllMetrics.addAll(toolBarAllStats) paintVisibleToolBars(project, frame.component, shareType, toolBarAllStats) myToolBarProgress = false } }) } if (frame is IdeFrameImpl) { if (mainMenuAllMetrics.isNotEmpty()) { groupStatsByMenus(frame, mainMenuAllMetrics) addMenusPopupListener(frame, shareType) } else { val accessToken = askSettings.getAccessToken() if (StringUtil.isEmpty(accessToken)) { showWarnNotification("Statistics fetch failed", "access token is not specified", project) return } ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Fetching statistics for Main menu", false) { override fun run(indicator: ProgressIndicator) { myMainMenuProgress = true val startDate = getDateString(startEndDate.first) val endDate = getDateString(startEndDate.second) val menuAllStats = fetchStatistics(startDate, endDate, PRODUCT_CODE, myBuilds, arrayListOf(MAIN_MENU_GROUP), accessToken!!) if (menuAllStats.isNotEmpty()) { mainMenuAllMetrics.addAll(menuAllStats) groupStatsByMenus(frame, mainMenuAllMetrics) addMenusPopupListener(frame, shareType) } myMainMenuProgress = false } }) } } } private fun groupStatsByMenus(frame: IdeFrameImpl, mainMenuAllStats: List<MetricEntity>) { val menus = frame.rootPane.jMenuBar.components for (menu in menus) { if (menu is ActionMenu) { val menuName = menu.text if (mainMenuMetrics[menuName] == null) { val menuStats = filterByMenuName(mainMenuAllStats, menuName) if (menuStats.isNotEmpty()) mainMenuMetrics[menuName] = menuStats var menuAllUsers = 0 menuStats.forEach { menuAllUsers += it.users } if (menuAllUsers > 0) mainMenuTotalMetricsUsers[menuName] = menuAllUsers } } } } private fun paintActionMenu(menu: ActionMenu, allUsers: Int, level: Float) { val menuName = menu.text val menuAllUsers = mainMenuTotalMetricsUsers[menuName] menu.component.background = tuneColor(myColor, level) menu.addMouseListener(object : MouseAdapter() { override fun mouseEntered(e: MouseEvent?) { ActionMenu.showDescriptionInStatusBar(true, menu.component, "$menuName: $menuAllUsers usages of total $allUsers") } override fun mouseExited(e: MouseEvent?) { ActionMenu.showDescriptionInStatusBar(true, menu.component, "") } }) } private fun addMenusPopupListener(frame: IdeFrameImpl, shareType: ShareType) { val menus = frame.rootPane.jMenuBar.components var mainMenuAllUsers = 0 mainMenuTotalMetricsUsers.values.forEach { mainMenuAllUsers += it } for (menu in menus) { if (menu is ActionMenu) { paintMenuAndAddPopupListener(mutableListOf(menu.text), menu, mainMenuAllUsers, shareType) } } } private fun paintMenuAndAddPopupListener(menuGroupNames: MutableList<String>, menu: ActionMenu, menuAllUsers: Int, shareType: ShareType) { val level = if (menuGroupNames.size == 1) { val subMenuAllUsers = mainMenuTotalMetricsUsers[menuGroupNames[0]] ?: 0 subMenuAllUsers / menuAllUsers.toFloat() } else { val subItemsStas: List<MetricEntity> = getMenuSubItemsStat(menuGroupNames) val maxUsers = subItemsStas.maxBy { m -> m.users } if (maxUsers != null) getLevel(shareType, maxUsers, MetricGroup.MAIN_MENU) else 0.001f } paintActionMenu(menu, menuAllUsers, level) val popupMenu = menu.popupMenu as? JBPopupMenu ?: return popupMenu.addPopupMenuListener(object : PopupMenuListenerAdapter() { override fun popupMenuWillBecomeVisible(e: PopupMenuEvent) { val source = e.source as? JBPopupMenu ?: return val menuStats = mainMenuMetrics[menuGroupNames[0]] ?: return for (c in source.components) { if (c is ActionMenuItem) { paintMenuItem(c, menuGroupNames, menuStats, shareType) } else if (c is ActionMenu) { val newMenuGroup = menuGroupNames.toMutableList() newMenuGroup.add(newMenuGroup.lastIndex + 1, c.text) paintMenuAndAddPopupListener(newMenuGroup, c, menuAllUsers, shareType) } } } }) } private fun getMenuSubItemsStat(menuGroupNames: MutableList<String>): List<MetricEntity> { val menuStat = mainMenuMetrics[menuGroupNames[0]] ?: emptyList() val pathPrefix = convertMenuItemsToKey(menuGroupNames) val result = mutableListOf<MetricEntity>() menuStat.forEach { if (it.id.startsWith(pathPrefix)) result.add(it) } return result } private fun paintMenuItem(menuItem: ActionMenuItem, menuGroupNames: List<String>, menuStats: List<MetricEntity>, shareType: ShareType) { val pathPrefix = convertMenuItemsToKey(menuGroupNames) val metricId = pathPrefix + MENU_ITEM_SEPARATOR + menuItem.text val menuItemMetric: MetricEntity? = findMetric(menuStats, metricId) if (menuItemMetric != null) { val color = calcColorForMetric(shareType, menuItemMetric, MetricGroup.MAIN_MENU) menuItem.isOpaque = true menuItem.text = menuItem.text + " (${menuItemMetric.users} / ${getMetricPlaceTotalUsersCache(menuItemMetric, MetricGroup.MAIN_MENU)})" menuItem.component.background = color } menuItem.addMouseListener(object : MouseAdapter() { override fun mouseEntered(e: MouseEvent) { //adds text to status bar and searching metrics if it was not found (using the path from MenuSelectionManager) val actionMenuItem = e.source if (actionMenuItem is ActionMenuItem) { val placeText = menuGroupNames.first() val action = actionMenuItem.anAction if (menuItemMetric != null) { val textWithStat = getTextWithStat(menuItemMetric, shareType, getMetricPlaceTotalUsersCache(menuItemMetric, MetricGroup.MAIN_MENU), placeText) val actionText = StringUtil.notNullize(menuItem.anAction.templatePresentation.text) ActionMenu.showDescriptionInStatusBar(true, menuItem, "$actionText: $textWithStat") } else { val pathStr = getPathFromMenuSelectionManager(action) if (pathStr != null) { val metric = findMetric(menuStats, pathStr) if (metric != null) { actionMenuItem.isOpaque = true actionMenuItem.component.background = calcColorForMetric(shareType, metric, MetricGroup.MAIN_MENU) val textWithStat = getTextWithStat(metric, shareType, getMetricPlaceTotalUsersCache(metric, MetricGroup.MAIN_MENU), placeText) val actionText = StringUtil.notNullize(menuItem.anAction.templatePresentation.text) ActionMenu.showDescriptionInStatusBar(true, menuItem, "$actionText: $textWithStat") } } } } } override fun mouseExited(e: MouseEvent?) { ActionMenu.showDescriptionInStatusBar(true, menuItem, "") } }) } private fun getPathFromMenuSelectionManager(action: AnAction): String? { val groups = MenuSelectionManager.defaultManager().selectedPath.filterIsInstance<ActionMenu>().map { o -> o.text }.toMutableList() if (groups.size > 0) { val text = getActionText(action) groups.add(text) return convertMenuItemsToKey(groups) } return null } private fun convertMenuItemsToKey(menuItems: List<String>): String { return menuItems.joinToString(MENU_ITEM_SEPARATOR) } private fun getActionText(action: AnAction): String { return ourBlackList[action.javaClass.name] ?: action.templatePresentation.text } private fun settingsChanged(startEndDate: Pair<Date, Date>, shareType: ShareType, currentServiceUrl: String, ideBuilds: List<String>, includeEap: Boolean): Boolean { if (currentServiceUrl != myServiceUrl) return true if (includeEap != myIncludeEap) return true if (ideBuilds.size != myBuilds.size) return true for (build in ideBuilds) { if (!myBuilds.contains(build)) return true } val prevStartEndDate = myEndStartDate if (prevStartEndDate != null) { if (!isSameDay(prevStartEndDate.first, startEndDate.first) || !isSameDay(prevStartEndDate.second, startEndDate.second)) { return true } } val prevShareType = myShareType if (prevShareType != null && prevShareType != shareType) { return true } return false } private fun isSameDay(date1: Date, date2: Date): Boolean { val c1 = Calendar.getInstance() val c2 = Calendar.getInstance() c1.time = date1 c2.time = date2 return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR) } private fun paintVisibleToolBars(project: Project, component: JComponent, shareType: ShareType, toolBarStats: List<MetricEntity>) { if (component is ActionToolbarImpl) paintToolBarButtons(component, shareType, toolBarStats) for (c in component.components) { when (c) { is ActionToolbarImpl -> paintToolBarButtons(c, shareType, toolBarStats) is JComponent -> paintVisibleToolBars(project, c, shareType, toolBarStats) else -> { LOG.debug("Unknown component: ${c.name}") } } } } private fun paintToolBarButtons(toolbar: ActionToolbarImpl, shareType: ShareType, toolBarAllStats: List<MetricEntity>) { val place = ConvertUsagesUtil.escapeDescriptorName(toolbar.place).replace(' ', '.') val toolBarStat = toolbarsMetrics[place] ?: filterByPlaceToolbar(toolBarAllStats, place) var toolbarAllUsers = 0 toolBarStat.forEach { toolbarAllUsers += it.users } if (toolBarStat.isNotEmpty()) toolbarsMetrics[place] = toolBarStat if (toolbarAllUsers > 0) toolbarsTotalMetricsUsers[place] = toolbarAllUsers for (button in toolbar.components) { val action = (button as? ActionButton)?.action ?: UIUtil.getClientProperty(button, CustomComponentAction.ACTION_KEY) ?: continue val id = getActionId(action) val buttonMetric = findMetric(toolBarStat, "$id@$place") val buttonColor = if (buttonMetric != null) calcColorForMetric(shareType, buttonMetric, MetricGroup.TOOLBAR) else BUTTON_EMPTY_STATS_COLOR val textWithStats = if (buttonMetric != null) getTextWithStat(buttonMetric, shareType, toolbarAllUsers, place) else "" val tooltipText = StringUtil.notNullize(action.templatePresentation.text) + textWithStats if (button is ActionButton) { (button as JComponent).toolTipText = tooltipText button.setLook(createButtonLook(buttonColor)) } else if (button is JComponent) { button.toolTipText = tooltipText button.isOpaque = true button.background = buttonColor } LOG.debug("Place: $place action id: [$id]") } } private fun getTextWithStat(buttonMetric: MetricEntity, shareType: ShareType, placeAllUsers: Int, place: String): String { val totalUsers = if (shareType == ShareType.BY_GROUP) buttonMetric.sampleSize else placeAllUsers return "\nClicks: Unique:${buttonMetric.users} / Avg:${DecimalFormat("####.#").format( buttonMetric.usagesPerUser)} / ${place.capitalize()} total:$totalUsers" } private fun clearCache() { toolbarsAllMetrics.clear() toolbarsMetrics.clear() mainMenuAllMetrics.clear() mainMenuMetrics.clear() toolbarsTotalMetricsUsers.clear() mainMenuTotalMetricsUsers.clear() } private fun getActionId(action: AnAction): String { return ActionManager.getInstance().getId(action) ?: if (action is ActionWithDelegate<*>) { (action as ActionWithDelegate<*>).presentableName } else { action.javaClass.name } } private fun getDateString(date: Date): String = SimpleDateFormat(DATE_PATTERN).format(date) private fun findMetric(list: List<MetricEntity>, key: String): MetricEntity? { val metricId = ConvertUsagesUtil.escapeDescriptorName(key) list.forEach { if (it.id == metricId) return it } return null } private fun createButtonLook(color: Color): ActionButtonLook { return object : ActionButtonLook() { override fun paintBorder(g: Graphics, c: JComponent, state: Int) { g.drawLine(c.width - 1, 0, c.width - 1, c.height) } override fun paintBackground(g: Graphics, component: JComponent, state: Int) { if (state == ActionButtonComponent.PUSHED) { g.color = component.background.brighter() (g as Graphics2D).fill(g.getClip()) } else { g.color = color (g as Graphics2D).fill(g.getClip()) } } } } private fun getMetricPlaceTotalUsersCache(metricEntity: MetricEntity, group: MetricGroup): Int { return when (group) { MetricGroup.TOOLBAR -> toolbarsTotalMetricsUsers[getToolBarButtonPlace(metricEntity)] ?: -1 MetricGroup.MAIN_MENU -> mainMenuTotalMetricsUsers[getMenuName(metricEntity)] ?: -1 } } private fun calcColorForMetric(shareType: ShareType, metricEntity: MetricEntity, group: MetricGroup): Color { val level = getLevel(shareType, metricEntity, group) return tuneColor(myColor, level) } fun getLevel(shareType: ShareType, metricEntity: MetricEntity, group: MetricGroup): Float { return if (shareType == ShareType.BY_GROUP) { Math.max(metricEntity.share, 0.0001f) / 100.0f } else { val toolbarUsers = getMetricPlaceTotalUsersCache(metricEntity, group) if (toolbarUsers != -1) metricEntity.users / toolbarUsers.toFloat() else Math.max(metricEntity.share, 0.0001f) / 100.0f } } private fun tuneColor(default: Color, level: Float): Color { val r = default.red val g = default.green val b = default.blue val hsb = FloatArray(3) Color.RGBtoHSB(r, g, b, hsb) hsb[1] *= level val hsbBkg = FloatArray(3) val background = UIUtil.getLabelBackground() Color.RGBtoHSB(background.red, background.green, background.blue, hsbBkg) return JBColor.getHSBColor(hsb[0], hsb[1], hsbBkg[2]) } private fun getProductCode(): String { var code = ApplicationInfo.getInstance().build.productCode if (StringUtil.isNotEmpty(code)) return code code = getProductCodeFromBuildFile() return if (StringUtil.isNotEmpty(code)) code else getProductCodeFromPlatformPrefix() } private fun getProductCodeFromBuildFile(): String { try { val home = PathManager.getHomePath() val buildTxtFile = FileUtil.findFirstThatExist( "$home/build.txt", "$home/Resources/build.txt", "$home/community/build.txt", "$home/ultimate/community/build.txt") if (buildTxtFile != null) { return FileUtil.loadFile(buildTxtFile).trim { it <= ' ' }.substringBefore('-', "") } } catch (ignored: IOException) { } return "" } private fun getProductCodeFromPlatformPrefix(): String { return when { PlatformUtils.isIdeaCommunity() -> "IC" PlatformUtils.isIdeaUltimate() -> "IU" PlatformUtils.isAppCode() -> "AC" PlatformUtils.isCLion() -> "CL" PlatformUtils.isDataGrip() -> "DB" PlatformUtils.isGoIde() -> "GO" PlatformUtils.isPyCharmPro() -> "PY" PlatformUtils.isPyCharmCommunity() -> "PC" PlatformUtils.isPyCharmEducational() -> "PE" PlatformUtils.isPhpStorm() -> "PS" PlatformUtils.isRider() -> "RD" PlatformUtils.isWebStorm() -> "WS" PlatformUtils.isRubyMine() -> "RM" else -> "" } } } enum class ShareType { BY_PLACE, BY_GROUP } private const val MENU_ITEM_SEPARATOR = " -> " private const val MAIN_MENU_GROUP = "statistics.actions.main.menu" private const val TOOLBAR_GROUP = "statistics.ui.toolbar.clicks" private const val DATE_PATTERN = "YYYY-MM-dd" enum class MetricGroup(val groupId: String) { TOOLBAR(TOOLBAR_GROUP), MAIN_MENU(MAIN_MENU_GROUP) } data class MetricEntity(val id: String, val sampleSize: Int, val groupSize: Int, val users: Int, val usages: Int, val usagesPerUser: Float, val share: Float) data class ProductBuildInfo(val code: String, val type: String, val version: String, val majorVersion: String, val build: String) { fun isEap(): Boolean = type.equals("eap", true) }
apache-2.0
7f9cb403b9b4b2c7f298a7edbcdcc26f
39.440285
140
0.694305
4.639264
false
false
false
false
bozaro/git-as-svn
src/main/kotlin/svnserver/parser/token/WordToken.kt
1
1501
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.parser.token import java.io.IOException import java.io.OutputStream import java.nio.charset.StandardCharsets /** * Ключевое слово. * * * Допустимые символы: 'a'..'z', 'A'..'Z', '-', '0'..'9' * * @author Artem V. Navrotskiy <[email protected]> */ class WordToken constructor(override val text: String) : TextToken { @Throws(IOException::class) override fun write(stream: OutputStream) { write(stream, text) } override fun toString(): String { return "Word{$text}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as WordToken if (text != other.text) return false return true } override fun hashCode(): Int { return text.hashCode() } companion object { @Throws(IOException::class) fun write(stream: OutputStream, word: String) { stream.write(word.toByteArray(StandardCharsets.US_ASCII)) stream.write(' '.code) } } }
gpl-2.0
c67acc43a072af4773a2227a392b17bb
26.240741
76
0.646499
3.840731
false
false
false
false
apixandru/intellij-community
platform/lang-impl/src/com/intellij/ide/util/gotoByName/SelectionPolicy.kt
5
1782
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.util.gotoByName /** * @author peter */ internal interface SelectionPolicy { fun performSelection(popup: ChooseByNameBase, model: SmartPointerListModel<Any>): List<Int> } internal fun fromIndex(index: Int) = if (index <= 0) SelectMostRelevant else SelectIndex(index) internal object SelectMostRelevant : SelectionPolicy { override fun performSelection(popup: ChooseByNameBase, model: SmartPointerListModel<Any>) = listOf(popup.calcSelectedIndex(model.items.toTypedArray(), popup.trimmedText)) } internal data class SelectIndex(private val selectedIndex: Int) : SelectionPolicy { override fun performSelection(popup: ChooseByNameBase, model: SmartPointerListModel<Any>) = listOf(selectedIndex) } internal data class SelectionSnapshot(val pattern: String, private val chosenElements: Set<Any>) : SelectionPolicy { override fun performSelection(popup: ChooseByNameBase, model: SmartPointerListModel<Any>): List<Int> { val items = model.items return items.indices.filter { items[it] in chosenElements } } fun hasSamePattern(popup: ChooseByNameBase) = popup.transformPattern(pattern) == popup.transformPattern(popup.trimmedText) }
apache-2.0
672a451a2ae0083771919cc18fd36071
40.465116
124
0.771605
4.293976
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/edit/richtext/SyntaxHighlighter.kt
1
11362
package org.wikipedia.edit.richtext import android.content.Context import android.os.Build import android.text.Spanned import androidx.core.text.getSpans import androidx.core.widget.NestedScrollView import androidx.core.widget.doAfterTextChanged import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.edit.SyntaxHighlightableEditText import org.wikipedia.util.log.L import java.util.* import java.util.concurrent.Callable import java.util.concurrent.TimeUnit class SyntaxHighlighter( private var context: Context, private val textBox: SyntaxHighlightableEditText, private val scrollView: NestedScrollView) { private val syntaxRules = listOf( SyntaxRule("{{", "}}", SyntaxRuleStyle.TEMPLATE), SyntaxRule("[[", "]]", SyntaxRuleStyle.INTERNAL_LINK), SyntaxRule("[", "]", SyntaxRuleStyle.EXTERNAL_LINK), SyntaxRule("<big>", "</big>", SyntaxRuleStyle.TEXT_LARGE), SyntaxRule("<small>", "</small>", SyntaxRuleStyle.TEXT_SMALL), SyntaxRule("<sub>", "</sub>", SyntaxRuleStyle.SUBSCRIPT), SyntaxRule("<sup>", "</sup>", SyntaxRuleStyle.SUPERSCRIPT), SyntaxRule("<code>", "</code>", if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) SyntaxRuleStyle.CODE else SyntaxRuleStyle.BOLD), SyntaxRule("<u>", "</u>", SyntaxRuleStyle.UNDERLINE), SyntaxRule("<s>", "</s>", SyntaxRuleStyle.STRIKETHROUGH), SyntaxRule("<", ">", SyntaxRuleStyle.REF), SyntaxRule("'''", "'''", SyntaxRuleStyle.BOLD), SyntaxRule("''", "''", SyntaxRuleStyle.ITALIC), SyntaxRule("=====", "=====", SyntaxRuleStyle.HEADING_SMALL), SyntaxRule("====", "====", SyntaxRuleStyle.HEADING_SMALL), SyntaxRule("===", "===", SyntaxRuleStyle.HEADING_MEDIUM), SyntaxRule("==", "==", SyntaxRuleStyle.HEADING_LARGE), ) private val disposables = CompositeDisposable() private var currentHighlightTask: SyntaxHighlightTask? = null private var lastScrollY = -1 private val highlightOnScrollRunnable = Runnable { postHighlightOnScroll() } private var searchQueryPositions: List<Int>? = null private var searchQueryLength = 0 private var searchQueryPositionIndex = 0 var enabled = true set(value) { field = value if (!value) { currentHighlightTask?.cancel() disposables.clear() textBox.text.getSpans<SpanExtents>().forEach { textBox.text.removeSpan(it) } } else { runHighlightTasks(HIGHLIGHT_DELAY_MILLIS) } } init { textBox.doAfterTextChanged { runHighlightTasks(HIGHLIGHT_DELAY_MILLIS * 2) } textBox.scrollView = scrollView postHighlightOnScroll() } private fun runHighlightTasks(delayMillis: Long) { currentHighlightTask?.cancel() disposables.clear() if (!enabled) { return } disposables.add(Observable.timer(delayMillis, TimeUnit.MILLISECONDS) .flatMap { if (textBox.layout == null) { throw IllegalArgumentException() } var firstVisibleLine = textBox.layout.getLineForVertical(scrollView.scrollY) if (firstVisibleLine < 0) firstVisibleLine = 0 var lastVisibleLine = textBox.layout.getLineForVertical(scrollView.scrollY + scrollView.height) if (lastVisibleLine < firstVisibleLine) lastVisibleLine = firstVisibleLine else if (lastVisibleLine >= textBox.lineCount) lastVisibleLine = textBox.lineCount - 1 val firstVisibleIndex = textBox.layout.getLineStart(firstVisibleLine) val lastVisibleIndex = textBox.layout.getLineEnd(lastVisibleLine) val textToHighlight = textBox.text.substring(firstVisibleIndex, lastVisibleIndex) currentHighlightTask = SyntaxHighlightTask(textToHighlight, firstVisibleIndex) Observable.zip<MutableList<SpanExtents>, List<SpanExtents>, List<SpanExtents>>(Observable.fromCallable(currentHighlightTask!!), if (searchQueryPositions.isNullOrEmpty()) Observable.just(emptyList()) else Observable.fromCallable(SyntaxHighlightSearchMatchesTask(firstVisibleIndex, textToHighlight.length))) { f, s -> f.addAll(s) f } } .retry(10) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ result -> textBox.enqueueNoScrollingLayoutChange() var time = System.currentTimeMillis() val oldSpans = textBox.text.getSpans<SpanExtents>().toMutableList() val newSpans = result.toMutableList() val dupes = oldSpans.filter { item -> val r = result.find { it.start == textBox.text.getSpanStart(item) && it.end == textBox.text.getSpanEnd(item) && it.syntaxRule == item.syntaxRule } if (r != null) { newSpans.remove(r) } r != null } oldSpans.removeAll(dupes) oldSpans.forEach { textBox.text.removeSpan(it) } newSpans.forEach { textBox.text.setSpan(it, it.start, it.end, Spanned.SPAN_INCLUSIVE_INCLUSIVE) } time = System.currentTimeMillis() - time L.d("Took $time ms to remove ${oldSpans.size} spans and add ${newSpans.size} new.") }) { L.e(it) }) } fun setSearchQueryInfo(searchQueryPositions: List<Int>?, searchQueryLength: Int, searchQueryPositionIndex: Int) { this.searchQueryPositions = searchQueryPositions this.searchQueryLength = searchQueryLength this.searchQueryPositionIndex = searchQueryPositionIndex runHighlightTasks(0) } fun clearSearchQueryInfo() { setSearchQueryInfo(null, 0, 0) } fun cleanup() { scrollView.removeCallbacks(highlightOnScrollRunnable) disposables.clear() textBox.text.clearSpans() } private fun postHighlightOnScroll() { if (lastScrollY != scrollView.scrollY) { lastScrollY = scrollView.scrollY runHighlightTasks(0) } scrollView.postDelayed(highlightOnScrollRunnable, HIGHLIGHT_DELAY_MILLIS) } private inner class SyntaxHighlightTask constructor(private val text: CharSequence, private val startOffset: Int) : Callable<MutableList<SpanExtents>> { private var cancelled = false fun cancel() { cancelled = true } override fun call(): MutableList<SpanExtents> { val spanStack = Stack<SpanExtents>() val spansToSet = mutableListOf<SpanExtents>() val textChars = text.toString().toCharArray() /* The (naïve) algorithm: Iterate through the text string, and maintain a stack of matched syntax rules. When the "start" and "end" symbol of a rule are matched in sequence, create a new Span to be added to the EditText at the corresponding location. */ var i = 0 while (i < textChars.size) { var newSpanInfo: SpanExtents var completed = false for (rule in syntaxRules) { if (i + rule.endChars.size > textChars.size) { continue } var pass = true for (j in 0 until rule.endChars.size) { if (textChars[i + j] != rule.endChars[j]) { pass = false break } } if (pass) { val sr = spanStack.find { it.syntaxRule == rule } if (sr != null) { newSpanInfo = sr spanStack.remove(sr) newSpanInfo.end = i + rule.endChars.size spansToSet.add(newSpanInfo) i += rule.endChars.size - 1 completed = true break } } } if (!completed) { for (rule in syntaxRules) { if (i + rule.startChars.size > textChars.size) { continue } var pass = true for (j in 0 until rule.startChars.size) { if (textChars[i + j] != rule.startChars[j]) { pass = false break } } if (pass) { val sp = rule.spanStyle.createSpan(context, i, rule) spanStack.push(sp) i += rule.startChars.size - 1 break } } if (cancelled) { break } } i++ } spansToSet.forEach { it.start += startOffset it.end += startOffset } spansToSet.sortWith { a, b -> a.syntaxRule.spanStyle.compareTo(b.syntaxRule.spanStyle) } return spansToSet } } private inner class SyntaxHighlightSearchMatchesTask constructor(private val startOffset: Int, private val textLength: Int) : Callable<List<SpanExtents>> { override fun call(): List<SpanExtents> { val spansToSet = mutableListOf<SpanExtents>() val syntaxItem = SyntaxRule("", "", SyntaxRuleStyle.SEARCH_MATCHES) searchQueryPositions?.let { for (i in it.indices) { if (it[i] >= startOffset && it[i] < startOffset + textLength) { val newSpanInfo = if (i == searchQueryPositionIndex) { SyntaxRuleStyle.SEARCH_MATCH_SELECTED.createSpan(context, it[i], syntaxItem) } else { SyntaxRuleStyle.SEARCH_MATCHES.createSpan(context, it[i], syntaxItem) } newSpanInfo.start = it[i] newSpanInfo.end = it[i] + searchQueryLength spansToSet.add(newSpanInfo) } } } return spansToSet } } companion object { const val HIGHLIGHT_DELAY_MILLIS = 500L } }
apache-2.0
8fa6ecf633b4bebc5294a05bcc33e9b6
41.550562
159
0.540357
5.34887
false
false
false
false
stripe/stripe-android
identity/src/main/java/com/stripe/android/identity/networking/models/DocumentUploadParam.kt
1
1008
package com.stripe.android.identity.networking.models import android.os.Parcelable import kotlinx.parcelize.Parcelize import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @Parcelize internal data class DocumentUploadParam( @SerialName("back_score") val backScore: Float? = null, @SerialName("front_card_score") val frontCardScore: Float? = null, @SerialName("high_res_image") val highResImage: String, @SerialName("invalid_score") val invalidScore: Float? = null, @SerialName("low_res_image") val lowResImage: String? = null, @SerialName("passport_score") val passportScore: Float? = null, @SerialName("upload_method") val uploadMethod: UploadMethod ) : Parcelable { @Serializable internal enum class UploadMethod { @SerialName("auto_capture") AUTOCAPTURE, @SerialName("file_upload") FILEUPLOAD, @SerialName("manual_capture") MANUALCAPTURE; } }
mit
e840c21489f072ce0632aa33a1e2f982
26.243243
53
0.698413
4.2
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/UpiPaymentActivity.kt
1
2363
package com.stripe.example.activity import android.content.Intent import android.os.Bundle import androidx.lifecycle.Observer import com.stripe.android.model.Address import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.payments.paymentlauncher.PaymentResult import com.stripe.example.databinding.UpiPaymentActivityBinding class UpiPaymentActivity : StripeIntentActivity() { private val viewBinding: UpiPaymentActivityBinding by lazy { UpiPaymentActivityBinding.inflate(layoutInflater) } private lateinit var paymentIntentSecret: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) viewModel.status.observe(this, Observer(viewBinding.status::setText)) viewBinding.submit.setOnClickListener { val params = PaymentMethodCreateParams.create( upi = PaymentMethodCreateParams.Upi( vpa = viewBinding.vpa.text.toString() ), billingDetails = PaymentMethod.BillingDetails( name = "Jenny Rosen", phone = "(555) 555-5555", email = "[email protected]", address = Address.Builder() .setCity("San Francisco") .setCountry("US") .setLine1("123 Market St") .setLine2("#345") .setPostalCode("94107") .setState("CA") .build() ) ) createAndConfirmPaymentIntent("in", params) { secret -> paymentIntentSecret = secret } } } override fun onConfirmSuccess() { startActivity( Intent(this@UpiPaymentActivity, UpiWaitingActivity::class.java) .putExtra(EXTRA_CLIENT_SECRET, paymentIntentSecret) ) } override fun onConfirmError(failedResult: PaymentResult.Failed) { viewModel.status.value += "\n\nPaymentIntent confirmation failed with throwable " + "${failedResult.throwable} \n\n" } internal companion object { const val EXTRA_CLIENT_SECRET = "extra_client_secret" } }
mit
854170a7e8185176251e32fab92fdebe
35.353846
91
0.614896
5.193407
false
false
false
false
ioc1778/incubator
incubator-javafx-desktop/src/main/java/com/riaektiv/javafx/desktop/PortfolioApplication.kt
2
3075
package com.riaektiv.javafx.desktop import javafx.application.Application import javafx.collections.FXCollections import javafx.geometry.Insets import javafx.scene.Group import javafx.scene.Scene import javafx.scene.control.* import javafx.scene.control.cell.PropertyValueFactory import javafx.scene.layout.HBox import javafx.scene.layout.VBox import javafx.scene.text.Font import javafx.stage.Stage /** * Coding With Passion Since 1991 * Created: 9/4/2016, 6:12 PM Eastern Time * @author Sergey Chuykov */ class PortfolioApplication : Application() { private val table = TableView<Position>() private val data = FXCollections.observableArrayList( Position("APA", "Apache Corp.", "3000"), Position("CHK", "Chesapeake Energy Corp.", "1000"), Position("NBL", "Nobel Energy Inc.", "5000")) @SuppressWarnings("unchecked") @Throws(Exception::class) override fun start(stage: Stage) { val scene = Scene(Group()) stage.title = "Portfolio" stage.width = 700.0 stage.height = 500.0 val label = Label("Positions") label.font = Font("Arial", 20.0) table.isEditable = true table.maxHeight = 300.0 val symbolCol = TableColumn<Position, String>("Symbol") symbolCol.minWidth = 100.0 symbolCol.cellValueFactory = PropertyValueFactory<Position, String>("symbol") val companyCol = TableColumn<Position, String>("Company") companyCol.minWidth = 400.0 companyCol.cellValueFactory = PropertyValueFactory<Position, String>("company") val qtyCol = TableColumn<Position, String>("Qty") qtyCol.minWidth = 100.0 qtyCol.cellValueFactory = PropertyValueFactory<Position, String>("qty") table.items = data table.columns.addAll(symbolCol, companyCol, qtyCol) val symbolText = TextField() symbolText.promptText = "Symbol" symbolText.maxWidth = symbolCol.prefWidth val companyText = TextField() companyText.maxWidth = companyCol.prefWidth companyText.promptText = "Company" val qtyText = TextField() qtyText.maxWidth = qtyCol.prefWidth qtyText.promptText = "Qty" val addButton = Button("Add") addButton.setOnAction { e -> data.add(Position( symbolText.text, companyText.text, qtyText.text)) symbolText.clear() companyText.clear() qtyText.clear() } val hb = HBox() hb.children.addAll(symbolText, companyText, qtyText, addButton) hb.spacing = 3.0 val vb = VBox() vb.spacing = 5.0 vb.padding = Insets(10.0, 0.0, 0.0, 10.0) vb.children.addAll(label, table, hb) (scene.root as Group).children.addAll(vb) stage.scene = scene stage.show() } companion object { @JvmStatic fun main(args: Array<String>) { launch(PortfolioApplication::class.java, *args) } } }
bsd-3-clause
52eff951c6acebf871836106a0b97636
29.147059
87
0.63122
4.270833
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/issues/actions/AnalyzeStacktraceAction.kt
1
2463
package com.github.jk1.ytplugin.issues.actions import com.github.jk1.ytplugin.issues.model.Issue import com.github.jk1.ytplugin.whenActive import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ide.CopyPasteManager import org.apache.commons.lang.StringEscapeUtils import java.awt.datatransfer.StringSelection import javax.swing.Icon /** * Checks, if issue description contains an exception and enables analyze stack trace * action for that exception. Current implementation can recognize only one exception * per issue and ignores comments. * * todo: add configurable option to skip an unscramble dialog and analyze stacktrace right away */ class AnalyzeStacktraceAction(private val getSelectedIssue: () -> Issue?) : IssueAction() { override val text = "Analyze Stack Trace" override val description = "Open the content from the issue description in the Analyze Stack Trace dialog" override val icon: Icon = AllIcons.Actions.Lightning override val shortcut = "control shift S" override fun actionPerformed(event: AnActionEvent) { event.whenActive { val issue = getSelectedIssue.invoke() if (issue != null && issue.hasException()) { openAnalyzeDialog(issue, event) } } } override fun update(event: AnActionEvent) { val issue = getSelectedIssue.invoke() event.presentation.isEnabled = issue != null && issue.hasException() } private fun openAnalyzeDialog(issue: Issue, event: AnActionEvent) { val clipboard = CopyPasteManager.getInstance() val existingContent = clipboard.contents // Analyze dialog uses clipboard contents, let's put a stack trace there clipboard.setContents(StringSelection(issue.getException())) ActionManager.getInstance().getAction("Unscramble").actionPerformed(event) if (existingContent != null) { // and restore everything afterwards clipboard.setContents(existingContent) } } private fun Issue.hasException() = description.contains("<pre class=\"wiki-exception\"") private fun Issue.getException() = StringEscapeUtils.unescapeHtml(description .split("</pre>")[1] .replace("<br/>", "\n") .replace("<[^>]+>".toRegex(), "") .replace("&hellip;", "")) }
apache-2.0
020aae9469c0e2116dd85bd3943cd2ae
40.066667
110
0.701989
4.857988
false
false
false
false
norswap/violin
src/norswap/violin/Utils.kt
1
4585
@file:Suppress("PackageDirectoryMismatch") package norswap.violin.utils import java.io.PrintWriter import java.io.StringWriter import java.nio.file.Files import java.nio.file.Paths import java.util.Comparator /** * This file contains a smattering of functions that do not find their place anywhere else. */ // ------------------------------------------------------------------------------------------------- /** * Returns the result of [f]. * The point is to allow statements in an expression context. */ inline fun <T> expr(f: () -> T): T = f() // ------------------------------------------------------------------------------------------------- /** * Returns the receiver after evaluating [f] on it. */ inline infix fun <T> T.after(f: (T) -> Unit): T { f(this) return this } // ------------------------------------------------------------------------------------------------- /** * Syntactic sugar for `if (this) then f() else null`. */ infix inline fun <T> Boolean.then (f: () -> T): T? = if (this) f() else null // ------------------------------------------------------------------------------------------------- /** * Analogous to `Kotlin.arrayOf`, but doesn't require reification. */ @Suppress("UNCHECKED_CAST") fun <T: Any> array(vararg items: T) = items as Array<T> // ------------------------------------------------------------------------------------------------- /** * Shorthand for [StringBuilder.append]. */ operator fun StringBuilder.plusAssign(s: String) { append(s) } // ------------------------------------------------------------------------------------------------- /** * Shorthand for [StringBuilder.append]. */ operator fun StringBuilder.plusAssign(o: Any?) { append(o) } // ------------------------------------------------------------------------------------------------- /** * Casts the receiver to [T]. * * This is more useful than regular casts because it enables casts to non-denotable types * through type inference. */ @Suppress("UNCHECKED_CAST") fun <T> Any?.cast() = this as T // ------------------------------------------------------------------------------------------------- /** * Like `String.substring` but allows [start] and [end] to be negative numbers. * * The first item in the sequence has index `0` (same as `-length`). * The last item in the sequence has index `length-1` (same as `-1`). * * The [start] bound is always inclusive. * The [end] bound is exclusive if positive, else inclusive. * * Throws an [IndexOutOfBoundsException] if the [start] bounds refers to an index below `0` or * if [end] refers to an index equal to or past `CharSequence.length`. * * It is fine to call this with [start] referring to `a` and [end] referring to `b` such that * `a > b`, as long the previous condition is respected. The result is then the empty string. */ operator fun CharSequence.get(start: Int, end: Int = length): String { val a = if (start >= 0) start else length + start val b = if (end >= 0) end else length + end + 1 if (a < 0) throw IndexOutOfBoundsException("Start index < 0") if (b > length) throw IndexOutOfBoundsException("End index > length") if (a > b) return "" return substring(a, b) } // ------------------------------------------------------------------------------------------------- /** * Reads a complete file and returns its contents as a string. * @throws IOException see [Files.readAllBytes] * @throws InvalidPathException see [Paths.get] */ fun readFile(file: String) = String(Files.readAllBytes(Paths.get(file))) // ------------------------------------------------------------------------------------------------- /** * Returns a comparator for type T that delegates to a `Comparable` type U. */ fun <T, U: Comparable<U>> comparator(f: (T) -> U) = Comparator<T> { o1, o2 -> f(o1).compareTo(f(o2)) } // ------------------------------------------------------------------------------------------------- /** * Returns a comparator for type [T] that delegates the receiver, a comparator for type [U]. */ fun <T, U> Comparator<U>.derive(f: (T) -> U) = Comparator<T> { o1, o2 -> compare(f(o1), f(o2)) } // ------------------------------------------------------------------------------------------------- /** * Returns a string representation of the Throwable's stack trace. */ fun Throwable.stackTraceString(): String { val sw = StringWriter() printStackTrace(PrintWriter(sw)) return sw.toString() } // -------------------------------------------------------------------------------------------------
bsd-3-clause
0a5240ab8624e7e7ecbaeb3c751190b6
32.97037
100
0.477644
4.575848
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/GLES32.kt
1
42137
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengles.templates import org.lwjgl.generator.* import org.lwjgl.opengles.* import org.lwjgl.opengles.BufferType.* val GLES32 = "GLES32".nativeClassGLES("GLES32", postfix = "") { documentation = "The core OpenGL ES 3.2 functionality." IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.", "MULTISAMPLE_LINE_WIDTH_RANGE_ARB"..0x9381, "MULTISAMPLE_LINE_WIDTH_GRANULARITY_ARB"..0x9382 ) // KHR_blend_equation_advanced IntConstant( "Accepted by the {@code mode} parameter of BlendEquation and BlendEquationi.", "MULTIPLY"..0x9294, "SCREEN"..0x9295, "OVERLAY"..0x9296, "DARKEN"..0x9297, "LIGHTEN"..0x9298, "COLORDODGE"..0x9299, "COLORBURN"..0x929A, "HARDLIGHT"..0x929B, "SOFTLIGHT"..0x929C, "DIFFERENCE"..0x929E, "EXCLUSION"..0x92A0, "HSL_HUE"..0x92AD, "HSL_SATURATION"..0x92AE, "HSL_COLOR"..0x92AF, "HSL_LUMINOSITY"..0x92B0 ) void( "BlendBarrier", """ Specifies a boundary between passes when using advanced blend equations. When using advanced blending equations, applications should split their rendering into a collection of blending passes, none of which touch an individual sample in the framebuffer more than once. The results of blending are undefined if the sample being blended has been touched previously in the same pass. Any command that causes the value of a sample to be modified using the framebuffer is considered to touch the sample, including clears, blended or unblended primitives, and GLES30#BlitFramebuffer() copies. """ ) // OES_copy_image void( "CopyImageSubData", "", GLuint.IN("srcName", ""), GLenum.IN("srcTarget", ""), GLint.IN("srcLevel", ""), GLint.IN("srcX", ""), GLint.IN("srcY", ""), GLint.IN("srcZ", ""), GLuint.IN("dstName", ""), GLenum.IN("dstTarget", ""), GLint.IN("dstLevel", ""), GLint.IN("dstX", ""), GLint.IN("dstY", ""), GLint.IN("dstZ", ""), GLsizei.IN("srcWidth", ""), GLsizei.IN("srcHeight", ""), GLsizei.IN("srcDepth", "") ) // KHR_debug IntConstant( "Tokens accepted by the {@code target} parameters of Enable, Disable, and IsEnabled.", "DEBUG_OUTPUT"..0x92E0, "DEBUG_OUTPUT_SYNCHRONOUS"..0x8242 ) IntConstant( "Returned by GetIntegerv when {@code pname} is CONTEXT_FLAGS.", "CONTEXT_FLAG_DEBUG_BIT"..0x00000002 ) IntConstant( "Tokens accepted by the {@code value} parameters of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev and GetInteger64v.", "MAX_DEBUG_MESSAGE_LENGTH"..0x9143, "MAX_DEBUG_LOGGED_MESSAGES"..0x9144, "DEBUG_LOGGED_MESSAGES"..0x9145, "DEBUG_NEXT_LOGGED_MESSAGE_LENGTH"..0x8243, "MAX_DEBUG_GROUP_STACK_DEPTH"..0x826C, "DEBUG_GROUP_STACK_DEPTH"..0x826D, "MAX_LABEL_LENGTH"..0x82E8 ) IntConstant( "Tokens accepted by the {@code pname} parameter of GetPointerv.", "DEBUG_CALLBACK_FUNCTION"..0x8244, "DEBUG_CALLBACK_USER_PARAM"..0x8245 ) val DebugSources = IntConstant( """ Tokens accepted or provided by the {@code source} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC, and the {@code sources} parameter of GetDebugMessageLog. """, "DEBUG_SOURCE_API"..0x8246, "DEBUG_SOURCE_WINDOW_SYSTEM"..0x8247, "DEBUG_SOURCE_SHADER_COMPILER"..0x8248, "DEBUG_SOURCE_THIRD_PARTY"..0x8249, "DEBUG_SOURCE_APPLICATION"..0x824A, "DEBUG_SOURCE_OTHER"..0x824B ).javaDocLinks val DebugTypes = IntConstant( """ Tokens accepted or provided by the {@code type} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC, and the {@code types} parameter of GetDebugMessageLog. """, "DEBUG_TYPE_ERROR"..0x824C, "DEBUG_TYPE_DEPRECATED_BEHAVIOR"..0x824D, "DEBUG_TYPE_UNDEFINED_BEHAVIOR"..0x824E, "DEBUG_TYPE_PORTABILITY"..0x824F, "DEBUG_TYPE_PERFORMANCE"..0x8250, "DEBUG_TYPE_OTHER"..0x8251, "DEBUG_TYPE_MARKER"..0x8268 ).javaDocLinks IntConstant( """ Tokens accepted or provided by the {@code type} parameters of DebugMessageControl and DEBUGPROC, and the {@code types} parameter of GetDebugMessageLog. """, "DEBUG_TYPE_PUSH_GROUP"..0x8269, "DEBUG_TYPE_POP_GROUP"..0x826A ) val DebugSeverities = IntConstant( """ Tokens accepted or provided by the {@code severity} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC callback functions, and the {@code severities} parameter of GetDebugMessageLog. """, "DEBUG_SEVERITY_HIGH"..0x9146, "DEBUG_SEVERITY_MEDIUM"..0x9147, "DEBUG_SEVERITY_LOW"..0x9148, "DEBUG_SEVERITY_NOTIFICATION"..0x826B ).javaDocLinks IntConstant( "Returned by GetError.", "STACK_UNDERFLOW"..0x0504, "STACK_OVERFLOW"..0x0503 ) val DebugIdentifiers = IntConstant( "Tokens accepted or provided by the {@code identifier} parameters of ObjectLabel and GetObjectLabel.", "BUFFER"..0x82E0, "SHADER"..0x82E1, "PROGRAM"..0x82E2, "QUERY"..0x82E3, "PROGRAM_PIPELINE"..0x82E4, "SAMPLER"..0x82E6 ).javaDocLinks void( "DebugMessageControl", """ Controls the volume of debug output in the active debug group, by disabling specific or groups of messages. If {@code enabled} is GLES20#TRUE, the referenced subset of messages will be enabled. If GLES20#FALSE, then those messages will be disabled. This command can reference different subsets of messages by first considering the set of all messages, and filtering out messages based on the following ways: ${ul( """ If {@code source}, {@code type}, or {@code severity} is GLES20#DONT_CARE, the messages from all sources, of all types, or of all severities are referenced respectively. """, """ When values other than GLES20#DONT_CARE are specified, all messages whose source, type, or severity match the specified {@code source}, {@code type}, or {@code severity} respectively will be referenced. """, """ If {@code count} is greater than zero, then {@code ids} is an array of {@code count} message IDs for the specified combination of {@code source} and {@code type}. In this case, if {@code source} or {@code type} is GLES20#DONT_CARE, or {@code severity} is not GLES20#DONT_CARE, the error GLES20#INVALID_OPERATION is generated. """ )} Unrecognized message IDs in {@code ids} are ignored. If {@code count} is zero, the value if {@code ids} is ignored. Although messages are grouped into an implicit hierarchy by their sources and types, there is no explicit per-source, per-type or per-severity enabled state. Instead, the enabled state is stored individually for each message. There is no difference between disabling all messages from one source in a single call, and individually disabling all messages from that source using their types and IDs. If the #DEBUG_OUTPUT state is disabled the GL operates the same as if messages of every {@code source}, {@code type} or {@code severity} are disabled. """, GLenum.IN("source", "the source of debug messages to enable or disable", DebugSources), GLenum.IN("type", "the type of debug messages to enable or disable", DebugTypes), GLenum.IN("severity", "the severity of debug messages to enable or disable", DebugSeverities), AutoSize("ids")..GLsizei.IN("count", "the length of the array {@code ids}"), SingleValue("id")..const..GLuint_p.IN("ids", "an array of unsigned integers containing the ids of the messages to enable or disable"), GLboolean.IN("enabled", "whether the selected messages should be enabled or disabled") ) void( "DebugMessageInsert", """ This function can be called by applications and third-party libraries to generate their own messages, such as ones containing timestamp information or signals about specific render system events. The value of {@code id} specifies the ID for the message and {@code severity} indicates its severity level as defined by the caller. The string {@code buf} contains the string representation of the message. The parameter {@code length} contains the number of characters in {@code buf}. If {@code length} is negative, it is implied that {@code buf} contains a null terminated string. The error GLES20#INVALID_VALUE will be generated if the number of characters in {@code buf}, excluding the null terminator when {@code length} is negative, is not less than the value of #MAX_DEBUG_MESSAGE_LENGTH. If the #DEBUG_OUTPUT state is disabled calls to DebugMessageInsert are discarded and do not generate an error. """, GLenum.IN("source", "the source of the debug message to insert", DebugSources), GLenum.IN("type", "the type of the debug message insert", DebugTypes), GLuint.IN("id", "the user-supplied identifier of the message to insert", DebugSeverities), GLenum.IN("severity", "the severity of the debug messages to insert"), AutoSize("message")..GLsizei.IN("length", "the length of the string contained in the character array whose address is given by {@code message}"), const..GLcharUTF8_p.IN("message", "a character array containing the message to insert") ) void( "DebugMessageCallback", """ Specifies a callback to receive debugging messages from the GL. The function's prototype must follow the type definition of DEBUGPROC including its platform-dependent calling convention. Anything else will result in undefined behavior. Only one debug callback can be specified for the current context, and further calls overwrite the previous callback. Specifying $NULL as the value of {@code callback} clears the current callback and disables message output through callbacks. Applications can provide user-specified data through the pointer {@code userParam}. The context will store this pointer and will include it as one of the parameters in each call to the callback function. If the application has specified a callback function for receiving debug output, the implementation will call that function whenever any enabled message is generated. The source, type, ID, and severity of the message are specified by the DEBUGPROC parameters {@code source}, {@code type}, {@code id}, and {@code severity}, respectively. The string representation of the message is stored in {@code message} and its length (excluding the null-terminator) is stored in {@code length}. The parameter {@code userParam} is the user-specified parameter that was given when calling DebugMessageCallback. Applications can query the current callback function and the current user-specified parameter by obtaining the values of #DEBUG_CALLBACK_FUNCTION and #DEBUG_CALLBACK_USER_PARAM, respectively. Applications that specify a callback function must be aware of certain special conditions when executing code inside a callback when it is called by the GL, regardless of the debug source. The memory for {@code message} is owned and managed by the GL, and should only be considered valid for the duration of the function call. The behavior of calling any GL or window system function from within the callback function is undefined and may lead to program termination. Care must also be taken in securing debug callbacks for use with asynchronous debug output by multi-threaded GL implementations. If the #DEBUG_OUTPUT state is disabled then the GL will not call the callback function. """, nullable..GLDEBUGPROC.IN("callback", "a callback function that will be called when a debug message is generated"), nullable..const..voidptr.IN( "userParam", "a user supplied pointer that will be passed on each invocation of {@code callback}" ) ) GLuint( "GetDebugMessageLog", """ Retrieves messages from the debug message log. This function fetches a maximum of {@code count} messages from the message log, and will return the number of messages successfully fetched. Messages will be fetched from the log in order of oldest to newest. Those messages that were fetched will be removed from the log. The sources, types, severities, IDs, and string lengths of fetched messages will be stored in the application-provided arrays {@code sources}, {@code types}, {@code severities}, {@code ids}, and {@code lengths}, respectively. The application is responsible for allocating enough space for each array to hold up to {@code count} elements. The string representations of all fetched messages are stored in the {@code messageLog} array. If multiple messages are fetched, their strings are concatenated into the same {@code messageLog} array and will be separated by single null terminators. The last string in the array will also be null-terminated. The maximum size of {@code messageLog}, including the space used by all null terminators, is given by {@code bufSize}. If {@code bufSize} is less than zero and {@code messageLog} is not $NULL, an GLES20#INVALID_VALUE error will be generated. If a message's string, including its null terminator, can not fully fit within the {@code messageLog} array's remaining space, then that message and any subsequent messages will not be fetched and will remain in the log. The string lengths stored in the array {@code lengths} include the space for the null terminator of each string. Any or all of the arrays {@code sources}, {@code types}, {@code ids}, {@code severities}, {@code lengths} and {@code messageLog} can also be null pointers, which causes the attributes for such arrays to be discarded when messages are fetched, however those messages will still be removed from the log. Thus to simply delete up to {@code count} messages from the message log while ignoring their attributes, the application can call the function with null pointers for all attribute arrays. If the context was created without the #CONTEXT_FLAG_DEBUG_BIT, then the GL can opt to never add messages to the message log so GetDebugMessageLog will always return zero. """, GLuint.IN("count", "the number of debug messages to retrieve from the log"), AutoSize("messageLog")..GLsizei.IN("bufsize", "the size of the buffer whose address is given by {@code messageLog}"), Check("count")..nullable..GLenum_p.OUT("sources", "an array of variables to receive the sources of the retrieved messages"), Check("count")..nullable..GLenum_p.OUT("types", "an array of variables to receive the types of the retrieved messages"), Check("count")..nullable..GLuint_p.OUT("ids", "an array of unsigned integers to receive the ids of the retrieved messages"), Check("count")..nullable..GLenum_p.OUT("severities", "an array of variables to receive the severites of the retrieved messages"), Check("count")..nullable..GLsizei_p.OUT("lengths", "an array of variables to receive the lengths of the received messages"), nullable..GLcharUTF8_p.OUT("messageLog", "an array of characters that will receive the messages") ) void( "GetPointerv", "", GLenum.IN("pname", ""), ReturnParam..Check(1)..void_pp.OUT("params", "") ) void( "PushDebugGroup", """ Pushes a debug group described by the string {@code message} into the command stream. The value of {@code id} specifies the ID of messages generated. The parameter {@code length} contains the number of characters in {@code message}. If {@code length} is negative, it is implied that {@code message} contains a null terminated string. The message has the specified {@code source} and {@code id}, {@code type} #DEBUG_TYPE_PUSH_GROUP, and {@code severity} #DEBUG_SEVERITY_NOTIFICATION. The GL will put a new debug group on top of the debug group stack which inherits the control of the volume of debug output of the debug group previously residing on the top of the debug group stack. Because debug groups are strictly hierarchical, any additional control of the debug output volume will only apply within the active debug group and the debug groups pushed on top of the active debug group. An GLES20#INVALID_ENUM error is generated if the value of {@code source} is neither #DEBUG_SOURCE_APPLICATION nor #DEBUG_SOURCE_THIRD_PARTY. An GLES20#INVALID_VALUE error is generated if {@code length} is negative and the number of characters in {@code message}, excluding the null-terminator, is not less than the value of #MAX_DEBUG_MESSAGE_LENGTH. """, GLenum.IN("source", "the source of the debug message", "#DEBUG_SOURCE_APPLICATION #DEBUG_SOURCE_THIRD_PARTY"), GLuint.IN("id", "the identifier of the message"), AutoSize("message")..GLsizei.IN("length", "the length of the message to be sent to the debug output stream"), const..GLcharUTF8_p.IN("message", "a string containing the message to be sent to the debug output stream") ) void( "PopDebugGroup", """ Pops the active debug group. When a debug group is popped, the GL will also generate a debug output message describing its cause based on the {@code message} string, the source {@code source}, and an ID {@code id} submitted to the associated #PushDebugGroup() command. #DEBUG_TYPE_PUSH_GROUP and #DEBUG_TYPE_POP_GROUP share a single namespace for message {@code id}. {@code severity} has the value #DEBUG_SEVERITY_NOTIFICATION. The {@code type} has the value #DEBUG_TYPE_POP_GROUP. Popping a debug group restores the debug output volume control of the parent debug group. Attempting to pop the default debug group off the stack generates a #STACK_UNDERFLOW error; pushing a debug group onto a stack containing #MAX_DEBUG_GROUP_STACK_DEPTH minus one elements will generate a #STACK_OVERFLOW error. """ ) void( "ObjectLabel", "Labels a named object identified within a namespace.", GLenum.IN( "identifier", "the namespace from which the name of the object is allocated", DebugIdentifiers + " GLES20#TEXTURE GLES20#RENDERBUFFER GLES20#FRAMEBUFFER GLES30#TRANSFORM_FEEDBACK" ), GLuint.IN("name", "the name of the object to label"), AutoSize("label")..GLsizei.IN("length", "the length of the label to be used for the object"), const..GLcharUTF8_p.IN("label", "a string containing the label to assign to the object") ) void( "GetObjectLabel", "Retrieves the label of a named object identified within a namespace.", GLenum.IN( "identifier", "the namespace from which the name of the object is allocated", DebugIdentifiers + " GLES20#TEXTURE GLES20#RENDERBUFFER GLES20#FRAMEBUFFER GLES30#TRANSFORM_FEEDBACK" ), GLuint.IN("name", "the name of the object whose label to retrieve"), AutoSize("label")..GLsizei.IN("bufSize", "the length of the buffer whose address is in {@code label}"), Check(1)..nullable..GLsizei_p.OUT("length", "the address of a variable to receive the length of the object label"), Return("length", "GLES20.glGetInteger(GL_MAX_LABEL_LENGTH)")..GLcharUTF8_p.OUT("label", "a string that will receive the object label") ) void( "ObjectPtrLabel", "Labels a sync object identified by a pointer.", voidptr.IN("ptr", "a pointer identifying a sync object"), AutoSize("label")..GLsizei.IN("length", "the length of the label to be used for the object"), const..GLcharUTF8_p.IN("label", "a string containing the label to assign to the object") ) void( "GetObjectPtrLabel", "Retrieves the label of a sync object identified by a pointer.", voidptr.IN("ptr", "the name of the sync object whose label to retrieve"), AutoSize("label")..GLsizei.IN("bufSize", "the length of the buffer whose address is in {@code label}"), Check(1)..nullable..GLsizei_p.OUT("length", "a variable to receive the length of the object label"), Return("length", "GLES20.glGetInteger(GL_MAX_LABEL_LENGTH)")..GLcharUTF8_p.OUT("label", "a string that will receive the object label") ) // OES_draw_buffers_indexed void( "Enablei", "", GLenum.IN("target", ""), GLuint.IN("index", "") ) void( "Disablei", "", GLenum.IN("target", ""), GLuint.IN("index", "") ) void( "BlendEquationi", "", GLuint.IN("buf", ""), GLenum.IN("mode", "") ) void( "BlendEquationSeparatei", "", GLuint.IN("buf", ""), GLenum.IN("modeRGB", ""), GLenum.IN("modeAlpha", "") ) void( "BlendFunci", "", GLuint.IN("buf", ""), GLenum.IN("src", ""), GLenum.IN("dst", "") ) void( "BlendFuncSeparatei", "", GLuint.IN("buf", ""), GLenum.IN("srcRGB", ""), GLenum.IN("dstRGB", ""), GLenum.IN("srcAlpha", ""), GLenum.IN("dstAlpha", "") ) void( "ColorMaski", "", GLuint.IN("index", ""), GLboolean.IN("r", ""), GLboolean.IN("g", ""), GLboolean.IN("b", ""), GLboolean.IN("a", "") ) GLboolean( "IsEnabledi", "", GLenum.IN("target", ""), GLuint.IN("index", "") ) // OES_draw_elements_base_vertex void( "DrawElementsBaseVertex", "", GLenum.IN("mode", ""), AutoSizeShr("GLESChecks.typeToByteShift(type)", "indices")..GLsizei.IN("count", ""), AutoType("indices", GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT)..GLenum.IN("type", ""), ELEMENT_ARRAY_BUFFER..const..void_p.IN("indices", ""), GLint.IN("basevertex", "") ) void( "DrawRangeElementsBaseVertex", "", GLenum.IN("mode", ""), GLuint.IN("start", ""), GLuint.IN("end", ""), AutoSizeShr("GLESChecks.typeToByteShift(type)", "indices")..GLsizei.IN("count", ""), AutoType("indices", GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT)..GLenum.IN("type", ""), ELEMENT_ARRAY_BUFFER..const..void_p.IN("indices", ""), GLint.IN("basevertex", "") ) void( "DrawElementsInstancedBaseVertex", "", GLenum.IN("mode", ""), AutoSizeShr("GLESChecks.typeToByteShift(type)", "indices")..GLsizei.IN("count", ""), AutoType("indices", GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT)..GLenum.IN("type", ""), ELEMENT_ARRAY_BUFFER..const..void_p.IN("indices", ""), GLsizei.IN("instancecount", ""), GLint.IN("basevertex", "") ) // OES_geometry_shader IntConstant( """ Accepted by the {@code type} parameter of CreateShader and CreateShaderProgramv, by the {@code pname} parameter of GetProgramPipelineiv and returned in the {@code params} parameter of GetShaderiv when {@code pname} is SHADER_TYPE. """, "GEOMETRY_SHADER"..0x8DD9 ) IntConstant( "Accepted by the {@code stages} parameter of UseProgramStages.", "GEOMETRY_SHADER_BIT"..0x00000004 ) IntConstant( "Accepted by the {@code pname} parameter of GetProgramiv.", "GEOMETRY_LINKED_VERTICES_OUT"..0x8916, "GEOMETRY_LINKED_INPUT_TYPE"..0x8917, "GEOMETRY_LINKED_OUTPUT_TYPE"..0x8918, "GEOMETRY_SHADER_INVOCATIONS"..0x887F ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetInteger64v.", "LAYER_PROVOKING_VERTEX"..0x825E, "MAX_GEOMETRY_UNIFORM_COMPONENTS"..0x8DDF, "MAX_GEOMETRY_UNIFORM_BLOCKS"..0x8A2C, "MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS"..0x8A32, "MAX_GEOMETRY_INPUT_COMPONENTS"..0x9123, "MAX_GEOMETRY_OUTPUT_COMPONENTS"..0x9124, "MAX_GEOMETRY_OUTPUT_VERTICES"..0x8DE0, "MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS"..0x8DE1, "MAX_GEOMETRY_SHADER_INVOCATIONS"..0x8E5A, "MAX_GEOMETRY_TEXTURE_IMAGE_UNITS"..0x8C29, "MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS"..0x92CF, "MAX_GEOMETRY_ATOMIC_COUNTERS"..0x92D5, "MAX_GEOMETRY_IMAGE_UNIFORMS"..0x90CD, "MAX_GEOMETRY_SHADER_STORAGE_BLOCKS"..0x90D7 ) IntConstant( "Returned in the {@code data} parameter from a Get query with a {@code pname} of LAYER_PROVOKING_VERTEX.", "FIRST_VERTEX_CONVENTION"..0x8E4D, "LAST_VERTEX_CONVENTION"..0x8E4E, "UNDEFINED_VERTEX"..0x8260 ) IntConstant( "Accepted by the {@code target} parameter of BeginQuery, EndQuery, GetQueryiv, and GetQueryObjectuiv.", "PRIMITIVES_GENERATED"..0x8C87 ) IntConstant( "Accepted by the {@code mode} parameter of DrawArrays, DrawElements, and other commands which draw primitives.", "LINES_ADJACENCY"..0xA, "LINE_STRIP_ADJACENCY"..0xB, "TRIANGLES_ADJACENCY"..0xC, "TRIANGLE_STRIP_ADJACENCY"..0xD ) IntConstant( "Accepted by the {@code pname} parameter of FramebufferParameteri, and GetFramebufferParameteriv.", "FRAMEBUFFER_DEFAULT_LAYERS"..0x9312 ) IntConstant( "Accepted by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetInteger64v, and GetFloatv.", "MAX_FRAMEBUFFER_LAYERS"..0x9317 ) IntConstant( "Returned by CheckFramebufferStatus.", "FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"..0x8DA8 ) IntConstant( "Accepted by the {@code pname} parameter of GetFramebufferAttachmentParameteriv.", "FRAMEBUFFER_ATTACHMENT_LAYERED"..0x8DA7 ) IntConstant( "Accepted by the {@code props} parameter of GetProgramResourceiv.", "REFERENCED_BY_GEOMETRY_SHADER"..0x9309 ) void( "FramebufferTexture", "", GLenum.IN("target", ""), GLenum.IN("attachment", ""), GLuint.IN("texture", ""), GLint.IN("level", "") ) // OES_primitive_bounding_box IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.", "PRIMITIVE_BOUNDING_BOX_ARB"..0x92BE ) void( "PrimitiveBoundingBox", """ Specifies the primitive bounding box. Implementations may be able to optimize performance if the application provides bounds of primitives that will be generated by the tessellation primitive generator or the geometry shader prior to executing those stages. If the provided bounds are incorrect and primitives extend beyond them, the rasterizer may or may not generate fragments for the portions of primitives outside the bounds. """, GLfloat.IN("minX", "the minimum x clip space coordinate"), GLfloat.IN("minY", "the minimum y clip space coordinate"), GLfloat.IN("minZ", "the minimum z clip space coordinate"), GLfloat.IN("minW", "the minimum w clip space coordinate"), GLfloat.IN("maxX", "the maximum x clip space coordinate"), GLfloat.IN("maxY", "the maximum y clip space coordinate"), GLfloat.IN("maxZ", "the maximum z clip space coordinate"), GLfloat.IN("maxW", "the maximum w clip space coordinate") ) // KHR_robustness IntConstant( "Returned by #GetGraphicsResetStatus().", "NO_ERROR"..0x0000, "GUILTY_CONTEXT_RESET"..0x8253, "INNOCENT_CONTEXT_RESET"..0x8254, "UNKNOWN_CONTEXT_RESET"..0x8255 ) IntConstant( "Accepted by the {@code value} parameter of GetBooleanv, GetIntegerv, and GetFloatv.", "CONTEXT_ROBUST_ACCESS"..0x90F3, "RESET_NOTIFICATION_STRATEGY"..0x8256 ) IntConstant( "Returned by GetIntegerv and related simple queries when {@code value} is #RESET_NOTIFICATION_STRATEGY.", "LOSE_CONTEXT_ON_RESET"..0x8252, "NO_RESET_NOTIFICATION"..0x8261 ) IntConstant( "Returned by GLES20#GetError().", "CONTEXT_LOST"..0x0507 ) GLenum( "GetGraphicsResetStatus", """ Indicates if the GL context has been in a reset state at any point since the last call to GetGraphicsResetStatus: ${ul( "GLES20#NO_ERROR indicates that the GL context has not been in a reset state since the last call.", "#GUILTY_CONTEXT_RESET indicates that a reset has been detected that is attributable to the current GL context.", "#INNOCENT_CONTEXT_RESET indicates a reset has been detected that is not attributable to the current GL context.", "#UNKNOWN_CONTEXT_RESET indicates a detected graphics reset whose cause is unknown." )} If a reset status other than NO_ERROR is returned and subsequent calls return NO_ERROR, the context reset was encountered and completed. If a reset status is repeatedly returned, the context may be in the process of resetting. Reset notification behavior is determined at context creation time, and may be queried by calling GetIntegerv with the symbolic constant #RESET_NOTIFICATION_STRATEGY. If the reset notification behavior is #NO_RESET_NOTIFICATION, then the implementation will never deliver notification of reset events, and GetGraphicsResetStatus will always return NO_ERROR. If the behavior is #LOSE_CONTEXT_ON_RESET, a graphics reset will result in a lost context and require creating a new context as described above. In this case GetGraphicsResetStatus will return an appropriate value from those described above. If a graphics reset notification occurs in a context, a notification must also occur in all other contexts which share objects with that context. After a graphics reset has occurred on a context, subsequent GL commands on that context (or any context which shares with that context) will generate a #CONTEXT_LOST error. Such commands will not have side effects (in particular, they will not modify memory passed by pointer for query results, and may not block indefinitely or cause termination of the application. Exceptions to this behavior include: ${ul( """ GLES20#GetError() and GetGraphicsResetStatus behave normally following a graphics reset, so that the application can determine a reset has occurred, and when it is safe to destroy and recreate the context. """, """ Any commands which might cause a polling application to block indefinitely will generate a CONTEXT_LOST error, but will also return a value indicating completion to the application. """ )} """ ) void( "ReadnPixels", "Behaves identically to GLES20#ReadPixels() except that it does not write more than {@code bufSize} bytes into {@code data}", GLint.IN("x", "the left pixel coordinate"), GLint.IN("y", "the lower pixel coordinate"), GLsizei.IN("width", "the number of pixels to read in the x-dimension"), GLsizei.IN("height", "the number of pixels to read in the y-dimension"), GLenum.IN("format", "the pixel format"), GLenum.IN("type", "the pixel type"), AutoSize("pixels")..GLsizei.IN("bufSize", "the maximum number of bytes to write into {@code data}"), PIXEL_PACK_BUFFER..MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT )..void_p.OUT("pixels", "a buffer in which to place the returned pixel data") ) void( "GetnUniformfv", "Returns the value or values of a uniform of the default uniform block.", GLuint.IN("program", "the program object"), GLint.IN("location", "the uniform location"), AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of bytes to write to {@code params}"), ReturnParam..GLfloat_p.OUT("params", "the buffer in which to place the returned data") ) void( "GetnUniformiv", "Integer version of #GetnUniformfv().", GLuint.IN("program", "the program object"), GLint.IN("location", "the uniform location"), AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of bytes to write to {@code params}"), ReturnParam..GLfloat_p.OUT("params", "the buffer in which to place the returned data") ) void( "GetnUniformuiv", "Unsigned version of #GetnUniformiv().", GLuint.IN("program", "the program object"), GLint.IN("location", "the uniform location"), AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of bytes to write to {@code params}"), ReturnParam..GLfloat_p.OUT("params", "the buffer in which to place the returned data") ) // OES_sample_shading IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetInteger64v. """, "SAMPLE_SHADING"..0x8C36 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetInteger64v, and GetFloatv.", "MIN_SAMPLE_SHADING_VALUE"..0x8C37 ) void( "MinSampleShading", "", GLfloat.IN("value", "") ) // OES_multisample_interpolation_features IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetInteger64v.", "MIN_FRAGMENT_INTERPOLATION_OFFSET"..0x8E5B, "MAX_FRAGMENT_INTERPOLATION_OFFSET"..0x8E5C, "FRAGMENT_INTERPOLATION_OFFSET_BITS"..0x8E5D ) // OES_tessellation_shader IntConstant( "Accepted by the {@code mode} parameter of DrawArrays, DrawElements, and other commands which draw primitives.", "PATCHES"..0xE ) IntConstant( "Accepted by the {@code pname} parameter of PatchParameteri, GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.", "PATCH_VERTICES"..0x8E72 ) IntConstant( "Accepted by the {@code pname} parameter of GetProgramiv.", "TESS_CONTROL_OUTPUT_VERTICES"..0x8E75, "TESS_GEN_MODE"..0x8E76, "TESS_GEN_SPACING"..0x8E77, "TESS_GEN_VERTEX_ORDER"..0x8E78, "TESS_GEN_POINT_MODE"..0x8E79 ) IntConstant( "Returned by GetProgramiv when {@code pname} is TESS_GEN_MODE.", "ISOLINES"..0x8E7A, "QUADS"..0x0007 ) IntConstant( "Returned by GetProgramiv when {@code pname} is TESS_GEN_SPACING.", "FRACTIONAL_ODD"..0x8E7B, "FRACTIONAL_EVEN"..0x8E7C ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v.", "MAX_PATCH_VERTICES"..0x8E7D, "MAX_TESS_GEN_LEVEL"..0x8E7E, "MAX_TESS_CONTROL_UNIFORM_COMPONENTS"..0x8E7F, "MAX_TESS_EVALUATION_UNIFORM_COMPONENTS"..0x8E80, "MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS"..0x8E81, "MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS"..0x8E82, "MAX_TESS_CONTROL_OUTPUT_COMPONENTS"..0x8E83, "MAX_TESS_PATCH_COMPONENTS"..0x8E84, "MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS"..0x8E85, "MAX_TESS_EVALUATION_OUTPUT_COMPONENTS"..0x8E86, "MAX_TESS_CONTROL_UNIFORM_BLOCKS"..0x8E89, "MAX_TESS_EVALUATION_UNIFORM_BLOCKS"..0x8E8A, "MAX_TESS_CONTROL_INPUT_COMPONENTS"..0x886C, "MAX_TESS_EVALUATION_INPUT_COMPONENTS"..0x886D, "MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS"..0x8E1E, "MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS"..0x8E1F, "MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS"..0x92CD, "MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS"..0x92CE, "MAX_TESS_CONTROL_ATOMIC_COUNTERS"..0x92D3, "MAX_TESS_EVALUATION_ATOMIC_COUNTERS"..0x92D4, "MAX_TESS_CONTROL_IMAGE_UNIFORMS"..0x90CB, "MAX_TESS_EVALUATION_IMAGE_UNIFORMS"..0x90CC, "MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS"..0x90D8, "MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS"..0x90D9, "PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED"..0x8221 ) IntConstant( "Accepted by the {@code props} parameter of GetProgramResourceiv.", "IS_PER_PATCH"..0x92E7, "REFERENCED_BY_TESS_CONTROL_SHADER"..0x9307, "REFERENCED_BY_TESS_EVALUATION_SHADER"..0x9308 ) IntConstant( """ Accepted by the {@code type} parameter of CreateShader, by the {@code pname} parameter of GetProgramPipelineiv, and returned by the {@code params} parameter of GetShaderiv. """, "TESS_EVALUATION_SHADER"..0x8E87, "TESS_CONTROL_SHADER"..0x8E88 ) IntConstant( "Accepted by the {@code stages} parameter of UseProgramStages.", "TESS_CONTROL_SHADER_BIT"..0x00000008, "TESS_EVALUATION_SHADER_BIT"..0x00000010 ) void( "PatchParameteri", "", GLenum.IN("pname", ""), GLint.IN("value", "") ) // OES_texture_border_clamp IntConstant( """ Accepted by the {@code pname} parameter of TexParameteriv, TexParameterfv, SamplerParameteriv, SamplerParameterfv, TexParameterIiv, TexParameterIuiv, SamplerParameterIiv, SamplerParameterIuiv, GetTexParameteriv, GetTexParameterfv, GetTexParameterIiv, GetTexParameterIuiv, GetSamplerParameteriv, GetSamplerParameterfv, GetSamplerParameterIiv, and GetSamplerParameterIuiv. """, "TEXTURE_BORDER_COLOR"..0x1004 ) IntConstant( """ Accepted by the {@code param} parameter of TexParameteri, TexParameterf, SamplerParameteri and SamplerParameterf, and by the {@code params} parameter of TexParameteriv, TexParameterfv, TexParameterIiv, TexParameterIuiv, SamplerParameterIiv, SamplerParameterIuiv and returned by the {@code params} parameter of GetTexParameteriv, GetTexParameterfv, GetTexParameterIiv, GetTexParameterIuiv, GetSamplerParameteriv, GetSamplerParameterfv, GetSamplerParameterIiv, and GetSamplerParameterIuiv when their {@code pname} parameter is TEXTURE_WRAP_S, TEXTURE_WRAP_T, or TEXTURE_WRAP_R. """, "CLAMP_TO_BORDER"..0x812D ) void( "TexParameterIiv", "", GLenum.IN("target", ""), GLenum.IN("pname", ""), SingleValue("param")..const..GLint_p.IN("params", "") ) void( "TexParameterIuiv", "", GLenum.IN("target", ""), GLenum.IN("pname", ""), SingleValue("param")..const..GLuint_p.IN("params", "") ) void( "GetTexParameterIiv", "", GLenum.IN("target", ""), GLenum.IN("pname", ""), ReturnParam..Check(1)..GLint_p.OUT("params", "") ) void( "GetTexParameterIuiv", "", GLenum.IN("target", ""), GLenum.IN("pname", ""), ReturnParam..Check(1)..GLuint_p.OUT("params", "") ) void( "SamplerParameterIiv", "", GLuint.IN("sampler", ""), GLenum.IN("pname", ""), SingleValue("param")..const..GLint_p.IN("params", "") ) void( "SamplerParameterIuiv", "", GLuint.IN("sampler", ""), GLenum.IN("pname", ""), SingleValue("param")..const..GLuint_p.IN("params", "") ) void( "GetSamplerParameterIiv", "", GLuint.IN("sampler", ""), GLenum.IN("pname", ""), ReturnParam..Check(1)..GLint_p.OUT("params", "") ) void( "GetSamplerParameterIuiv", "", GLuint.IN("sampler", ""), GLenum.IN("pname", ""), ReturnParam..Check(1)..GLuint_p.OUT("params", "") ) // OES_texture_buffer IntConstant( """ Accepted by the {@code target} parameter of BindBuffer, BufferData, BufferSubData, MapBufferRange, BindTexture, UnmapBuffer, GetBufferParameteriv, GetBufferPointerv, TexBuffer, and TexBufferRange. """, "TEXTURE_BUFFER"..0x8C2A ) IntConstant( "Accepted by the {@code pname} parameters of GetBooleanv, GetFloatv, and GetIntegerv.", "TEXTURE_BUFFER_BINDING"..0x8C2A ) IntConstant( """ (note that this token name is an alias for TEXTURE_BUFFER, and is used for naming consistency with queries for the buffers bound to other buffer binding points). MAX_TEXTURE_BUFFER_SIZE 0x8C2B TEXTURE_BINDING_BUFFER 0x8C2C TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F Returned in the {@code type} parameter of GetActiveUniform, the {@code params} parameter of GetActiveUniformsiv, and the {@code params} parameter of GetProgramResourceiv when the TYPE property is queried on the UNIFORM interface. """, "SAMPLER_BUFFER"..0x8DC2, "INT_SAMPLER_BUFFER"..0x8DD0, "UNSIGNED_INT_SAMPLER_BUFFER"..0x8DD8, "IMAGE_BUFFER"..0x9051, "INT_IMAGE_BUFFER"..0x905C, "UNSIGNED_INT_IMAGE_BUFFER"..0x9067 ) IntConstant( "Accepted by the {@code pname} parameter of GetTexLevelParameter.", "TEXTURE_BUFFER_DATA_STORE_BINDING"..0x8C2D, "TEXTURE_BUFFER_OFFSET"..0x919D, "TEXTURE_BUFFER_SIZE"..0x919E ) void( "TexBuffer", "", GLenum.IN("target", ""), GLenum.IN("internalformat", ""), GLuint.IN("buffer", "") ) void( "TexBufferRange", "", GLenum.IN("target", ""), GLenum.IN("internalformat", ""), GLuint.IN("buffer", ""), GLintptr.IN("offset", ""), GLsizeiptr.IN("size", "") ) // KHR_texture_compression_astc_ldr IntConstant( """ Accepted by the {@code internalformat} parameter of CompressedTexImage2D, CompressedTexSubImage2D, TexStorage2D, TextureStorage2D, TexStorage3D, and TextureStorage3D. """, "COMPRESSED_RGBA_ASTC_4x4"..0x93B0, "COMPRESSED_RGBA_ASTC_5x4"..0x93B1, "COMPRESSED_RGBA_ASTC_5x5"..0x93B2, "COMPRESSED_RGBA_ASTC_6x5"..0x93B3, "COMPRESSED_RGBA_ASTC_6x6"..0x93B4, "COMPRESSED_RGBA_ASTC_8x5"..0x93B5, "COMPRESSED_RGBA_ASTC_8x6"..0x93B6, "COMPRESSED_RGBA_ASTC_8x8"..0x93B7, "COMPRESSED_RGBA_ASTC_10x5"..0x93B8, "COMPRESSED_RGBA_ASTC_10x6"..0x93B9, "COMPRESSED_RGBA_ASTC_10x8"..0x93BA, "COMPRESSED_RGBA_ASTC_10x10"..0x93BB, "COMPRESSED_RGBA_ASTC_12x10"..0x93BC, "COMPRESSED_RGBA_ASTC_12x12"..0x93BD, "COMPRESSED_SRGB8_ALPHA8_ASTC_4x4"..0x93D0, "COMPRESSED_SRGB8_ALPHA8_ASTC_5x4"..0x93D1, "COMPRESSED_SRGB8_ALPHA8_ASTC_5x5"..0x93D2, "COMPRESSED_SRGB8_ALPHA8_ASTC_6x5"..0x93D3, "COMPRESSED_SRGB8_ALPHA8_ASTC_6x6"..0x93D4, "COMPRESSED_SRGB8_ALPHA8_ASTC_8x5"..0x93D5, "COMPRESSED_SRGB8_ALPHA8_ASTC_8x6"..0x93D6, "COMPRESSED_SRGB8_ALPHA8_ASTC_8x8"..0x93D7, "COMPRESSED_SRGB8_ALPHA8_ASTC_10x5"..0x93D8, "COMPRESSED_SRGB8_ALPHA8_ASTC_10x6"..0x93D9, "COMPRESSED_SRGB8_ALPHA8_ASTC_10x8"..0x93DA, "COMPRESSED_SRGB8_ALPHA8_ASTC_10x10"..0x93DB, "COMPRESSED_SRGB8_ALPHA8_ASTC_12x10"..0x93DC, "COMPRESSED_SRGB8_ALPHA8_ASTC_12x12"..0x93DD ) // OES_texture_cube_map_array IntConstant( """ Accepted by the {@code target} parameter of TexParameter{if}, TexParameter{if}v, TexParameterI{i ui}v, BindTexture, GenerateMipmap, TexImage3D, TexSubImage3D, TexStorage3D, GetTexParameter{if}v, GetTexParameter{i ui}v, GetTexLevelParameter{if}v, CompressedTexImage3D, CompressedTexSubImage3D and CopyTexSubImage3D. """, "TEXTURE_CUBE_MAP_ARRAY"..0x9009 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv and GetFloatv.", "TEXTURE_BINDING_CUBE_MAP_ARRAY"..0x900A ) IntConstant( "Returned by the {@code type} parameter of GetActiveUniform, and by the {@code params} parameter of GetProgramResourceiv when {@code props} is TYPE.", "SAMPLER_CUBE_MAP_ARRAY"..0x900C, "SAMPLER_CUBE_MAP_ARRAY_SHADOW"..0x900D, "INT_SAMPLER_CUBE_MAP_ARRAY"..0x900E, "UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY"..0x900F, "IMAGE_CUBE_MAP_ARRAY"..0x9054, "INT_IMAGE_CUBE_MAP_ARRAY"..0x905F, "UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY"..0x906A ) // OES_texture_storage_multisample_2d_array IntConstant( """ Accepted by the {@code target} parameter of BindTexture, TexStorage3DMultisample, GetInternalformativ, TexParameter{if}*, GetTexParameter{if}v and GetTexLevelParameter{if}v. Also, the texture object indicated by the {@code texture} argument to FramebufferTextureLayer can be TEXTURE_2D_MULTISAMPLE_ARRAY. """, "TEXTURE_2D_MULTISAMPLE_ARRAY"..0x9102 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, and GetFloatv.", "TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY"..0x9105 ) IntConstant( "Returned by the {@code type} parameter of GetActiveUniform.", "SAMPLER_2D_MULTISAMPLE_ARRAY"..0x910B, "INT_SAMPLER_2D_MULTISAMPLE_ARRAY"..0x910C, "UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY"..0x910D ) void( "TexStorage3DMultisample", "", GLenum.IN("target", ""), GLsizei.IN("samples", ""), GLenum.IN("internalformat", ""), GLsizei.IN("width", ""), GLsizei.IN("height", ""), GLsizei.IN("depth", ""), GLboolean.IN("fixedsamplelocations", "") ) }
bsd-3-clause
bb660b7f2341715524ec5f542102b191
34.740458
171
0.723189
3.495106
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/insight/ColorLineMarkerProvider.kt
1
5998
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.insight import com.demonwav.mcdev.MinecraftSettings import com.intellij.codeInsight.daemon.GutterIconNavigationHandler import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo import com.intellij.codeInsight.daemon.NavigateAction import com.intellij.codeInsight.hint.HintManager import com.intellij.icons.AllIcons import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.JVMElementFactories import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiEditorUtil import com.intellij.ui.ColorChooser import com.intellij.util.FunctionUtil import com.intellij.util.ui.ColorIcon import com.intellij.util.ui.ColorsIcon import java.awt.Color import javax.swing.Icon import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UIdentifier import org.jetbrains.uast.ULiteralExpression import org.jetbrains.uast.toUElementOfType class ColorLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { if (!MinecraftSettings.instance.isShowChatColorGutterIcons) { return null } val identifier = element.toUElementOfType<UIdentifier>() ?: return null val info = identifier.findColor { map, chosen -> ColorInfo(element, chosen.value, map, chosen.key, identifier) } if (info != null) { NavigateAction.setNavigateAction(info, "Change Color", null) } return info } open class ColorInfo : MergeableLineMarkerInfo<PsiElement> { protected val color: Color constructor( element: PsiElement, color: Color, map: Map<String, Color>, colorName: String, workElement: UElement ) : super( element, element.textRange, ColorIcon(12, color), FunctionUtil.nullConstant<Any, String>(), GutterIconNavigationHandler handler@{ _, psiElement -> if (psiElement == null || !psiElement.isWritable || !psiElement.isValid || !workElement.isPsiValid) { return@handler } val editor = PsiEditorUtil.findEditor(psiElement) ?: return@handler val picker = ColorPicker(map, editor.component) val newColor = picker.showDialog() if (newColor != null && map[newColor] != color) { workElement.setColor(newColor) } }, GutterIconRenderer.Alignment.RIGHT, { "$colorName color indicator" } ) { this.color = color } constructor(element: PsiElement, color: Color, handler: GutterIconNavigationHandler<PsiElement>) : super( element, element.textRange, ColorIcon(12, color), FunctionUtil.nullConstant<Any, String>(), handler, GutterIconRenderer.Alignment.RIGHT, { "color indicator" } ) { this.color = color } override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is ColorInfo override fun getCommonIconAlignment(infos: List<MergeableLineMarkerInfo<*>>) = GutterIconRenderer.Alignment.RIGHT override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<*>>): Icon { if (infos.size == 2 && infos[0] is ColorInfo && infos[1] is ColorInfo) { return ColorsIcon(12, (infos[0] as ColorInfo).color, (infos[1] as ColorInfo).color) } return AllIcons.Gutter.Colors } override fun getCommonTooltip(infos: List<MergeableLineMarkerInfo<*>>) = FunctionUtil.nullConstant<PsiElement, String>() } class CommonColorInfo( element: PsiElement, color: Color, workElement: UElement ) : ColorLineMarkerProvider.ColorInfo( element, color, GutterIconNavigationHandler handler@{ _, psiElement -> if (psiElement == null || !psiElement.isValid || !workElement.isPsiValid || workElement.sourcePsi?.isWritable != true ) { return@handler } val editor = PsiEditorUtil.findEditor(psiElement) ?: return@handler if (JVMElementFactories.getFactory(psiElement.language, psiElement.project) == null) { // The setColor methods used here require a JVMElementFactory. Unfortunately the Kotlin plugin does not // implement it yet. It is better to not display the color chooser at all than deceiving users after // after they chose a color HintManager.getInstance() .showErrorHint(editor, "Can't change colors in " + psiElement.language.displayName) return@handler } val c = ColorChooser.chooseColor(psiElement.project, editor.component, "Choose Color", color, false) ?: return@handler when (workElement) { is ULiteralExpression -> workElement.setColor(c.rgb and 0xFFFFFF) is UCallExpression -> workElement.setColor(c.red, c.green, c.blue) } } ) abstract class CommonLineMarkerProvider : LineMarkerProvider { override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { val pair = findColor(element) ?: return null val info = CommonColorInfo(element, pair.first, pair.second) NavigateAction.setNavigateAction(info, "Change color", null) return info } abstract fun findColor(element: PsiElement): Pair<Color, UElement>? } }
mit
5bea13e70bb8b67d8436ebe80433ffd8
36.962025
120
0.642881
5.083051
false
false
false
false
wordpress-mobile/AztecEditor-Android
wordpress-comments/src/main/java/org/wordpress/aztec/plugins/wpcomments/spans/GutenbergCommentSpan.kt
1
725
package org.wordpress.aztec.plugins.wpcomments.spans import org.wordpress.aztec.AztecAttributes import org.wordpress.aztec.ITextFormat import org.wordpress.aztec.spans.IAztecBlockSpan class GutenbergCommentSpan( override val startTag: String, override var nestingLevel: Int, override var attributes: AztecAttributes = AztecAttributes() ) : IAztecBlockSpan { override val TAG: String = "wp:" override var startBeforeCollapse: Int = -1 override var endBeforeBleed: Int = -1 private var _endTag: String = super.endTag override var endTag: String get() = _endTag set(value) { _endTag = value } override val textFormat: ITextFormat? = null }
mpl-2.0
4e73b20fd71fd334f4e29da2eb5f6b4a
29.208333
68
0.70069
4.166667
false
false
false
false
arkon/LISTEN.moe-Unofficial-Android-App
app/src/main/java/me/echeung/moemoekyun/ui/activity/SettingsActivity.kt
1
2847
package me.echeung.moemoekyun.ui.activity import android.content.Intent import android.os.Bundle import android.view.View import androidx.core.app.TaskStackBuilder import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager import me.echeung.moemoekyun.R import me.echeung.moemoekyun.ui.base.BaseActivity import me.echeung.moemoekyun.util.PreferenceUtil class SettingsActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) initAppbar() supportFragmentManager.beginTransaction() .replace(R.id.content_frame, SettingsFragment()) .commit() } class SettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.pref_general) addPreferencesFromResource(R.xml.pref_music) addPreferencesFromResource(R.xml.pref_audio) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) invalidateSettings() } private fun invalidateSettings() { val languageSetting = findPreference<ListPreference>(PreferenceUtil.PREF_GENERAL_LANGUAGE)!! setSummary(languageSetting) languageSetting.setOnPreferenceChangeListener { _, o -> setSummary(languageSetting, o) recreateBackStack() true } } private fun setSummary(preference: Preference, value: Any = getPreferenceValue(preference)) { val stringValue = value.toString() if (preference is ListPreference) { val index = preference.findIndexOfValue(stringValue) preference.setSummary( if (index >= 0) { preference.entries[index] } else { null } ) } else { preference.summary = stringValue } } private fun getPreferenceValue(preference: Preference): String { return PreferenceManager .getDefaultSharedPreferences(preference.context) .getString(preference.key, "")!! } private fun recreateBackStack() { val activity = requireActivity() TaskStackBuilder.create(activity) .addNextIntent(Intent(activity, MainActivity::class.java)) .addNextIntent(activity.intent) .startActivities() } } }
mit
96eb986dda38828cdcc090c8f0ab8a17
33.719512
104
0.628381
5.845996
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/procdebuggers/utils/DefaultRespondent.kt
1
3041
package org.jetbrains.haskell.debugger.procdebuggers.utils import org.jetbrains.haskell.debugger.HaskellDebugProcess import org.jetbrains.haskell.debugger.frames.HsSuspendContext import org.jetbrains.haskell.debugger.utils.HaskellUtils import com.intellij.openapi.vfs.LocalFileSystem import org.jetbrains.haskell.debugger.frames.HsHistoryFrame import org.jetbrains.haskell.debugger.parser.HistoryResult import org.jetbrains.haskell.debugger.parser.HsHistoryFrameInfo import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointDescription public class DefaultRespondent(val debugProcess: HaskellDebugProcess) : DebugRespondent { private val session = debugProcess.getSession()!! override fun traceFinished() = debugProcess.traceFinished() override fun positionReached(context: HsSuspendContext) = session.positionReached(context) override fun breakpointReached(breakpoint: HaskellLineBreakpointDescription, context: HsSuspendContext) { val realBreakpoint = debugProcess.getBreakpointAtPosition(breakpoint.module, breakpoint.line) if (realBreakpoint == null) { session.positionReached(context) } else { session.breakpointReached(realBreakpoint, realBreakpoint.getLogExpression(), context) } } override fun exceptionReached(context: HsSuspendContext) { val breakpoint = debugProcess.exceptionBreakpoint if (breakpoint == null) { session.positionReached(context) } else { session.breakpointReached(breakpoint, breakpoint.getLogExpression(), context) } } override fun breakpointRemoved() { } override fun getBreakpointAt(module: String, line: Int): HaskellLineBreakpointDescription? { val breakpoint = debugProcess.getBreakpointAtPosition(module, line) if (breakpoint == null) { return null } else { return HaskellLineBreakpointDescription(module, line, breakpoint.getCondition()) } } override fun setBreakpointNumberAt(breakpointNumber: Int, module: String, line: Int) = debugProcess.setBreakpointNumberAtLine(breakpointNumber, module, line) override fun resetHistoryStack() {}//= debugProcess.historyManager.resetHistoryStack() override fun historyChange(currentFrame: HsHistoryFrame, history: HistoryResult?) { //debugProcess.historyManager.historyFrameAppeared(currentFrame) //if (history != null) { // debugProcess.historyManager.setHistoryFramesInfo( // HsHistoryFrameInfo(0, currentFrame.stackFrameInfo.functionName, // currentFrame.stackFrameInfo.filePosition), history.frames, history.full) //} //debugProcess.historyManager.historyChanged(false, true, currentFrame) } override fun getModuleByFile(filename: String): String = HaskellUtils.getModuleName(session.getProject(), LocalFileSystem.getInstance()!!.findFileByPath(filename)!!) }
apache-2.0
7d2fe2bb6054a2e2cf83af1c60d30d5b
44.402985
120
0.728379
5.216123
false
false
false
false
pbauerochse/youtrack-worklog-viewer
application/src/main/java/de/pbauerochse/worklogviewer/settings/SettingsViewModel.kt
1
12381
package de.pbauerochse.worklogviewer.settings import de.pbauerochse.worklogviewer.datasource.DataSources import de.pbauerochse.worklogviewer.fx.ConnectorDescriptor import de.pbauerochse.worklogviewer.fx.Theme import de.pbauerochse.worklogviewer.timerange.TimerangeProvider import de.pbauerochse.worklogviewer.toURL import javafx.beans.binding.BooleanBinding import javafx.beans.property.* import javafx.beans.value.ChangeListener import javafx.scene.input.KeyCombination import java.time.DayOfWeek.* import java.time.LocalDate /** * Java FX Model for the settings screen */ class SettingsViewModel internal constructor(val settings: Settings) { val youTrackUrlProperty = SimpleStringProperty() val youTrackConnectorProperty = SimpleObjectProperty<ConnectorDescriptor>() val youTrackUsernameProperty = SimpleStringProperty() val youTrackPermanentTokenProperty = SimpleStringProperty() val themeProperty = SimpleObjectProperty<Theme>() val workhoursProperty = SimpleFloatProperty() val showAllWorklogsProperty = SimpleBooleanProperty() val showStatisticsProperty = SimpleBooleanProperty() val statisticsPaneDividerPosition = SimpleDoubleProperty() val loadDataAtStartupProperty = SimpleBooleanProperty() val showDecimalsInExcelProperty = SimpleBooleanProperty() val enablePluginsProperty = SimpleBooleanProperty() val lastUsedReportTimerangeProperty = SimpleObjectProperty<TimerangeProvider>() val startDateProperty = SimpleObjectProperty<LocalDate>() val endDateProperty = SimpleObjectProperty<LocalDate>() val lastUsedGroupByCategoryIdProperty = SimpleStringProperty() val lastUsedFilePath = SimpleStringProperty() val collapseStateMondayProperty = SimpleBooleanProperty() val collapseStateTuesdayProperty = SimpleBooleanProperty() val collapseStateWednesdayProperty = SimpleBooleanProperty() val collapseStateThursdayProperty = SimpleBooleanProperty() val collapseStateFridayProperty = SimpleBooleanProperty() val collapseStateSaturdayProperty = SimpleBooleanProperty() val collapseStateSundayProperty = SimpleBooleanProperty() val highlightStateMondayProperty = SimpleBooleanProperty() val highlightStateTuesdayProperty = SimpleBooleanProperty() val highlightStateWednesdayProperty = SimpleBooleanProperty() val highlightStateThursdayProperty = SimpleBooleanProperty() val highlightStateFridayProperty = SimpleBooleanProperty() val highlightStateSaturdayProperty = SimpleBooleanProperty() val highlightStateSundayProperty = SimpleBooleanProperty() // search result val showTagsInSearchResults = SimpleBooleanProperty() val showFieldsInSearchResults = SimpleBooleanProperty() val showDescriptionInSearchResults = SimpleBooleanProperty() val hasMissingConnectionSettings = hasMissingConnectionSettingsBinding // shortcuts val fetchWorklogsKeyboardCombination = SimpleObjectProperty<KeyCombination>() val showIssueSearchKeyboardCombination = SimpleObjectProperty<KeyCombination>() val toggleStatisticsKeyboardCombination = SimpleObjectProperty<KeyCombination>() val showSettingsKeyboardCombination = SimpleObjectProperty<KeyCombination>() val exitWorklogViewerKeyboardCombination = SimpleObjectProperty<KeyCombination>() // overtime statistics var overtimeStatisticsIgnoreWeekendsProperty = SimpleBooleanProperty() var overtimeStatisticsIgnoreWithoutTimeEntriesProperty = SimpleBooleanProperty() var overtimeStatisticsIgnoreTodayProperty = SimpleBooleanProperty() init { applyPropertiesFromSettings() bindAutoUpdatingProperties() } fun saveChanges() { settings.youTrackConnectionSettings.baseUrl = youTrackUrlProperty.get().toURL() settings.youTrackConnectionSettings.selectedConnectorId = youTrackConnectorProperty.get().id settings.youTrackConnectionSettings.username = youTrackUsernameProperty.get() settings.youTrackConnectionSettings.permanentToken = youTrackPermanentTokenProperty.get() settings.theme = themeProperty.get() settings.workHoursADay = workhoursProperty.get() settings.isShowAllWorklogs = showAllWorklogsProperty.get() settings.isShowStatistics = showStatisticsProperty.get() settings.isLoadDataAtStartup = loadDataAtStartupProperty.get() settings.isShowDecimalHourTimesInExcelReport = showDecimalsInExcelProperty.get() settings.isEnablePlugins = enablePluginsProperty.get() settings.lastUsedReportTimerange = lastUsedReportTimerangeProperty.get() settings.startDate = startDateProperty.get() settings.endDate = endDateProperty.get() settings.lastUsedGroupByCategoryId = lastUsedGroupByCategoryIdProperty.get() settings.collapseState.set(MONDAY, collapseStateMondayProperty.get()) settings.collapseState.set(TUESDAY, collapseStateTuesdayProperty.get()) settings.collapseState.set(WEDNESDAY, collapseStateWednesdayProperty.get()) settings.collapseState.set(THURSDAY, collapseStateThursdayProperty.get()) settings.collapseState.set(FRIDAY, collapseStateFridayProperty.get()) settings.collapseState.set(SATURDAY, collapseStateSaturdayProperty.get()) settings.collapseState.set(SUNDAY, collapseStateSundayProperty.get()) settings.highlightState.set(MONDAY, highlightStateMondayProperty.get()) settings.highlightState.set(TUESDAY, highlightStateTuesdayProperty.get()) settings.highlightState.set(WEDNESDAY, highlightStateWednesdayProperty.get()) settings.highlightState.set(THURSDAY, highlightStateThursdayProperty.get()) settings.highlightState.set(FRIDAY, highlightStateFridayProperty.get()) settings.highlightState.set(SATURDAY, highlightStateSaturdayProperty.get()) settings.highlightState.set(SUNDAY, highlightStateSundayProperty.get()) settings.isShowTagsInSearchResults = showTagsInSearchResults.get() settings.isShowFieldsInSearchResults = showFieldsInSearchResults.get() settings.isShowDescriptionInSearchResults = showDescriptionInSearchResults.get() settings.shortcuts.fetchWorklogs = fetchWorklogsKeyboardCombination.get()?.name settings.shortcuts.showIssueSearch = showIssueSearchKeyboardCombination.get()?.name settings.shortcuts.toggleStatistics = toggleStatisticsKeyboardCombination.get()?.name settings.shortcuts.showSettings = showSettingsKeyboardCombination.get()?.name settings.shortcuts.exitWorklogViewer = exitWorklogViewerKeyboardCombination.get()?.name SettingsUtil.saveSettings() } fun discardChanges() { applyPropertiesFromSettings() } private fun applyPropertiesFromSettings() { youTrackUrlProperty.set(settings.youTrackConnectionSettings.baseUrl?.toExternalForm()) youTrackConnectorProperty.set(DataSources.dataSourceFactories.find { it.id == settings.youTrackConnectionSettings.selectedConnectorId }?.let { ConnectorDescriptor(it.id, it.name) }) youTrackUsernameProperty.set(settings.youTrackConnectionSettings.username) youTrackPermanentTokenProperty.set(settings.youTrackConnectionSettings.permanentToken) themeProperty.set(settings.theme) workhoursProperty.set(settings.workHoursADay) showAllWorklogsProperty.set(settings.isShowAllWorklogs) showStatisticsProperty.set(settings.isShowStatistics) loadDataAtStartupProperty.set(settings.isLoadDataAtStartup) showDecimalsInExcelProperty.set(settings.isShowDecimalHourTimesInExcelReport) enablePluginsProperty.set(settings.isEnablePlugins) lastUsedReportTimerangeProperty.set(settings.lastUsedReportTimerange) lastUsedFilePath.set(settings.lastUsedFilePath) startDateProperty.set(settings.startDate) endDateProperty.set(settings.endDate) lastUsedGroupByCategoryIdProperty.set(settings.lastUsedGroupByCategoryId) collapseStateMondayProperty.set(settings.collapseState.isSet(MONDAY)) collapseStateTuesdayProperty.set(settings.collapseState.isSet(TUESDAY)) collapseStateWednesdayProperty.set(settings.collapseState.isSet(WEDNESDAY)) collapseStateThursdayProperty.set(settings.collapseState.isSet(THURSDAY)) collapseStateFridayProperty.set(settings.collapseState.isSet(FRIDAY)) collapseStateSaturdayProperty.set(settings.collapseState.isSet(SATURDAY)) collapseStateSundayProperty.set(settings.collapseState.isSet(SUNDAY)) highlightStateMondayProperty.set(settings.highlightState.isSet(MONDAY)) highlightStateTuesdayProperty.set(settings.highlightState.isSet(TUESDAY)) highlightStateWednesdayProperty.set(settings.highlightState.isSet(WEDNESDAY)) highlightStateThursdayProperty.set(settings.highlightState.isSet(THURSDAY)) highlightStateFridayProperty.set(settings.highlightState.isSet(FRIDAY)) highlightStateSaturdayProperty.set(settings.highlightState.isSet(SATURDAY)) highlightStateSundayProperty.set(settings.highlightState.isSet(SUNDAY)) showTagsInSearchResults.set(settings.isShowTagsInSearchResults) showFieldsInSearchResults.set(settings.isShowFieldsInSearchResults) showDescriptionInSearchResults.set(settings.isShowDescriptionInSearchResults) settings.shortcuts.fetchWorklogs?.let { fetchWorklogsKeyboardCombination.set(KeyCombination.valueOf(it)) } settings.shortcuts.showIssueSearch?.let { showIssueSearchKeyboardCombination.set(KeyCombination.valueOf(it)) } settings.shortcuts.toggleStatistics?.let { toggleStatisticsKeyboardCombination.set(KeyCombination.valueOf(it)) } settings.shortcuts.showSettings?.let { showSettingsKeyboardCombination.set(KeyCombination.valueOf(it)) } settings.shortcuts.exitWorklogViewer?.let { exitWorklogViewerKeyboardCombination.set(KeyCombination.valueOf(it)) } overtimeStatisticsIgnoreWeekendsProperty.set(settings.isOvertimeStatisticsIgnoreWeekends) overtimeStatisticsIgnoreWithoutTimeEntriesProperty.set(settings.isOvertimeStatisticsIgnoreWithoutTimeEntries) overtimeStatisticsIgnoreTodayProperty.set(settings.isOvertimeStatisticsIgnoreToday) statisticsPaneDividerPosition.set(settings.statisticsPaneDividerPosition) } private val hasMissingConnectionSettingsBinding: BooleanBinding get() = youTrackUrlProperty.isEmpty .or(youTrackConnectorProperty.isNull) .or(youTrackUsernameProperty.isEmpty) .or(youTrackPermanentTokenProperty.isEmpty) /** * These settings are applied to the persistent settings * object whenever they are changed. In general, those are * the application state properties, that are not set * in the settings view. */ private fun bindAutoUpdatingProperties() { lastUsedReportTimerangeProperty.addListener(invokeSetter { settings.lastUsedReportTimerange = it }) lastUsedGroupByCategoryIdProperty.addListener(invokeSetter { settings.lastUsedGroupByCategoryId = it }) startDateProperty.addListener(invokeSetter { settings.startDate = it }) endDateProperty.addListener(invokeSetter { settings.endDate = it }) lastUsedFilePath.addListener(invokeSetter { settings.lastUsedFilePath = it }) overtimeStatisticsIgnoreWeekendsProperty.addListener(invokeSetter { settings.isOvertimeStatisticsIgnoreWeekends = it }) overtimeStatisticsIgnoreWithoutTimeEntriesProperty.addListener(invokeSetter { settings.isOvertimeStatisticsIgnoreWithoutTimeEntries = it }) overtimeStatisticsIgnoreTodayProperty.addListener(invokeSetter { settings.isOvertimeStatisticsIgnoreToday = it }) showFieldsInSearchResults.addListener(invokeSetter { settings.isShowFieldsInSearchResults = it }) showTagsInSearchResults.addListener(invokeSetter { settings.isShowTagsInSearchResults = it }) showDescriptionInSearchResults.addListener(invokeSetter { settings.isShowDescriptionInSearchResults = it }) statisticsPaneDividerPosition.addListener(invokeSetter { settings.statisticsPaneDividerPosition = it.toDouble() }) } private fun <T> invokeSetter(block: (t : T) -> Unit): ChangeListener<T> { return ChangeListener { _, _, newValue -> block.invoke(newValue) } } }
mit
d45cd2ac652084c37ebed2a9822055f8
56.319444
189
0.793232
5.306901
false
false
false
false
java-opengl-labs/learn-OpenGL
src/main/kotlin/learnOpenGL/d_advancedOpenGL/2 stencil testing.kt
1
6198
package learnOpenGL.d_advancedOpenGL /** * Created by elect on 13/05/17. */ import glm_.func.rad import glm_.glm import glm_.mat4x4.Mat4 import gln.draw.glDrawArrays import gln.get import gln.glClearColor import gln.glf.glf import gln.glf.semantic import gln.program.usingProgram import gln.set import gln.uniform.glUniform import gln.vertexArray.glBindVertexArray import gln.vertexArray.glEnableVertexAttribArray import gln.vertexArray.glVertexAttribPointer import learnOpenGL.a_gettingStarted.end import learnOpenGL.a_gettingStarted.swapAndPoll import learnOpenGL.a_gettingStarted.verticesCube import learnOpenGL.b_lighting.camera import learnOpenGL.b_lighting.clearColor0 import learnOpenGL.b_lighting.initWindow0 import learnOpenGL.b_lighting.processFrame import learnOpenGL.common.loadTexture import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL13.GL_TEXTURE0 import org.lwjgl.opengl.GL13.glActiveTexture import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.glGetUniformLocation import org.lwjgl.opengl.GL30.* import uno.buffer.destroyBuf import uno.buffer.intBufferBig import uno.glsl.Program import uno.glsl.glDeletePrograms import uno.glsl.glUseProgram fun main(args: Array<String>) { with(StencilTesting()) { run() end() } } private class StencilTesting { val window = initWindow0("Depth Testing View") val program = ProgramB() val programSingleColor = ProgramA() enum class Object { Cube, Plane } val vao = intBufferBig<Object>() val vbo = intBufferBig<Object>() val tex = intBufferBig<Object>() inner open class ProgramA(vertex: String = "stencil-testing.vert", fragment: String = "stencil-single-color.frag") : Program("shaders/d/_2", vertex, fragment) { val model = glGetUniformLocation(name, "model") val view = glGetUniformLocation(name, "view") val proj = glGetUniformLocation(name, "projection") } inner class ProgramB(shader: String = "stencil-testing") : ProgramA("$shader.vert", "$shader.frag") { init { usingProgram(name) { "texture1".unit = semantic.sampler.DIFFUSE } } } init { glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glEnable(GL_STENCIL_TEST) glStencilFunc(GL_NOTEQUAL, 1, 0xFF) glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE) glGenVertexArrays(vao) glGenBuffers(vbo) for (i in Object.values()) { glBindVertexArray(vao[i]) glBindBuffer(GL_ARRAY_BUFFER, vbo[i]) glBufferData(GL_ARRAY_BUFFER, if (i == Object.Cube) verticesCube else planeVertices, GL_STATIC_DRAW) glEnableVertexAttribArray(glf.pos3_tc2) glVertexAttribPointer(glf.pos3_tc2) glBindVertexArray() } // load textures tex[Object.Cube] = loadTexture("textures/marble.jpg") tex[Object.Plane] = loadTexture("textures/metal.png") } fun run() { while (window.open) { window.processFrame() // render glClearColor(clearColor0) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT or GL_STENCIL_BUFFER_BIT) // don't forget to clear the stencil buffer! // set uniforms glUseProgram(programSingleColor) var model = Mat4() val view = camera.viewMatrix val projection = glm.perspective(camera.zoom.rad, window.aspect, 0.1f, 100f) glUniform(programSingleColor.proj, projection) glUniform(programSingleColor.view, view) glUseProgram(program) glUniform(program.proj, projection) glUniform(program.view, view) /* draw floor as normal, but don't write the floor to the stencil buffer, we only care about the containers. We set its mask to 0x00 to not write to the stencil buffer. */ glStencilMask(0x00) // floor glBindVertexArray(vao[Object.Plane]) glBindTexture(GL_TEXTURE_2D, tex[Object.Plane]) glUniform(program.model, model) glDrawArrays(GL_TRIANGLES, 6) glBindVertexArray() // 1st. render pass, draw objects as normal, writing to the stencil buffer glStencilFunc(GL_ALWAYS, 1, 0xFF) glStencilMask(0xFF) // cubes glBindVertexArray(vao[Object.Cube]) glActiveTexture(GL_TEXTURE0 + semantic.sampler.DIFFUSE) glBindTexture(GL_TEXTURE_2D, tex[Object.Cube]) model.translate_(-1f, 0f, -1f) glUniform(program.model, model) glDrawArrays(GL_TRIANGLES, 36) model = Mat4().translate_(2f, 0f, 0f) glUniform(program.model, model) glDrawArrays(GL_TRIANGLES, 36) /* 2nd. render pass: now draw slightly scaled versions of the objects, this time disabling stencil writing. Because the stencil buffer is now filled with several 1s. The parts of the buffer that are 1 are not drawn, thus only drawing the objects' size differences, making it look like borders. */ glStencilFunc(GL_NOTEQUAL, 1, 0xFF) glStencilMask(0x00) glDisable(GL_DEPTH_TEST) glUseProgram(programSingleColor) val scale = 1.1f // cubes glBindVertexArray(vao[Object.Cube]) model = Mat4() .translate_(-1f, 0f, -1f) .scale_(scale) glUniform(programSingleColor.model, model) glDrawArrays(GL_TRIANGLES, 36) model = Mat4() .translate_(2f, 0f, 0f) .scale_(scale) glUniform(programSingleColor.model, model) glDrawArrays(GL_TRIANGLES, 36) glBindVertexArray(0) glStencilMask(0xFF) glEnable(GL_DEPTH_TEST) window.swapAndPoll() } } fun end() { glDeletePrograms(program, programSingleColor) glDeleteVertexArrays(vao) glDeleteBuffers(vbo) glDeleteTextures(tex) destroyBuf(vao, vbo, tex) window.end() } }
mit
3439d17369287746d29b8526686fbd28
31.798942
164
0.63827
4.190669
false
false
false
false
lydia-schiff/hella-renderscript
app/src/main/java/com/lydiaschiff/hellaparallel/RsCameraPreviewRenderer.kt
1
6987
package com.lydiaschiff.hellaparallel import android.graphics.ImageFormat import android.os.Handler import android.os.HandlerThread import android.renderscript.Allocation import android.renderscript.Allocation.OnBufferAvailableListener import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsicYuvToRGB import android.util.Log import android.view.Surface import androidx.annotation.AnyThread import androidx.annotation.RequiresApi import androidx.annotation.WorkerThread import com.lydiaschiff.hella.FrameStats import com.lydiaschiff.hella.RsRenderer import com.lydiaschiff.hella.RsSurfaceRenderer import com.lydiaschiff.hella.RsUtil import com.lydiaschiff.hella.renderer.DefaultRsRenderer /** * Created by lydia on 10/30/17. */ @RequiresApi(19) class RsCameraPreviewRenderer @JvmOverloads constructor( private val rs: RenderScript, private var rsRenderer: RsRenderer, x: Int, y: Int, // guarded by "this" private var renderHandler: Handler? = null ) : RsSurfaceRenderer, OnBufferAvailableListener, Runnable { private val yuvInAlloc: Allocation = RsUtil.createYuvIoInputAlloc(rs, x, y, ImageFormat.YUV_420_888).also { it.setOnBufferAvailableListener(this) } private val rgbInAlloc: Allocation = RsUtil.createRgbAlloc(rs, x, y) private val rgbOutAlloc: Allocation = RsUtil.createRgbIoOutputAlloc(rs, x, y) private val yuvToRGBScript = ScriptIntrinsicYuvToRGB.create(rs, Element.RGBA_8888(rs)).apply { setInput(yuvInAlloc) } // all vars guarded by "this" private var renderThread: HandlerThread? = when (renderHandler) { null -> HandlerThread(TAG).apply { start() renderHandler = Handler(looper) } else -> null } private var droppedFrameLogger: FrameStats? = null private var nFramesAvailable = 0 private var totalFrames = 0 private var totalDropped = 0 private var outputSurfaceIsSet = false init { Log.i(TAG, "Setting up RsCameraPreviewRenderer with ${rsRenderer.name} ($x,$y)") } constructor(rs: RenderScript, x: Int, y: Int) : this(rs, DefaultRsRenderer(), x, y) @AnyThread @Synchronized override fun setRsRenderer(rsRenderer: RsRenderer) { if (isRunning) { this.rsRenderer = rsRenderer Log.i(TAG, "updating RsRenderer to \"" + rsRenderer.name + "\"") totalFrames = 0 totalDropped = 0 if (droppedFrameLogger != null) { droppedFrameLogger!!.clear() } } } @Synchronized fun setDroppedFrameLogger(droppedFrameLogger: FrameStats) { this.droppedFrameLogger = droppedFrameLogger } /** * Check if this renderer is still running or has been shutdown. * * @return true if we're running, else false */ @get:Synchronized @get:AnyThread override val isRunning: Boolean get() { if (renderHandler == null) { Log.w(TAG, "renderer was already shut down") return false } return true } /** * Set the output surface to consume the stream of edited camera frames. This is probably * from a SurfaceView or TextureView. Please make sure it's valid. * * @param surface a valid surface to consume a stream of edited frames from the camera */ @AnyThread @Synchronized override fun setOutputSurface(surface: Surface) { if (isRunning) { require(surface.isValid) { "output was invalid" } rgbOutAlloc.surface = surface outputSurfaceIsSet = true Log.d(TAG, "output surface was set") } } /** * Get the Surface that the camera will push frames to. This is the Surface from our yuv * input allocation. It will recieve a callback when a frame is available from the camera. * * @return a surface that consumes yuv frames from the camera preview, or null renderer is * shutdown */ @get:Synchronized @get:AnyThread override val inputSurface: Surface? get() = if (isRunning) yuvInAlloc.surface else null /** * Callback for when the camera has a new frame. We want to handle this on the render thread * specific thread, so we'll increment nFramesAvailable and post a render request. */ @Synchronized override fun onBufferAvailable(a: Allocation) { if (isRunning) { if (!outputSurfaceIsSet) { Log.e(TAG, "We are getting frames from the camera but we never set the view " + "surface to render to") return } nFramesAvailable++ renderHandler!!.post(this) } } /** * Render a frame on the render thread. Everything is async except for ioSend() will block * until the rendering completes. If we wanted to time it, make sure to log the time after * that call. */ @WorkerThread override fun run() { var renderer: RsRenderer var nFrames: Int synchronized(this) { if (!isRunning) { return } renderer = rsRenderer nFrames = nFramesAvailable nFramesAvailable = 0 logFrames(nFrames) renderHandler!!.removeCallbacks(this) } for (i in 0 until nFrames) { yuvInAlloc.ioReceive() } yuvToRGBScript.forEach(rgbInAlloc) renderer.renderFrame(rs, rgbInAlloc, rgbOutAlloc) rgbOutAlloc.ioSend() } private fun logFrames(nFrames: Int) { if (droppedFrameLogger != null) { totalFrames++ val droppedFrames = nFrames - 1 totalDropped += droppedFrames droppedFrameLogger!!.logFrame(TAG, droppedFrames, totalDropped, totalFrames) } } /** * Shut down the renderer when you're finished. */ @AnyThread override fun shutdown() { synchronized(this) { if (!isRunning) { Log.d(TAG, "requesting shutdown...") renderHandler!!.removeCallbacks(this) renderHandler!!.postAtFrontOfQueue { Log.i(TAG, "shutting down") synchronized(this) { droppedFrameLogger = null yuvInAlloc.destroy() rgbInAlloc.destroy() rgbOutAlloc.destroy() yuvToRGBScript.destroy() renderThread?.quitSafely() } } renderHandler = null } } } companion object { private const val TAG = "RsCameraPreviewRenderer" } }
mit
d2365e5adc6cb0ff3c74f0d73641bd0c
31.807512
98
0.609417
4.617978
false
false
false
false
ligee/kotlin-jupyter
src/main/kotlin/org/jetbrains/kotlinx/jupyter/apiImpl.kt
1
6829
package org.jetbrains.kotlinx.jupyter import jupyter.kotlin.JavaRuntime import org.jetbrains.kotlinx.jupyter.api.CodeCell import org.jetbrains.kotlinx.jupyter.api.DisplayContainer import org.jetbrains.kotlinx.jupyter.api.DisplayResult import org.jetbrains.kotlinx.jupyter.api.DisplayResultWithCell import org.jetbrains.kotlinx.jupyter.api.JREInfoProvider import org.jetbrains.kotlinx.jupyter.api.JupyterClientType import org.jetbrains.kotlinx.jupyter.api.KotlinKernelVersion import org.jetbrains.kotlinx.jupyter.api.Notebook import org.jetbrains.kotlinx.jupyter.api.RenderersProcessor import org.jetbrains.kotlinx.jupyter.api.ResultsAccessor import org.jetbrains.kotlinx.jupyter.api.VariableState import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionRequest import org.jetbrains.kotlinx.jupyter.repl.impl.SharedReplContext class DisplayResultWrapper private constructor( val display: DisplayResult, override val cell: CodeCellImpl, ) : DisplayResult by display, DisplayResultWithCell { companion object { fun create(display: DisplayResult, cell: CodeCellImpl): DisplayResultWrapper { return if (display is DisplayResultWrapper) DisplayResultWrapper(display.display, cell) else DisplayResultWrapper(display, cell) } } } class DisplayContainerImpl : DisplayContainer { private val displays: MutableMap<String?, MutableList<DisplayResultWrapper>> = mutableMapOf() fun add(display: DisplayResultWrapper) { val list = displays.getOrPut(display.id) { mutableListOf() } list.add(display) } fun add(display: DisplayResult, cell: CodeCellImpl) { add(DisplayResultWrapper.create(display, cell)) } override fun getAll(): List<DisplayResultWithCell> { return displays.flatMap { it.value } } override fun getById(id: String?): List<DisplayResultWithCell> { return displays[id].orEmpty() } fun update(id: String?, display: DisplayResult) { val initialDisplays = displays[id] ?: return val updated = initialDisplays.map { DisplayResultWrapper.create(display, it.cell) } initialDisplays.clear() initialDisplays.addAll(updated) } } class CodeCellImpl( override val notebook: NotebookImpl, override val id: Int, override val internalId: Int, override val code: String, override val preprocessedCode: String, override val prevCell: CodeCell?, ) : CodeCell { var resultVal: Any? = null override val result: Any? get() = resultVal private var isStreamOutputUpToDate: Boolean = true private var collectedStreamOutput: String = "" private val streamBuilder = StringBuilder() fun appendStreamOutput(output: String) { isStreamOutputUpToDate = false streamBuilder.append(output) } override val streamOutput: String get() { if (!isStreamOutputUpToDate) { isStreamOutputUpToDate = true collectedStreamOutput = streamBuilder.toString() } return collectedStreamOutput } override val displays = DisplayContainerImpl() fun addDisplay(display: DisplayResult) { val wrapper = DisplayResultWrapper.create(display, this) displays.add(wrapper) notebook.displays.add(wrapper) } } class EvalData( val executionCounter: Int, val rawCode: String, ) { constructor(evalRequestData: EvalRequestData) : this(evalRequestData.jupyterId, evalRequestData.code) } class NotebookImpl( private val runtimeProperties: ReplRuntimeProperties, ) : Notebook { private val cells = hashMapOf<Int, CodeCellImpl>() internal var sharedReplContext: SharedReplContext? = null override val cellsList: Collection<CodeCellImpl> get() = cells.values override val variablesState: Map<String, VariableState> get() { return sharedReplContext?.evaluator?.variablesHolder ?: throw IllegalStateException("Evaluator is not initialized yet") } override val cellVariables: Map<Int, Set<String>> get() { return sharedReplContext?.evaluator?.cellVariables ?: throw IllegalStateException("Evaluator is not initialized yet") } override val resultsAccessor = ResultsAccessor { getResult(it) } override fun getCell(id: Int): CodeCellImpl { return cells[id] ?: throw ArrayIndexOutOfBoundsException( "There is no cell with number '$id'" ) } override fun getResult(id: Int): Any? { return getCell(id).result } private val history = arrayListOf<CodeCellImpl>() private var mainCellCreated = false val displays = DisplayContainerImpl() override fun getAllDisplays(): List<DisplayResultWithCell> { return displays.getAll() } override fun getDisplaysById(id: String?): List<DisplayResultWithCell> { return displays.getById(id) } override val kernelVersion: KotlinKernelVersion get() = runtimeProperties.version ?: throw IllegalStateException("Kernel version is not known") override val jreInfo: JREInfoProvider get() = JavaRuntime override val jupyterClientType: JupyterClientType by lazy { JupyterClientDetector.detect() } fun variablesReportAsHTML(): String { return generateHTMLVarsReport(variablesState) } fun variablesReport(): String { return if (variablesState.isEmpty()) "" else { buildString { append("Visible vars: \n") variablesState.forEach { (name, currentState) -> append("\t$name : ${currentState.stringValue}\n") } } } } fun addCell( internalId: Int, preprocessedCode: String, data: EvalData, ): CodeCellImpl { val cell = CodeCellImpl(this, data.executionCounter, internalId, data.rawCode, preprocessedCode, lastCell) cells[data.executionCounter] = cell history.add(cell) mainCellCreated = true return cell } fun beginEvalSession() { mainCellCreated = false } override fun history(before: Int): CodeCellImpl? { val offset = if (mainCellCreated) 1 else 0 return history.getOrNull(history.size - offset - before) } override val currentCell: CodeCellImpl? get() = history(0) override val lastCell: CodeCellImpl? get() = history(1) override val renderersProcessor: RenderersProcessor get() = sharedReplContext?.renderersProcessor ?: throw IllegalStateException("Type renderers processor is not initialized yet") override val libraryRequests: Collection<LibraryResolutionRequest> get() = sharedReplContext?.librariesProcessor?.requests.orEmpty() }
apache-2.0
855bc11c80d6293a1d04bae5d497863d
32.312195
135
0.695124
4.690247
false
false
false
false
czyzby/ktx
assets/src/test/kotlin/ktx/assets/FilesTest.kt
2
2203
package ktx.assets import com.badlogic.gdx.Files.FileType.Absolute import com.badlogic.gdx.Files.FileType.Classpath import com.badlogic.gdx.Files.FileType.External import com.badlogic.gdx.Files.FileType.Internal import com.badlogic.gdx.Files.FileType.Local import com.badlogic.gdx.Gdx import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Test /** * Tests files-related utilities. */ class FilesTest { @Before fun `mock Files`() { Gdx.files = MockFiles() } @Test fun `should convert string to classpath FileHandle`() { val file = "my/package/classpath.file".toClasspathFile() assertNotNull(file) assertEquals(Classpath, file.type()) assertEquals("my/package/classpath.file", file.path()) } @Test fun `should convert string to internal FileHandle`() { val file = "internal.file".toInternalFile() assertNotNull(file) assertEquals(Internal, file.type()) assertEquals("internal.file", file.path()) } @Test fun `should convert string to local FileHandle`() { val file = "local.file".toLocalFile() assertNotNull(file) assertEquals(Local, file.type()) assertEquals("local.file", file.path()) } @Test fun `should convert string to external FileHandle`() { val file = "some/directory/external.file".toExternalFile() assertNotNull(file) assertEquals(External, file.type()) assertEquals("some/directory/external.file", file.path()) } @Test fun `should convert string to absolute FileHandle`() { val file = "/home/mock/absolute.file".toAbsoluteFile() assertNotNull(file) assertEquals(Absolute, file.type()) assertEquals("/home/mock/absolute.file", file.path()) } @Test fun `should create FileHandle with default type`() { val file = file("mock.file") assertNotNull(file) assertEquals(Internal, file.type()) assertEquals("mock.file", file.path()) } @Test fun `should create FileHandle with custom type`() { val file = file("/home/ktx/mock.file", type = Absolute) assertNotNull(file) assertEquals(Absolute, file.type()) assertEquals("/home/ktx/mock.file", file.path()) } }
cc0-1.0
a85f46f12c268bb456abb1fd32fe6327
24.917647
62
0.702224
3.948029
false
true
false
false
rhdunn/xquery-intellij-plugin
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/text/Units.kt
1
1305
/* * Copyright (C) 2019 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.core.text import java.text.NumberFormat object Units { private fun numberFormat(min: Int, max: Int): NumberFormat { val nf = NumberFormat.getInstance() nf.minimumFractionDigits = min nf.maximumFractionDigits = max return nf } @Suppress("unused") object Precision { val milli: NumberFormat = numberFormat(0, 3) val micro: NumberFormat = numberFormat(3, 6) val nano: NumberFormat = numberFormat(6, 9) val milliWithZeros: NumberFormat = numberFormat(3, 3) val microWithZeros: NumberFormat = numberFormat(6, 6) val nanoWithZeros: NumberFormat = numberFormat(9, 9) } }
apache-2.0
c31fb4cb0864ce8d3178f49aa84aa6c6
33.342105
75
0.698084
4.209677
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/CataloguePresenter.kt
1
3789
package eu.kanade.tachiyomi.ui.catalogue import android.os.Bundle import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.source.LocalSource import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.util.* import java.util.concurrent.TimeUnit /** * Presenter of [CatalogueController] * Function calls should be done from here. UI calls should be done from the controller. * * @param sourceManager manages the different sources. * @param preferences application preferences. */ class CataloguePresenter( val sourceManager: SourceManager = Injekt.get(), private val preferences: PreferencesHelper = Injekt.get(), private val controllerMode: CatalogueController.Mode ) : BasePresenter<CatalogueController>() { /** * Enabled sources. */ var sources = getEnabledSources() /** * Subscription for retrieving enabled sources. */ private var sourceSubscription: Subscription? = null override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) // Load enabled and last used sources loadSources() loadLastUsedSource() } /** * Unsubscribe and create a new subscription to fetch enabled sources. */ fun loadSources() { sourceSubscription?.unsubscribe() val map = TreeMap<String, MutableList<CatalogueSource>> { d1, d2 -> // Catalogues without a lang defined will be placed at the end when { d1 == "" && d2 != "" -> 1 d2 == "" && d1 != "" -> -1 else -> d1.compareTo(d2) } } val byLang = sources.groupByTo(map, { it.lang }) val sourceItems = byLang.flatMap { val langItem = LangItem(it.key) it.value.map { source -> SourceItem(source, langItem, controllerMode == CatalogueController.Mode.CATALOGUE) } } sourceSubscription = Observable.just(sourceItems) .subscribeLatestCache(CatalogueController::setSources) } private fun loadLastUsedSource() { val sharedObs = preferences.lastUsedCatalogueSource().asObservable().share() // Emit the first item immediately but delay subsequent emissions by 500ms. Observable.merge( sharedObs.take(1), sharedObs.skip(1).delay(500, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())) .distinctUntilChanged() .map { (sourceManager.get(it) as? CatalogueSource)?.let { SourceItem(it, showButtons = controllerMode == CatalogueController.Mode.CATALOGUE) } } .subscribeLatestCache(CatalogueController::setLastUsedSource) } fun updateSources() { sources = getEnabledSources() loadSources() } /** * Returns a list of enabled sources ordered by language and name. * * @return list containing enabled sources. */ private fun getEnabledSources(): List<CatalogueSource> { val languages = preferences.enabledLanguages().getOrDefault() val hiddenCatalogues = preferences.hiddenCatalogues().getOrDefault() return sourceManager.getVisibleCatalogueSources() .filter { it.lang in languages } .filterNot { it.id.toString() in hiddenCatalogues } .sortedBy { "(${it.lang}) ${it.name}" } + sourceManager.get(LocalSource.ID) as LocalSource } }
apache-2.0
99f8db860938f604faeb42f3c430551d
35.085714
160
0.663764
4.802281
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/source/EnhancedHttpSource.kt
1
7620
package exh.source import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.HttpSource import okhttp3.Response import uy.kohesive.injekt.injectLazy class EnhancedHttpSource(val originalSource: HttpSource, val enchancedSource: HttpSource): HttpSource() { private val prefs: PreferencesHelper by injectLazy() /** * Returns the request for the popular manga given the page. * * @param page the page number to retrieve. */ override fun popularMangaRequest(page: Int) = throw UnsupportedOperationException("Should never be called!") /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ override fun popularMangaParse(response: Response) = throw UnsupportedOperationException("Should never be called!") /** * Returns the request for the search manga given the page. * * @param page the page number to retrieve. * @param query the search query. * @param filters the list of filters to apply. */ override fun searchMangaRequest(page: Int, query: String, filters: FilterList) = throw UnsupportedOperationException("Should never be called!") /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ override fun searchMangaParse(response: Response) = throw UnsupportedOperationException("Should never be called!") /** * Returns the request for latest manga given the page. * * @param page the page number to retrieve. */ override fun latestUpdatesRequest(page: Int) = throw UnsupportedOperationException("Should never be called!") /** * Parses the response from the site and returns a [MangasPage] object. * * @param response the response from the site. */ override fun latestUpdatesParse(response: Response) = throw UnsupportedOperationException("Should never be called!") /** * Parses the response from the site and returns the details of a manga. * * @param response the response from the site. */ override fun mangaDetailsParse(response: Response) = throw UnsupportedOperationException("Should never be called!") /** * Parses the response from the site and returns a list of chapters. * * @param response the response from the site. */ override fun chapterListParse(response: Response) = throw UnsupportedOperationException("Should never be called!") /** * Parses the response from the site and returns a list of pages. * * @param response the response from the site. */ override fun pageListParse(response: Response) = throw UnsupportedOperationException("Should never be called!") /** * Parses the response from the site and returns the absolute url to the source image. * * @param response the response from the site. */ override fun imageUrlParse(response: Response) = throw UnsupportedOperationException("Should never be called!") /** * Base url of the website without the trailing slash, like: http://mysite.com */ override val baseUrl get() = source().baseUrl /** * Whether the source has support for latest updates. */ override val supportsLatest get() = source().supportsLatest /** * Name of the source. */ override val name get() = source().name /** * An ISO 639-1 compliant language code (two letters in lower case). */ override val lang get() = source().lang // ===> OPTIONAL FIELDS /** * Id of the source. By default it uses a generated id using the first 16 characters (64 bits) * of the MD5 of the string: sourcename/language/versionId * Note the generated id sets the sign bit to 0. */ override val id get() = source().id /** * Default network client for doing requests. */ override val client get() = source().client /** * Visible name of the source. */ override fun toString() = source().toString() /** * Returns an observable containing a page with a list of manga. Normally it's not needed to * override this method. * * @param page the page number to retrieve. */ override fun fetchPopularManga(page: Int) = source().fetchPopularManga(page) /** * Returns an observable containing a page with a list of manga. Normally it's not needed to * override this method. * * @param page the page number to retrieve. * @param query the search query. * @param filters the list of filters to apply. */ override fun fetchSearchManga(page: Int, query: String, filters: FilterList) = source().fetchSearchManga(page, query, filters) /** * Returns an observable containing a page with a list of latest manga updates. * * @param page the page number to retrieve. */ override fun fetchLatestUpdates(page: Int) = source().fetchLatestUpdates(page) /** * Returns an observable with the updated details for a manga. Normally it's not needed to * override this method. * * @param manga the manga to be updated. */ override fun fetchMangaDetails(manga: SManga) = source().fetchMangaDetails(manga) /** * Returns the request for the details of a manga. Override only if it's needed to change the * url, send different headers or request method like POST. * * @param manga the manga to be updated. */ override fun mangaDetailsRequest(manga: SManga) = source().mangaDetailsRequest(manga) /** * Returns an observable with the updated chapter list for a manga. Normally it's not needed to * override this method. If a manga is licensed an empty chapter list observable is returned * * @param manga the manga to look for chapters. */ override fun fetchChapterList(manga: SManga) = source().fetchChapterList(manga) /** * Returns an observable with the page list for a chapter. * * @param chapter the chapter whose page list has to be fetched. */ override fun fetchPageList(chapter: SChapter) = source().fetchPageList(chapter) /** * Returns an observable with the page containing the source url of the image. If there's any * error, it will return null instead of throwing an exception. * * @param page the page whose source image has to be fetched. */ override fun fetchImageUrl(page: Page) = source().fetchImageUrl(page) /** * Called before inserting a new chapter into database. Use it if you need to override chapter * fields, like the title or the chapter number. Do not change anything to [manga]. * * @param chapter the chapter to be added. * @param manga the manga of the chapter. */ override fun prepareNewChapter(chapter: SChapter, manga: SManga) = source().prepareNewChapter(chapter, manga) /** * Returns the list of filters for the source. */ override fun getFilterList() = source().getFilterList() private fun source(): HttpSource { return if(prefs.eh_delegateSources().getOrDefault()) { enchancedSource } else { originalSource } } }
apache-2.0
01f741f42f07534920e94cdf5ac14af4
33.640909
99
0.658924
4.87524
false
false
false
false
mtransitapps/parser
src/main/java/org/mtransit/parser/mt/data/MFrequency.kt
1
2268
package org.mtransit.parser.mt.data import org.mtransit.parser.Constants import org.mtransit.parser.db.SQLUtils import org.mtransit.parser.gtfs.GAgencyTools import org.mtransit.parser.gtfs.data.GIDs data class MFrequency( val serviceIdInt: Int, private val tripId: Long, // exported val startTime: Int, val endTime: Int, private val headwayInSec: Int ) : Comparable<MFrequency?> { @Deprecated(message = "Not memory efficient") @Suppress("unused") val serviceId = _serviceId private val _serviceId: String get() { return GIDs.getString(serviceIdInt) } private fun getCleanServiceId(agencyTools: GAgencyTools): String { return agencyTools.cleanServiceId(_serviceId) } val uID by lazy { getNewUID(serviceIdInt, tripId, startTime, endTime) } fun toFile(agencyTools: GAgencyTools): String { return SQLUtils.quotes(SQLUtils.escape(getCleanServiceId(agencyTools))) + // service ID Constants.COLUMN_SEPARATOR + // tripId + // trip ID Constants.COLUMN_SEPARATOR + // startTime + // start time Constants.COLUMN_SEPARATOR + // endTime + // end time Constants.COLUMN_SEPARATOR + // headwayInSec // headway in seconds } override fun compareTo(other: MFrequency?): Int { return when { other !is MFrequency -> { +1 } serviceIdInt != other.serviceIdInt -> { _serviceId.compareTo(other._serviceId) } tripId != other.tripId -> { tripId.compareTo(other.tripId) } startTime != other.startTime -> { startTime - other.startTime } endTime != other.endTime -> { endTime - other.endTime } else -> { headwayInSec - other.headwayInSec } } } companion object { @JvmStatic fun getNewUID( serviceIdInt: Int, tripId: Long, startTime: Int, endTime: Int ) = "${serviceIdInt}-${tripId}-${startTime}-${endTime}" } }
apache-2.0
8787de0542dd04905b11c07e4757d9cb
29.253333
95
0.559083
4.68595
false
false
false
false
apollostack/apollo-android
apollo-runtime/src/main/java/com/apollographql/apollo3/fetcher/ApolloResponseFetchers.kt
1
2345
package com.apollographql.apollo3.fetcher import com.apollographql.apollo3.internal.fetcher.CacheAndNetworkFetcher import com.apollographql.apollo3.internal.fetcher.CacheFirstFetcher import com.apollographql.apollo3.internal.fetcher.CacheOnlyFetcher import com.apollographql.apollo3.internal.fetcher.NetworkFirstFetcher import com.apollographql.apollo3.internal.fetcher.NetworkOnlyFetcher object ApolloResponseFetchers { /** * Signals the apollo client to **only** fetch the data from the normalized cache. If it's not present in * the normalized cache or if an exception occurs while trying to fetch it from the normalized cache, an empty [ ] is sent back with the [com.apollographql.apollo3.api.Operation] info * wrapped inside. */ val CACHE_ONLY: ResponseFetcher = CacheOnlyFetcher() /** * Signals the apollo client to **only** fetch the GraphQL data from the network. If network request fails, an * exception is thrown. */ @JvmField val NETWORK_ONLY: ResponseFetcher = NetworkOnlyFetcher() /** * Signals the apollo client to first fetch the data from the normalized cache. If it's not present in the * normalized cache or if an exception occurs while trying to fetch it from the normalized cache, then the data is * instead fetched from the network. */ @JvmField val CACHE_FIRST: ResponseFetcher = CacheFirstFetcher() /** * Signals the apollo client to first fetch the data from the network. If network request fails, then the * data is fetched from the normalized cache. If the data is not present in the normalized cache, then the * exception which led to the network request failure is rethrown. */ val NETWORK_FIRST: ResponseFetcher = NetworkFirstFetcher() /** * Signal the apollo client to fetch the data from both the network and the cache. If cached data is not * present, only network data will be returned. If cached data is available, but network experiences an error, * cached data is first returned, followed by the network error. If cache data is not available, and network * data is not available, the error of the network request will be propagated. If both network and cache * are available, both will be returned. Cache data is guaranteed to be returned first. */ val CACHE_AND_NETWORK: ResponseFetcher = CacheAndNetworkFetcher() }
mit
54ddea0180d57654aa5b14de592fefe7
48.914894
185
0.764606
4.509615
false
false
false
false
Maccimo/intellij-community
tools/intellij.ide.starter/src/com/intellij/ide/starter/utils/utils.kt
1
9295
package com.intellij.ide.starter.utils import com.intellij.ide.starter.di.di import com.intellij.ide.starter.exec.ExecOutputRedirect import com.intellij.ide.starter.exec.exec import com.intellij.ide.starter.path.GlobalPaths import com.intellij.ide.starter.system.SystemInfo import org.kodein.di.direct import org.kodein.di.instance import java.io.* import java.lang.Long.numberOfLeadingZeros import java.nio.charset.Charset import java.nio.file.FileStore import java.nio.file.Files import java.nio.file.Path import java.time.LocalDateTime import java.time.format.DateTimeFormatter import kotlin.io.path.* import kotlin.time.Duration fun formatArtifactName(artifactType: String, testName: String): String { val testNameFormatted = testName.replace("/", "-").replace(" ", "") val time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) return "$artifactType-$testNameFormatted-$time" } fun getThrowableText(t: Throwable): String { val writer = StringWriter() t.printStackTrace(PrintWriter(writer)) return writer.buffer.toString() } inline fun catchAll(action: () -> Unit) { try { action() } catch (t: Throwable) { logError("CatchAll swallowed error: ${t.message}") logError(getThrowableText(t)) } } fun FileStore.getDiskInfo(): String = buildString { appendLine("Disk info of ${name()}") appendLine(" Total space: " + totalSpace.formatSize()) appendLine(" Unallocated space: " + unallocatedSpace.formatSize()) appendLine(" Usable space: " + usableSpace.formatSize()) } fun Runtime.getRuntimeInfo(): String = buildString { appendLine("Memory info") appendLine(" Total memory: " + totalMemory().formatSize()) appendLine(" Free memory: " + freeMemory().formatSize()) appendLine(" Max memory: " + maxMemory().formatSize()) } /** * Invoke cmd: java [arg1 arg2 ... argN] */ fun execJavaCmd(javaHome: Path, args: Iterable<String> = listOf()): List<String> { val ext = if (SystemInfo.isWindows) ".exe" else "" val realJavaHomePath = if (javaHome.isSymbolicLink()) javaHome.readSymbolicLink() else javaHome val java = realJavaHomePath.toAbsolutePath().resolve("bin/java$ext") require(java.isRegularFile()) { "Java is not found under $java" } val prefix = "exec-java-cmd" val stdout = ExecOutputRedirect.ToString() val stderr = ExecOutputRedirect.ToString() val processArguments = listOf(java.toString()).plus(args) exec( presentablePurpose = prefix, workDir = javaHome, timeout = Duration.minutes(1), args = processArguments, stdoutRedirect = stdout, stderrRedirect = stderr ) val mergedOutput = listOf(stdout, stderr) .flatMap { it.read().split(System.lineSeparator()) } .map { it.trim() } .filter { it.isNotBlank() } logOutput( """ Result of calling $processArguments: ${mergedOutput.joinToString(System.lineSeparator())} """) return mergedOutput } /** * Invoke java -version * * @return * openjdk version "17.0.1" 2021-10-19 LTS * OpenJDK Runtime Environment Corretto-17.0.1.12.1 (build 17.0.1+12-LTS) * OpenJDK 64-Bit Server VM Corretto-17.0.1.12.1 (build 17.0.1+12-LTS, mixed mode, sharing) */ fun callJavaVersion(javaHome: Path): String = execJavaCmd(javaHome, listOf("-version")).joinToString(System.lineSeparator()) fun isX64Jdk(javaHome: Path): Boolean { val archProperty = execJavaCmd(javaHome, listOf("-XshowSettings:all", "-version")).firstOrNull { it.startsWith("sun.arch.data.model") } if (archProperty.isNullOrBlank()) throw IllegalAccessException("Couldn't get architecture property sun.arch.data.model value from JDK") return archProperty.trim().endsWith("64") } fun resolveInstalledJdk11(): Path { val jdkEnv = listOf("JDK_11_X64", "JAVA_HOME").firstNotNullOfOrNull { System.getenv(it) } ?: System.getProperty("java.home") val javaHome = jdkEnv?.let { val path = Path(it) if (path.isSymbolicLink()) path.readSymbolicLink() else path } if (javaHome == null || !javaHome.exists()) throw IllegalArgumentException("Java Home $javaHome is null, empty or doesn't exist. Specify JAVA_HOME to point to JDK 11 x64") require(javaHome.isDirectory() && Files.walk(javaHome) .use { it.count() } > 10) { "Java Home $javaHome is not found or empty!" } require(isX64Jdk(javaHome)) { "JDK at path $javaHome should support x64 architecture" } return javaHome } fun String.withIndent(indent: String = " "): String = lineSequence().map { "$indent$it" }.joinToString(System.lineSeparator()) private fun quoteArg(arg: String): String { val specials = " #'\"\n\r\t\u000c" if (!specials.any { arg.contains(it) }) { return arg } val sb = StringBuilder(arg.length * 2) for (element in arg) { when (element) { ' ', '#', '\'' -> sb.append('"').append(element).append('"') '"' -> sb.append("\"\\\"\"") '\n' -> sb.append("\"\\n\"") '\r' -> sb.append("\"\\r\"") '\t' -> sb.append("\"\\t\"") else -> sb.append(element) } } return sb.toString() } /** * Writes list of Java arguments to the Java Command-Line Argument File * See https://docs.oracle.com/javase/9/tools/java.htm, section "java Command-Line Argument Files" **/ fun writeJvmArgsFile(argFile: File, args: List<String>, lineSeparator: String = System.lineSeparator(), charset: Charset = Charsets.UTF_8) { BufferedWriter(OutputStreamWriter(FileOutputStream(argFile), charset)).use { writer -> for (arg in args) { writer.write(quoteArg(arg)) writer.write(lineSeparator) } } } fun takeScreenshot(logsDir: Path) { val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools") val toolName = "TakeScreenshot" val screenshotTool = toolsDir / toolName if (!File(screenshotTool.toString()).exists()) { val archivePath = toolsDir / "$toolName.zip" HttpClient.download("https://repo.labs.intellij.net/phpstorm/tools/TakeScreenshot-1.02.zip", archivePath) FileSystem.unpack(archivePath, screenshotTool) } val screenshotFile = logsDir.resolve("screenshot_beforeKill.jpg") val toolPath = screenshotTool.resolve("$toolName.jar") val javaPath = ProcessHandle.current().info().command().orElseThrow().toString() exec( presentablePurpose = "take-screenshot", workDir = toolsDir, timeout = Duration.seconds(15), args = mutableListOf(javaPath, "-jar", toolPath.absolutePathString(), screenshotFile.toString()), environmentVariables = mapOf("DISPLAY" to ":88"), onlyEnrichExistedEnvVariables = true ) if (screenshotFile.exists()) { logOutput("Screenshot saved in $screenshotFile") } else { error("Couldn't take screenshot") } } fun startProfileNativeThreads(pid: String) { if (!SystemInfo.isWindows) { val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools") val toolName = "async-profiler-2.7-macos" val profiler = toolsDir / toolName downloadAsyncProfilerIfNeeded(profiler, toolsDir) givePermissionsToExecutables(profiler) exec( presentablePurpose = "start-profile", workDir = profiler, timeout = Duration.seconds(15), args = mutableListOf("./profiler.sh", "start", pid) ) } } private fun givePermissionsToExecutables(profiler: Path) { exec( presentablePurpose = "give-permissions-to-jattach", workDir = profiler.resolve("build"), timeout = Duration.seconds(10), args = mutableListOf("chmod", "+x", "jattach") ) exec( presentablePurpose = "give-permissions-to-profiler", workDir = profiler, timeout = Duration.seconds(10), args = mutableListOf("chmod", "+x", "profiler.sh") ) } fun stopProfileNativeThreads(pid: String, fileToStoreInfo: String) { if (!SystemInfo.isWindows) { val toolsDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("tools") val toolName = "async-profiler-2.7-macos" val profiler = toolsDir / toolName exec( presentablePurpose = "stop-profile", workDir = profiler, timeout = Duration.seconds(15), args = mutableListOf("./profiler.sh", "stop", pid, "-f", fileToStoreInfo) ) } } private fun downloadAsyncProfilerIfNeeded(profiler: Path, toolsDir: Path) { if (!File(profiler.toString()).exists()) { val profilerFileName = when { SystemInfo.isMac -> "async-profiler-2.7-macos.zip" SystemInfo.isLinux -> "async-profiler-2.7-linux-x64.tar.gz" else -> error("Current OS is not supported") } val archivePath = toolsDir / profilerFileName HttpClient.download("https://github.com/jvm-profiling-tools/async-profiler/releases/download/v2.7/$profilerFileName", archivePath) FileSystem.unpack(archivePath, toolsDir) } } fun Long.formatSize(): String { if (this < 1024) return "$this B" val z = (63 - numberOfLeadingZeros(this)) / 10 return String.format("%.1f %sB", this.toDouble() / (1L shl z * 10), " KMGTPE"[z]) } fun pathInsideJarFile( jarFile: Path, pathInsideJar: String ): String = jarFile.toAbsolutePath().toString().trimEnd('/') + "!/" + pathInsideJar data class FindUsagesCallParameters(val pathToFile: String, val offset: String, val element: String) { override fun toString() = "$pathToFile $element, $offset)" }
apache-2.0
d60bc8c56ea7231e0a3a1af55717a4b8
32.8
137
0.690264
3.864865
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/ide/codestyle/RustLanguageCodeStyleSettingsProvider.kt
1
1183
package org.rust.ide.codestyle import com.intellij.openapi.util.io.StreamUtil import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable import com.intellij.psi.codeStyle.CommonCodeStyleSettings import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider import org.rust.lang.RustLanguage class RustLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() { override fun getLanguage() = RustLanguage override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: LanguageCodeStyleSettingsProvider.SettingsType) { if (settingsType == SettingsType.WRAPPING_AND_BRACES_SETTINGS) { consumer.showStandardOptions("RIGHT_MARGIN"); } } override fun getDefaultCommonSettings() = CommonCodeStyleSettings(language).apply { RIGHT_MARGIN = 99 } override fun getCodeSample(settingsType: LanguageCodeStyleSettingsProvider.SettingsType) = CODE_SAMPLE private val CODE_SAMPLE by lazy { val stream = javaClass.classLoader.getResourceAsStream("org/rust/ide/codestyle/code_sample.rs") StreamUtil.readText(stream, "UTF-8") } }
mit
1294bf9edb86afbf24ff0918a0b6e7a6
38.433333
106
0.756551
5.077253
false
false
false
false
benjamin-bader/thrifty
thrifty-java-codegen/src/main/kotlin/com/microsoft.thrifty.gen/GenerateReaderVisitor.kt
1
9496
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.gen import com.microsoft.thrifty.Adapter import com.microsoft.thrifty.schema.BuiltinType import com.microsoft.thrifty.schema.EnumType import com.microsoft.thrifty.schema.ListType import com.microsoft.thrifty.schema.MapType import com.microsoft.thrifty.schema.NamespaceScope import com.microsoft.thrifty.schema.ServiceType import com.microsoft.thrifty.schema.SetType import com.microsoft.thrifty.schema.StructType import com.microsoft.thrifty.schema.ThriftType import com.microsoft.thrifty.schema.TypedefType import com.microsoft.thrifty.schema.UserType import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterizedTypeName import java.util.ArrayDeque import java.util.Deque /** * Generates Java code to read a field's value from an open Protocol object. * * Assumptions: * We are inside of [Adapter.read]. Further, we are * inside of a single case block for a single field. There are variables * in scope named "protocol" and "builder", representing the connection and * the struct builder. */ internal open class GenerateReaderVisitor( private val resolver: TypeResolver, private val read: MethodSpec.Builder, private val fieldName: String, private val fieldType: ThriftType, private val failOnUnknownEnumValues: Boolean = true ) : ThriftType.Visitor<Unit> { private val nameStack: Deque<String> = ArrayDeque<String>() private var scope: Int = 0 fun generate() { val fieldTypeCode = resolver.getTypeCode(fieldType) val codeName = TypeNames.getTypeCodeName(fieldTypeCode) read.beginControlFlow("if (field.typeId == \$T.\$L)", TypeNames.TTYPE, codeName) nameStack.push("value") fieldType.accept(this) nameStack.pop() useReadValue("value") read.nextControlFlow("else") read.addStatement("\$T.skip(protocol, field.typeId)", TypeNames.PROTO_UTIL) read.endControlFlow() } protected open fun useReadValue(localName: String) { if (failOnUnknownEnumValues || !fieldType.isEnum) { read.addStatement("builder.\$N(\$N)", fieldName, localName) } else { read.beginControlFlow("if (\$N != null)", localName) read.addStatement("builder.\$N(\$N)", fieldName, localName) read.endControlFlow() } } override fun visitBool(boolType: BuiltinType) { read.addStatement("\$T \$N = protocol.readBool()", TypeNames.BOOLEAN.unbox(), nameStack.peek()) } override fun visitByte(byteType: BuiltinType) { read.addStatement("\$T \$N = protocol.readByte()", TypeNames.BYTE.unbox(), nameStack.peek()) } override fun visitI16(i16Type: BuiltinType) { read.addStatement("\$T \$N = protocol.readI16()", TypeNames.SHORT.unbox(), nameStack.peek()) } override fun visitI32(i32Type: BuiltinType) { read.addStatement("\$T \$N = protocol.readI32()", TypeNames.INTEGER.unbox(), nameStack.peek()) } override fun visitI64(i64Type: BuiltinType) { read.addStatement("\$T \$N = protocol.readI64()", TypeNames.LONG.unbox(), nameStack.peek()) } override fun visitDouble(doubleType: BuiltinType) { read.addStatement("\$T \$N = protocol.readDouble()", TypeNames.DOUBLE.unbox(), nameStack.peek()) } override fun visitString(stringType: BuiltinType) { read.addStatement("\$T \$N = protocol.readString()", TypeNames.STRING, nameStack.peek()) } override fun visitBinary(binaryType: BuiltinType) { read.addStatement("\$T \$N = protocol.readBinary()", TypeNames.BYTE_STRING, nameStack.peek()) } override fun visitVoid(voidType: BuiltinType) { throw AssertionError("Cannot read void") } override fun visitEnum(enumType: EnumType) { val target = nameStack.peek() val qualifiedJavaName = getFullyQualifiedJavaName(enumType) val intName = "i32_$scope" read.addStatement("int \$L = protocol.readI32()", intName) read.addStatement("$1L $2N = $1L.findByValue($3L)", qualifiedJavaName, target, intName) if (failOnUnknownEnumValues) { read.beginControlFlow("if (\$N == null)", target!!) read.addStatement( "throw new $1T($2T.PROTOCOL_ERROR, $3S + $4L)", TypeNames.THRIFT_EXCEPTION, TypeNames.THRIFT_EXCEPTION_KIND, "Unexpected value for enum-type " + enumType.name + ": ", intName) read.endControlFlow() } } override fun visitList(listType: ListType) { val elementType = resolver.getJavaClass(listType.elementType.trueType) val genericListType = ParameterizedTypeName.get(TypeNames.LIST, elementType) val listImplType = resolver.listOf(elementType) val listInfo = "listMetadata$scope" val idx = "i$scope" val item = "item$scope" read.addStatement("\$T \$N = protocol.readListBegin()", TypeNames.LIST_META, listInfo) read.addStatement("\$T \$N = new \$T(\$N.size)", genericListType, nameStack.peek(), listImplType, listInfo) read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, listInfo) pushScope { nameStack.push(item) listType.elementType.trueType.accept(this) nameStack.pop() } read.addStatement("\$N.add(\$N)", nameStack.peek(), item) read.endControlFlow() read.addStatement("protocol.readListEnd()") } override fun visitSet(setType: SetType) { val elementType = resolver.getJavaClass(setType.elementType.trueType) val genericSetType = ParameterizedTypeName.get(TypeNames.SET, elementType) val setImplType = resolver.setOf(elementType) val setInfo = "setMetadata$scope" val idx = "i$scope" val item = "item$scope" read.addStatement("\$T \$N = protocol.readSetBegin()", TypeNames.SET_META, setInfo) read.addStatement("\$T \$N = new \$T(\$N.size)", genericSetType, nameStack.peek(), setImplType, setInfo) read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, setInfo) pushScope { nameStack.push(item) setType.elementType.accept(this) nameStack.pop() } read.addStatement("\$N.add(\$N)", nameStack.peek(), item) read.endControlFlow() read.addStatement("protocol.readSetEnd()") } override fun visitMap(mapType: MapType) { val keyType = resolver.getJavaClass(mapType.keyType.trueType) val valueType = resolver.getJavaClass(mapType.valueType.trueType) val genericMapType = ParameterizedTypeName.get(TypeNames.MAP, keyType, valueType) val mapImplType = resolver.mapOf(keyType, valueType) val mapInfo = "mapMetadata$scope" val idx = "i$scope" val key = "key$scope" val value = "value$scope" pushScope { read.addStatement("\$T \$N = protocol.readMapBegin()", TypeNames.MAP_META, mapInfo) read.addStatement("\$T \$N = new \$T(\$N.size)", genericMapType, nameStack.peek(), mapImplType, mapInfo) read.beginControlFlow("for (int $1N = 0; $1N < $2N.size; ++$1N)", idx, mapInfo) nameStack.push(key) mapType.keyType.accept(this) nameStack.pop() pushScope { nameStack.push(value) mapType.valueType.accept(this) nameStack.pop() } read.addStatement("\$N.put(\$N, \$N)", nameStack.peek(), key, value) read.endControlFlow() read.addStatement("protocol.readMapEnd()") } } override fun visitStruct(structType: StructType) { val qualifiedJavaName = getFullyQualifiedJavaName(structType) read.addStatement("$1L $2N = $1L.ADAPTER.read(protocol)", qualifiedJavaName, nameStack.peek()) } override fun visitTypedef(typedefType: TypedefType) { // throw AssertionError? typedefType.trueType.accept(this) } override fun visitService(serviceType: ServiceType) { throw AssertionError("Cannot read a service") } private fun getFullyQualifiedJavaName(type: UserType): String { if (type.isBuiltin || type.isList || type.isMap || type.isSet || type.isTypedef) { throw AssertionError("Only user and enum types are supported") } val packageName = type.getNamespaceFor(NamespaceScope.JAVA) return packageName + "." + type.name } private inline fun pushScope(fn: () -> Unit) { ++scope try { fn() } finally { --scope } } }
apache-2.0
d056c1f6e0670da514c70f0225bf1380
35.523077
116
0.649115
4.1962
false
false
false
false
florent37/Flutter-AssetsAudioPlayer
android/src/main/kotlin/com/github/florent37/assets_audio_player/notification/NotificationSettings.kt
1
1603
package com.github.florent37.assets_audio_player.notification import java.io.Serializable class NotificationSettings( val nextEnabled: Boolean, val playPauseEnabled: Boolean, val prevEnabled: Boolean, val seekBarEnabled: Boolean, //android only val stopEnabled: Boolean, val previousIcon: String?, val stopIcon: String?, val playIcon: String?, val nextIcon: String?, val pauseIcon: String? ) : Serializable { fun numberEnabled() : Int { var number = 0 if(playPauseEnabled) number++ if(prevEnabled) number++ if(nextEnabled) number++ if(stopEnabled) number++ return number } } fun fetchNotificationSettings(from: Map<*, *>) : NotificationSettings { return NotificationSettings( nextEnabled= from["notif.settings.nextEnabled"] as? Boolean ?: true, stopEnabled= from["notif.settings.stopEnabled"] as? Boolean ?: true, playPauseEnabled = from["notif.settings.playPauseEnabled"] as? Boolean ?: true, prevEnabled = from["notif.settings.prevEnabled"] as? Boolean ?: true, seekBarEnabled = from["notif.settings.seekBarEnabled"] as? Boolean ?: true, previousIcon = from["notif.settings.previousIcon"] as? String, nextIcon = from["notif.settings.nextIcon"] as? String, pauseIcon = from["notif.settings.pauseIcon"] as? String, playIcon = from["notif.settings.playIcon"] as? String, stopIcon = from["notif.settings.stopIcon"] as? String ) }
apache-2.0
ca49fafb899ff091682991eee01bf0e2
37.190476
91
0.638178
4.452778
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/find/impl/FindPopupHeader.kt
8
5061
// 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.find.impl import com.intellij.find.FindBundle import com.intellij.find.FindUsagesCollector import com.intellij.find.impl.FindPopupPanel.ToggleOptionName import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.ExperimentalUI import com.intellij.ui.StateRestoringCheckBox import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.scale.JBUIScale import com.intellij.util.MathUtil import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Dimension import javax.swing.Box import javax.swing.JButton import javax.swing.JComponent import javax.swing.JLabel import kotlin.math.max internal class FindPopupHeader(project: Project, filterContextButton: ActionButton, pinAction: ToggleAction) { @JvmField val panel: DialogPanel lateinit var titleLabel: JLabel lateinit var infoLabel: JLabel lateinit var loadingIcon: JLabel lateinit var cbFileFilter: StateRestoringCheckBox lateinit var fileMaskField: ComboBox<String> init { panel = panel { customizeSpacingConfiguration(spacingConfiguration = object : IntelliJSpacingConfiguration() { // Remove default vertical gap around cells, so the header can be smaller override val verticalComponentGap: Int get() = if (ExperimentalUI.isNewUI()) 0 else super.verticalComponentGap }) { row { val titleCell = label(FindBundle.message("find.in.path.dialog.title")) .bold() titleLabel = titleCell.component infoLabel = label("") .gap(RightGap.SMALL) .component if (ExperimentalUI.isNewUI()) { val headerInsets = JBUI.CurrentTheme.ComplexPopup.headerInsets() titleCell.customize(Gaps(top = headerInsets.top, bottom = headerInsets.bottom, right = JBUI.scale(12))) infoLabel.foreground = JBUI.CurrentTheme.ContextHelp.FOREGROUND } else { titleCell.gap(RightGap.SMALL) UIUtil.applyStyle(UIUtil.ComponentStyle.SMALL, infoLabel) } loadingIcon = icon(EmptyIcon.ICON_16) .resizableColumn() .component cbFileFilter = cell(createCheckBox(project)) .gap(RightGap.SMALL) .component fileMaskField = cell(createFileFilter()).component cell(filterContextButton) .gap(RightGap.SMALL) if (!ExperimentalUI.isNewUI()) { cell(createSeparator()) .gap(RightGap.SMALL) } actionButton(pinAction) } } } } private fun createCheckBox(project: Project): StateRestoringCheckBox { val checkBox = StateRestoringCheckBox(FindBundle.message("find.popup.filemask")) checkBox.addActionListener { FindUsagesCollector.CHECK_BOX_TOGGLED.log(project, FindUsagesCollector.FIND_IN_PATH, ToggleOptionName.FileFilter, checkBox.isSelected) } return checkBox } private fun createFileFilter(): ComboBox<String> { val result = object : ComboBox<String>() { override fun getPreferredSize(): Dimension { var width = 0 var buttonWidth = 0 val components = components for (component in components) { val size = component.preferredSize val w = size?.width ?: 0 if (component is JButton) { buttonWidth = w } width += w } val editor = getEditor() if (editor != null) { val editorComponent = editor.editorComponent if (editorComponent != null) { val fontMetrics = editorComponent.getFontMetrics(editorComponent.font) val item: Any? = selectedItem width = max(width, fontMetrics.stringWidth(item.toString()) + buttonWidth) // Let's reserve some extra space for just one 'the next' letter width += fontMetrics.stringWidth("m") } } val size = super.getPreferredSize() val insets = insets width += insets.left + insets.right size.width = MathUtil.clamp(width, JBUIScale.scale(80), JBUIScale.scale(500)) return size } } result.isEditable = true result.maximumRowCount = 8 return result } private fun createSeparator(): JComponent { val result = Box.createRigidArea(JBDimension(1, 24)) as JComponent result.isOpaque = true result.background = JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground() return result } }
apache-2.0
b17a24058c66a37b2eaf23bc781196ff
35.15
140
0.685042
4.660221
false
false
false
false
KotlinBy/bkug.by
webapp/src/main/kotlin/by/bkug/webapp/App.kt
1
2860
package by.bkug.webapp import by.bkug.calendar.IcsCalendarGenerator import by.bkug.common.DefaultShutdownManager import by.bkug.data.calendar import by.bkug.data.internalCalendar import by.bkug.data.model.Calendar import by.bkug.shortener.URLShortenerHandler import io.undertow.Undertow import io.undertow.server.HttpHandler import io.undertow.server.HttpServerExchange import io.undertow.server.RoutingHandler import io.undertow.server.handlers.PathHandler import io.undertow.server.handlers.resource.ClassPathResourceManager import io.undertow.server.handlers.resource.PathResourceManager import io.undertow.server.handlers.resource.ResourceHandler import io.undertow.util.Headers import io.undertow.util.StatusCodes import java.nio.file.Paths /** * Runs web app: * * - authentication * - forms * - shortener * - storage * * @author Ruslan Ibragimov * @since 1.0.0 */ fun main() { val rootHandler = PathHandler(100) .addPrefixPath("/", ResourceHandler( ClassPathResourceManager( ClassPathResourceManager::class.java.classLoader, "public" ), ResourceHandler( PathResourceManager( Paths.get("web-theme", "dist") ) ) )) .addPrefixPath("/auth", NoopHandler) .addPrefixPath("/form", NoopHandler) .addPrefixPath("/to", URLShortenerHandler()) .addPrefixPath("/files", NoopHandler) .addPrefixPath("/api", ApiHandler()) .addExactPath("/calendar.ics", CalendarHandler(calendar)) .addExactPath("/calendar-internal.ics", CalendarHandler(internalCalendar)) val server = Undertow.builder() .addHttpListener(8080, "0.0.0.0") .setHandler(rootHandler) .build() val manager = DefaultShutdownManager() manager.onShutdown("Undertow") { server.stop() } server.start() } class CalendarHandler( calendarData: Calendar ) : HttpHandler { private val data = IcsCalendarGenerator().generate(calendarData) override fun handleRequest(exchange: HttpServerExchange) { exchange.responseHeaders.put(Headers.CONTENT_TYPE, "text/calendar") exchange.responseSender.send(data) } } class HealthCheckHandler : HttpHandler { override fun handleRequest(exchange: HttpServerExchange) { exchange.statusCode = StatusCodes.OK exchange.responseSender.send("ok") } } class ApiHandler : HttpHandler { private val pathHandler = RoutingHandler() .get("/healthcheck", HealthCheckHandler()) override fun handleRequest(exchange: HttpServerExchange) { pathHandler.handleRequest(exchange) } } object NoopHandler : HttpHandler { override fun handleRequest(exchange: HttpServerExchange) { exchange.responseSender.send(exchange.requestPath) } }
gpl-3.0
59e8122ea8c38f0f05dce7447087058e
28.183673
82
0.69965
4.339909
false
false
false
false
yongce/AndroidLib
baseLib/src/main/java/me/ycdev/android/lib/common/net/HttpClient.kt
1
5467
package me.ycdev.android.lib.common.net import me.ycdev.android.lib.common.utils.IoUtils import me.ycdev.android.lib.common.utils.LibLogger import java.io.DataOutputStream import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.util.HashMap import java.util.zip.GZIPInputStream import java.util.zip.InflaterInputStream @Suppress("unused") class HttpClient { private val charset = "UTF-8" private var connectTimeout: Int = 10_000 // ms private var readTimeout: Int = 10_1000 // ms fun setTimeout(connectTimeout: Int, readTimeout: Int) { this.connectTimeout = connectTimeout this.readTimeout = readTimeout } @Throws(IOException::class) operator fun get( url: String, requestHeaders: HashMap<String, String> ): String { val httpConn = getHttpConnection(url, false, requestHeaders) try { httpConn.connect() } catch (e: Exception) { throw IOException(e.toString()) } try { return getResponse(httpConn) } finally { httpConn.disconnect() } } @Throws(IOException::class) fun post(url: String, body: String): String { val httpConn = getHttpConnection(url, true, null) var os: DataOutputStream? = null // Send the "POST" request try { os = DataOutputStream(httpConn.outputStream) os.write(body.toByteArray(charset(charset))) os.flush() return getResponse(httpConn) } catch (e: Exception) { // should not be here, but..... throw IOException(e.toString()) } finally { // Must be called before calling HttpURLConnection.disconnect() IoUtils.closeQuietly(os) httpConn.disconnect() } } @Throws(IOException::class) fun post(url: String, body: ByteArray): String { val httpConn = getHttpConnection(url, true, null) var os: DataOutputStream? = null // Send the "POST" request try { os = DataOutputStream(httpConn.outputStream) os.write(body) os.flush() return getResponse(httpConn) } catch (e: Exception) { // prepare for any unexpected exceptions throw IOException(e.toString()) } finally { // Must be called before calling HttpURLConnection.disconnect() IoUtils.closeQuietly(os) httpConn.disconnect() } } @Throws(IOException::class) private fun getHttpConnection( url: String, post: Boolean, requestHeaders: HashMap<String, String>? ): HttpURLConnection { val httpConn = NetworkUtils.openHttpURLConnection(url) httpConn.connectTimeout = connectTimeout httpConn.readTimeout = readTimeout httpConn.doInput = true httpConn.useCaches = false httpConn.setRequestProperty("Accept-Encoding", "gzip,deflate") httpConn.setRequestProperty("Charset", charset) if (requestHeaders != null) { addRequestHeaders(httpConn, requestHeaders) } if (post) { httpConn.doOutput = true httpConn.requestMethod = "POST" } else { httpConn.requestMethod = "GET" // by default } return httpConn } private fun addRequestHeaders( httpConn: HttpURLConnection, requestHeaders: HashMap<String, String> ) { val allHeaders = requestHeaders.entries for ((key, value) in allHeaders) { httpConn.addRequestProperty(key, value) } } @Throws(IOException::class) private fun getResponse(httpConn: HttpURLConnection): String { val contentEncoding = httpConn.contentEncoding LibLogger.d( TAG, "response code: " + httpConn.responseCode + ", encoding: " + contentEncoding + ", method: " + httpConn.requestMethod ) var httpInputStream: InputStream? = null try { httpInputStream = httpConn.inputStream } catch (e: IOException) { // ignore } catch (e: IllegalStateException) { } if (httpInputStream == null) { // If httpConn.getInputStream() throws IOException, // we can get the error message from the error stream. // For example, the case when the response code is 4xx. httpInputStream = httpConn.errorStream } if (httpInputStream == null) { throw IOException("HttpURLConnection.getInputStream() returned null") } val input: InputStream if (contentEncoding != null && contentEncoding.contains("gzip")) { input = GZIPInputStream(httpInputStream) } else if (contentEncoding != null && contentEncoding.contains("deflate")) { input = InflaterInputStream(httpInputStream) } else { input = httpInputStream } // Read the response content try { val responseContent = input.readBytes() return String(responseContent, charset(charset)) } finally { // Must be called before calling HttpURLConnection.disconnect() IoUtils.closeQuietly(input) } } companion object { private const val TAG = "HttpClient" } }
apache-2.0
3a6e16277e77f3961f4cb5ac22fce526
31.541667
92
0.603805
4.903139
false
false
false
false
jk1/intellij-community
java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt
1
11070
// 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.psi.impl import com.intellij.codeInsight.JavaModuleSystemEx import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.JavaErrorMessages import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.JdkOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.psi.* import com.intellij.psi.impl.light.LightJavaModule import com.intellij.psi.impl.source.PsiJavaModuleReference import com.intellij.psi.util.PsiUtil /** * Checks package accessibility according to JLS 7 "Packages and Modules". * * @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html">JLS 7 "Packages and Modules"</a> * @see <a href="http://openjdk.java.net/jeps/261">JEP 261: Module System</a> */ class JavaPlatformModuleSystem : JavaModuleSystemEx { override fun getName(): String = "Java Platform Module System" override fun isAccessible(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): Boolean = checkAccess(targetPackageName, targetFile?.originalFile, place, quick = true) == null override fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): ErrorWithFixes? = checkAccess(targetPackageName, targetFile?.originalFile, place, quick = false) private fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement, quick: Boolean): ErrorWithFixes? { val useFile = place.containingFile?.originalFile if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) { val useVFile = useFile.virtualFile val index = ProjectFileIndex.getInstance(useFile.project) if (useVFile == null || !index.isInLibrarySource(useVFile)) { if (targetFile != null && targetFile.isPhysical) { return checkAccess(targetFile, useFile, targetPackageName, quick) } else if (useVFile != null) { val target = JavaPsiFacade.getInstance(useFile.project).findPackage(targetPackageName) if (target != null) { val module = index.getModuleForFile(useVFile) if (module != null) { val test = index.isInTestSourceContent(useVFile) val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test)) if (dirs.isEmpty()) { return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("package.not.found", target.qualifiedName)) } val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick) return when { error == null -> null dirs.size == 1 -> error dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null } -> null else -> error } } } } } } return null } private val ERR = ErrorWithFixes("-") private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? { val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target) val useModule = JavaModuleGraphUtil.findDescriptorByElement(place) if (targetModule != null) { if (targetModule == useModule) { return null } val targetName = targetModule.name val useName = useModule?.name ?: "ALL-UNNAMED" val module = place.virtualFile?.let { ProjectFileIndex.getInstance(place.project).getModuleForFile(it) } if (useModule == null) { val origin = targetModule.containingFile?.virtualFile if (origin == null || module == null || ModuleRootManager.getInstance(module).fileIndex.getOrderEntryForFile(origin) !is JdkOrderEntry) { return null // a target is not on the mandatory module path } val root = PsiJavaModuleReference.resolve(place, "java.se", false) if (!(root == null || JavaModuleGraphUtil.reads(root, targetModule) || inAddedModules(module, targetName))) { return if (quick) ERR else ErrorWithFixes( JavaErrorMessages.message("module.access.not.in.graph", packageName, targetName), listOf(AddModulesOptionFix(module, targetName))) } } if (!(targetModule is LightJavaModule || JavaModuleGraphUtil.exports(targetModule, packageName, useModule) || module != null && inAddedExports(module, targetName, packageName, useName))) { if (quick) return ERR val fixes = when { packageName.isEmpty() -> emptyList() targetModule is PsiCompiledElement && module != null -> listOf(AddExportsOptionFix(module, targetName, packageName, useName)) targetModule !is PsiCompiledElement && useModule != null -> listOf(AddExportsDirectiveFix(targetModule, packageName, useName)) else -> emptyList() } return when (useModule) { null -> ErrorWithFixes(JavaErrorMessages.message("module.access.from.unnamed", packageName, targetName), fixes) else -> ErrorWithFixes(JavaErrorMessages.message("module.access.from.named", packageName, targetName, useName), fixes) } } if (useModule != null && !(targetName == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) { return when { quick -> ERR PsiNameHelper.isValidModuleName(targetName, useModule) -> ErrorWithFixes( JavaErrorMessages.message("module.access.does.not.read", packageName, targetName, useName), listOf(AddRequiresDirectiveFix(useModule, targetName))) else -> ErrorWithFixes(JavaErrorMessages.message("module.access.bad.name", packageName, targetName)) } } } else if (useModule != null) { return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("module.access.to.unnamed", packageName, useModule.name)) } return null } private fun inAddedExports(module: Module, targetName: String, packageName: String, useName: String): Boolean { val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module) if (options.isEmpty()) return false val prefix = "${targetName}/${packageName}=" return optionValues(options, "--add-exports") .filter { it.startsWith(prefix) } .map { it.substring(prefix.length) } .flatMap { it.splitToSequence(",") } .any { it == useName } } private fun inAddedModules(module: Module, moduleName: String): Boolean { val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module) return optionValues(options, "--add-modules") .flatMap { it.splitToSequence(",") } .any { it == moduleName || it == "ALL-SYSTEM" } } private fun optionValues(options: List<String>, name: String) = if (options.isEmpty()) emptySequence() else { var useValue = false options.asSequence() .map { when { it == name -> { useValue = true; "" } useValue -> { useValue = false; it } it.startsWith(name) && it[name.length] == '=' -> it.substring(name.length + 1) else -> "" } } .filterNot { it.isEmpty() } } private abstract class CompilerOptionFix(private val module: Module) : IntentionAction { override fun getFamilyName() = "dfd4a2c1-da18-4651-9aa8-d7d31cae10be" // random string; never visible override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = !module.isDisposed override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { if (isAvailable(project, editor, file)) { val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module).toMutableList() update(options) JavaCompilerConfigurationProxy.setAdditionalOptions(module.project, module, options) PsiManager.getInstance(project).dropPsiCaches() DaemonCodeAnalyzer.getInstance(project).restart() } } protected abstract fun update(options: MutableList<String>) override fun startInWriteAction() = true } private class AddExportsOptionFix(module: Module, targetName: String, packageName: String, private val useName: String) : CompilerOptionFix(module) { private val qualifier = "${targetName}/${packageName}" override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-exports=${qualifier}=${useName}") override fun update(options: MutableList<String>) { var idx = -1; var candidate = -1; var offset = 0 for ((i, option) in options.withIndex()) { if (option.startsWith("--add-exports")) { if (option.length == 13) { candidate = i + 1 ; offset = 0 } else if (option[13] == '=') { candidate = i; offset = 14 } } if (i == candidate && option.startsWith(qualifier, offset)) { val qualifierEnd = qualifier.length + offset if (option.length == qualifierEnd || option[qualifierEnd] == '=') { idx = i } } } when { idx == -1 -> options += "--add-exports=${qualifier}=${useName}" candidate == options.size -> options[idx - 1] = "--add-exports=${qualifier}=${useName}" else -> { val value = options[idx] options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + useName else "${value},${useName}" } } } } private class AddModulesOptionFix(module: Module, private val moduleName: String) : CompilerOptionFix(module) { override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-modules=${moduleName}") override fun update(options: MutableList<String>) { var idx = -1 for ((i, option) in options.withIndex()) { if (option.startsWith("--add-modules")) { if (option.length == 13) idx = i + 1 else if (option[13] == '=') idx = i } } when (idx) { -1 -> options += "--add-modules=${moduleName}" options.size -> options[idx - 1] = "--add-modules=${moduleName}" else -> { val value = options[idx] options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + moduleName else "${value},${moduleName}" } } } } }
apache-2.0
c3ec34884d53ea79d0f291095d0f9741
44.747934
151
0.667299
4.643456
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/Android.kt
1
1309
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.engine.android import io.ktor.client.* import io.ktor.client.engine.* /** * A JVM/Android client engine that uses `HttpURLConnection` under the hood. * You can use this engine if your application targets old Android versions (1.x+). * * To create the client with this engine, pass it to the `HttpClient` constructor: * ```kotlin * val client = HttpClient(Android) * ``` * To configure the engine, pass settings exposed by [AndroidEngineConfig] to the `engine` method: * ```kotlin * val client = HttpClient(Android) { * engine { * // this: AndroidEngineConfig * } * } * ``` * * You can learn more about client engines from [Engines](https://ktor.io/docs/http-client-engines.html). */ public object Android : HttpClientEngineFactory<AndroidEngineConfig> { override fun create(block: AndroidEngineConfig.() -> Unit): HttpClientEngine = AndroidClientEngine(AndroidEngineConfig().apply(block)) } @Suppress("KDocMissingDocumentation") public class AndroidEngineContainer : HttpClientEngineContainer { override val factory: HttpClientEngineFactory<*> = Android override fun toString(): String = "Android" }
apache-2.0
37eb2e3ef20d2fc6f853ab7528963768
32.564103
119
0.720397
4.103448
false
true
false
false
seirion/code
google/2019/qualification_round/4/small.kt
1
820
import java.util.* fun main(args: Array<String>) { val t = readLine()!!.toInt() (1..t).forEach { solve() } } fun solve() { val (N, B, F) = readLine()!!.split("\\s".toRegex()).map { it.toInt() } val response = ArrayList<String>() (0 until F).forEach { println(bitFlag(N, 1 shl it)) readLine()!!.let { s -> response.add(s) } } val s = ArrayList<Int>(N - B).apply { repeat(N - B) { add(0) } } response.forEachIndexed { row, value -> value.forEachIndexed { col, v -> if (v == '1') s[col] += (1 shl row) } } println((0 until N).toSet().minus(s).joinToString(" ")) readLine() } fun bitFlag(size: Int, gap: Int) = ("0".repeat(gap) + "1".repeat(gap)) .repeat(size / gap + gap) .take(size)
apache-2.0
0c8eb69b0c2c8fb100f3282e1bd1dc85
23.117647
78
0.502439
3.266932
false
false
false
false
ktorio/ktor
ktor-http/common/src/io/ktor/http/Cookie.kt
1
7636
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http import io.ktor.util.* import io.ktor.util.date.* import kotlin.jvm.* /** * Represents a cookie with name, content and a set of settings such as expiration, visibility and security. * A cookie with neither [expires] nor [maxAge] is a session cookie. * * @property name * @property value * @property encoding - cookie encoding type [CookieEncoding] * @property maxAge number of seconds to keep cookie * @property expires date when it expires * @property domain for which it is set * @property path for which it is set * @property secure send it via secure connection only * @property httpOnly only transfer cookie over HTTP, no access from JavaScript * @property extensions additional cookie extensions */ public data class Cookie( val name: String, val value: String, val encoding: CookieEncoding = CookieEncoding.URI_ENCODING, @get:JvmName("getMaxAgeInt") val maxAge: Int = 0, val expires: GMTDate? = null, val domain: String? = null, val path: String? = null, val secure: Boolean = false, val httpOnly: Boolean = false, val extensions: Map<String, String?> = emptyMap() ) /** * Cooke encoding strategy */ public enum class CookieEncoding { /** * No encoding (could be dangerous) */ RAW, /** * Double quotes with slash-escaping */ DQUOTES, /** * URI encoding */ URI_ENCODING, /** * BASE64 encoding */ BASE64_ENCODING } private val loweredPartNames = setOf("max-age", "expires", "domain", "path", "secure", "httponly", "\$x-enc") /** * Parse server's `Set-Cookie` header value */ public fun parseServerSetCookieHeader(cookiesHeader: String): Cookie { val asMap = parseClientCookiesHeader(cookiesHeader, false) val first = asMap.entries.first { !it.key.startsWith("$") } val encoding = asMap["\$x-enc"]?.let { CookieEncoding.valueOf(it) } ?: CookieEncoding.RAW val loweredMap = asMap.mapKeys { it.key.toLowerCasePreservingASCIIRules() } return Cookie( name = first.key, value = decodeCookieValue(first.value, encoding), encoding = encoding, maxAge = loweredMap["max-age"]?.toIntClamping() ?: 0, expires = loweredMap["expires"]?.fromCookieToGmtDate(), domain = loweredMap["domain"], path = loweredMap["path"], secure = "secure" in loweredMap, httpOnly = "httponly" in loweredMap, extensions = asMap.filterKeys { it.toLowerCasePreservingASCIIRules() !in loweredPartNames && it != first.key } ) } private val clientCookieHeaderPattern = """(^|;)\s*([^;=\{\}\s]+)\s*(=\s*("[^"]*"|[^;]*))?""".toRegex() /** * Parse client's `Cookie` header value */ public fun parseClientCookiesHeader(cookiesHeader: String, skipEscaped: Boolean = true): Map<String, String> = clientCookieHeaderPattern.findAll(cookiesHeader) .map { (it.groups[2]?.value ?: "") to (it.groups[4]?.value ?: "") } .filter { !skipEscaped || !it.first.startsWith("$") } .map { cookie -> if (cookie.second.startsWith("\"") && cookie.second.endsWith("\"")) { cookie.copy(second = cookie.second.removeSurrounding("\"")) } else { cookie } } .toMap() /** * Format `Set-Cookie` header value */ public fun renderSetCookieHeader(cookie: Cookie): String = with(cookie) { renderSetCookieHeader( name, value, encoding, maxAge, expires, domain, path, secure, httpOnly, extensions ) } /** * Format `Cookie` header value */ public fun renderCookieHeader(cookie: Cookie): String = with(cookie) { "$name=${encodeCookieValue(value, encoding)}" } /** * Format `Set-Cookie` header value */ public fun renderSetCookieHeader( name: String, value: String, encoding: CookieEncoding = CookieEncoding.URI_ENCODING, maxAge: Int = 0, expires: GMTDate? = null, domain: String? = null, path: String? = null, secure: Boolean = false, httpOnly: Boolean = false, extensions: Map<String, String?> = emptyMap(), includeEncoding: Boolean = true ): String = ( listOf( cookiePart(name.assertCookieName(), value, encoding), cookiePartUnencoded("Max-Age", if (maxAge > 0) maxAge else null), cookiePartUnencoded("Expires", expires?.toHttpDate()), cookiePart("Domain", domain, CookieEncoding.RAW), cookiePart("Path", path, CookieEncoding.RAW), cookiePartFlag("Secure", secure), cookiePartFlag("HttpOnly", httpOnly) ) + extensions.map { cookiePartExt(it.key.assertCookieName(), it.value) } + if (includeEncoding) cookiePartExt("\$x-enc", encoding.name) else "" ).filter { it.isNotEmpty() } .joinToString("; ") /** * Encode cookie value using the specified [encoding] */ public fun encodeCookieValue(value: String, encoding: CookieEncoding): String = when (encoding) { CookieEncoding.RAW -> when { value.any { it.shouldEscapeInCookies() } -> throw IllegalArgumentException( "The cookie value contains characters that cannot be encoded in RAW format. " + " Consider URL_ENCODING mode" ) else -> value } CookieEncoding.DQUOTES -> when { value.contains('"') -> throw IllegalArgumentException( "The cookie value contains characters that cannot be encoded in DQUOTES format. " + "Consider URL_ENCODING mode" ) value.any { it.shouldEscapeInCookies() } -> "\"$value\"" else -> value } CookieEncoding.BASE64_ENCODING -> value.encodeBase64() CookieEncoding.URI_ENCODING -> value.encodeURLParameter(spaceToPlus = true) } /** * Decode cookie value using the specified [encoding] */ public fun decodeCookieValue(encodedValue: String, encoding: CookieEncoding): String = when (encoding) { CookieEncoding.RAW, CookieEncoding.DQUOTES -> when { encodedValue.trimStart().startsWith("\"") && encodedValue.trimEnd().endsWith("\"") -> encodedValue.trim().removeSurrounding("\"") else -> encodedValue } CookieEncoding.URI_ENCODING -> encodedValue.decodeURLQueryComponent(plusIsSpace = true) CookieEncoding.BASE64_ENCODING -> encodedValue.decodeBase64String() } private fun String.assertCookieName() = when { any { it.shouldEscapeInCookies() } -> throw IllegalArgumentException("Cookie name is not valid: $this") else -> this } private val cookieCharsShouldBeEscaped = setOf(';', ',', '"') private fun Char.shouldEscapeInCookies() = isWhitespace() || this < ' ' || this in cookieCharsShouldBeEscaped @Suppress("NOTHING_TO_INLINE") private inline fun cookiePart(name: String, value: Any?, encoding: CookieEncoding) = if (value != null) "$name=${encodeCookieValue(value.toString(), encoding)}" else "" @Suppress("NOTHING_TO_INLINE") private inline fun cookiePartUnencoded(name: String, value: Any?) = if (value != null) "$name=$value" else "" @Suppress("NOTHING_TO_INLINE") private inline fun cookiePartFlag(name: String, value: Boolean) = if (value) name else "" @Suppress("NOTHING_TO_INLINE") private inline fun cookiePartExt(name: String, value: String?) = if (value == null) cookiePartFlag(name, true) else cookiePart(name, value, CookieEncoding.RAW) private fun String.toIntClamping(): Int = toLong().coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
apache-2.0
d3f700d3ffa30e5ce38e797104d03b23
32.638767
118
0.650733
4.072533
false
false
false
false
airbnb/lottie-android
sample/src/main/kotlin/com/airbnb/lottie/samples/LottiefilesFragment.kt
1
6546
package com.airbnb.lottie.samples import android.content.Context import android.os.Bundle import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingDataAdapter import androidx.paging.PagingSource import androidx.paging.PagingState import androidx.paging.cachedIn import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.airbnb.lottie.samples.api.LottiefilesApi import com.airbnb.lottie.samples.databinding.LottiefilesFragmentBinding import com.airbnb.lottie.samples.model.AnimationData import com.airbnb.lottie.samples.model.AnimationResponse import com.airbnb.lottie.samples.model.CompositionArgs import com.airbnb.lottie.samples.utils.MvRxViewModel import com.airbnb.lottie.samples.utils.hideKeyboard import com.airbnb.lottie.samples.utils.viewBinding import com.airbnb.lottie.samples.views.AnimationItemView import com.airbnb.mvrx.BaseMvRxFragment import com.airbnb.mvrx.MvRxState import com.airbnb.mvrx.MvRxViewModelFactory import com.airbnb.mvrx.ViewModelContext import com.airbnb.mvrx.fragmentViewModel import com.airbnb.mvrx.withState import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch data class LottiefilesState( val mode: LottiefilesMode = LottiefilesMode.Recent, val query: String = "" ) : MvRxState class LottiefilesViewModel(initialState: LottiefilesState, private val api: LottiefilesApi) : MvRxViewModel<LottiefilesState>(initialState) { private var mode = initialState.mode private var query = initialState.query private var dataSource: LottiefilesDataSource? = null val pager = Pager(PagingConfig(pageSize = 16)) { LottiefilesDataSource(api, mode, query).also { dataSource = it } }.flow.cachedIn(viewModelScope) init { selectSubscribe(LottiefilesState::mode, LottiefilesState::query) { mode, query -> this.mode = mode this.query = query dataSource?.invalidate() } } fun setMode(mode: LottiefilesMode) = setState { copy(mode = mode) } fun setQuery(query: String) = setState { copy(query = query) } companion object : MvRxViewModelFactory<LottiefilesViewModel, LottiefilesState> { override fun create(viewModelContext: ViewModelContext, state: LottiefilesState): LottiefilesViewModel { val service = viewModelContext.app<LottieApplication>().lottiefilesService return LottiefilesViewModel(state, service) } } } class LottiefilesDataSource( private val api: LottiefilesApi, val mode: LottiefilesMode, private val query: String ) : PagingSource<Int, AnimationData>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AnimationData> { val page = params.key ?: 1 return try { val response = when (mode) { LottiefilesMode.Popular -> api.getPopular(page) LottiefilesMode.Recent -> api.getRecent(page) LottiefilesMode.Search -> { if (query.isBlank()) { AnimationResponse(page, emptyList(), "", page, null, "", 0, "", 0, 0) } else { api.search(query, page) } } } LoadResult.Page( response.data, if (page == 1) null else page + 1, (page + 1).takeIf { page < response.lastPage } ) } catch (e: Exception) { LoadResult.Error(e) } } override fun getRefreshKey(state: PagingState<Int, AnimationData>): Int? { return state.closestItemToPosition(state.anchorPosition ?: return null)?.id as Int? } } class LottiefilesFragment : BaseMvRxFragment(R.layout.lottiefiles_fragment) { private val binding: LottiefilesFragmentBinding by viewBinding() private val viewModel: LottiefilesViewModel by fragmentViewModel() private object AnimationItemDataDiffCallback : DiffUtil.ItemCallback<AnimationData>() { override fun areItemsTheSame(oldItem: AnimationData, newItem: AnimationData) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: AnimationData, newItem: AnimationData) = oldItem == newItem } private class AnimationItemViewHolder(context: Context) : RecyclerView.ViewHolder(AnimationItemView(context)) { fun bind(data: AnimationData?) { val view = itemView as AnimationItemView view.setTitle(data?.title) view.setPreviewUrl(data?.preview) view.setPreviewBackgroundColor(data?.bgColorInt) view.setOnClickListener { val intent = PlayerActivity.intent(view.context, CompositionArgs(animationData = data)) view.context.startActivity(intent) } } } private val adapter = object : PagingDataAdapter<AnimationData, AnimationItemViewHolder>(AnimationItemDataDiffCallback) { override fun onBindViewHolder(holder: AnimationItemViewHolder, position: Int) = holder.bind(getItem(position)) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = AnimationItemViewHolder(parent.context) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.recyclerView.adapter = adapter viewLifecycleOwner.lifecycleScope.launch { viewModel.pager.collectLatest(adapter::submitData) } binding.tabBar.setRecentClickListener { viewModel.setMode(LottiefilesMode.Recent) requireContext().hideKeyboard() } binding.tabBar.setPopularClickListener { viewModel.setMode(LottiefilesMode.Popular) requireContext().hideKeyboard() } binding.tabBar.setSearchClickListener { viewModel.setMode(LottiefilesMode.Search) requireContext().hideKeyboard() } binding.searchView.query.onEach { query -> viewModel.setQuery(query) }.launchIn(viewLifecycleOwner.lifecycleScope) } override fun invalidate(): Unit = withState(viewModel) { state -> binding.searchView.isVisible = state.mode == LottiefilesMode.Search binding.tabBar.setMode(state.mode) } }
apache-2.0
b57a21bb307f6cf78ef77d9b3548fc0c
38.439759
141
0.701803
4.79912
false
false
false
false
Kerooker/rpg-npc-generator
app/src/main/java/me/kerooker/rpgnpcgenerator/view/random/npc/RandomNpcElementListview.kt
1
1299
package me.kerooker.rpgnpcgenerator.view.random.npc import android.content.Context import android.util.AttributeSet import android.util.Log import androidx.cardview.widget.CardView import kotlinx.android.synthetic.main.randomnpc_element_list_view_item.view.* import kotlinx.android.synthetic.main.randomnpc_element_view.view.random_field_dice class RandomNpcElementListview(context: Context, attrs: AttributeSet) : CardView(context, attrs) { var onDeleteClick = { } var onRandomClick = { } var onManualInput = object : ManualInputListener { override fun onManualInput(text: String) { } } override fun onFinishInflate() { super.onFinishInflate() prepareEventListeners() } private fun prepareEventListeners() { random_npc_minus.setOnClickListener { onDeleteClick() } random_npc_list_item_element.onRandomClick = { onRandomClick() } random_npc_list_item_element.onManualInput = object : ManualInputListener { override fun onManualInput(text: String) { onManualInput.onManualInput(text) } } } fun setText(text: String) { random_npc_list_item_element.text = text } fun setHint(hint: String) { random_npc_list_item_element.setHint(hint) } }
apache-2.0
087c5f3a042152f601d850db73d4297d
33.184211
98
0.698229
4.12381
false
false
false
false
meik99/CoffeeList
app/src/main/java/rynkbit/tk/coffeelist/ui/item/ItemAdapter.kt
1
1864
package rynkbit.tk.coffeelist.ui.item import androidx.recyclerview.widget.RecyclerView import android.view.View import android.view.ViewGroup import android.widget.TextView import rynkbit.tk.coffeelist.R import rynkbit.tk.coffeelist.contract.entity.Item /** * Created by michael on 13/11/16. */ class ItemAdapter : RecyclerView.Adapter<ItemAdapter.ViewHolder>() { private var items = mutableListOf<Item>() var onClickListener: ((item: Item) -> Unit)? = null fun updateItems(itemList: List<Item>) { items.clear() items.addAll(itemList) this.notifyDataSetChanged() } class ViewHolder(internal var view: View) : RecyclerView.ViewHolder(view) { internal var txtItemName: TextView = view.findViewById<View>(R.id.txtItemName) as TextView internal var txtItemPrice: TextView = view.findViewById<View>(R.id.txtItemPrice) as TextView internal var txtItemStock: TextView = view.findViewById<View>(R.id.txtItemStock) as TextView } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemAdapter.ViewHolder { val itemView = View.inflate(parent.context, R.layout.item_card, null) return ViewHolder(itemView) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = items[position] holder.txtItemName.text = item.name holder.txtItemStock.text = String.format( holder.view.context.getString(R.string.item_stock), item.stock ) holder.txtItemPrice.text = String.format( holder.view.context.getString(R.string.item_price), item.price ) holder.view.setOnClickListener { onClickListener?.apply { this(item) } } } override fun getItemCount(): Int { return items.size } }
mit
7e64db3867c5aeebebd944048b04e693
30.066667
100
0.674893
4.324826
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/factory/Factories.kt
1
29609
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @file:JvmName("Factories") package com.github.jonathanxd.kores.factory import com.github.jonathanxd.kores.* import com.github.jonathanxd.kores.base.* import com.github.jonathanxd.kores.base.Annotation import com.github.jonathanxd.kores.base.Retention import com.github.jonathanxd.kores.base.comment.Comments import com.github.jonathanxd.kores.common.KoresNothing import com.github.jonathanxd.kores.common.Void import com.github.jonathanxd.kores.literal.Literals import com.github.jonathanxd.kores.operator.Operator import com.github.jonathanxd.kores.operator.Operators import com.github.jonathanxd.kores.type.PlainKoresType import java.lang.reflect.Type import java.util.* // Access /** * @see Access */ fun accessStatic(): Access = Defaults.ACCESS_STATIC /** * @see Access */ fun accessLocal(): Access = Defaults.ACCESS_LOCAL /** * @see Access */ fun accessThis(): Access = Defaults.ACCESS_THIS /** * @see Access */ fun accessSuper(): Access = Defaults.ACCESS_SUPER // Annotations /** * @see Annotation */ @JvmOverloads fun annotation( retention: com.github.jonathanxd.kores.base.Retention, type: Type, values: Map<String, Any> = emptyMap() ): Annotation = Annotation(type, values, retention) /** * @see Annotation */ @JvmOverloads fun runtimeAnnotation(type: Type, values: Map<String, Any> = emptyMap()): Annotation = annotation(Retention.RUNTIME, type, values) /** * @see Annotation */ @JvmOverloads fun classAnnotation(type: Type, values: Map<String, Any> = emptyMap()): Annotation = annotation(Retention.CLASS, type, values) /** * @see Annotation */ @JvmOverloads fun sourceAnnotation(type: Type, values: Map<String, Any> = emptyMap()): Annotation = annotation(Retention.SOURCE, type, values) /** * @see Annotation */ fun overrideAnnotation(): Annotation = sourceAnnotation(Override::class.java, mapOf()) /** * @see Annotation */ fun deprecatedAnnotation(): Annotation = sourceAnnotation(Deprecated::class.java, mapOf()) /** * @see Annotation */ @JvmOverloads fun annotationProperty( comments: Comments = Comments.Absent, annotations: List<Annotation> = emptyList(), type: Type, name: String, defaultValue: Any? ): AnnotationProperty = AnnotationProperty(comments, annotations, type, name, defaultValue) // Arrays /** * @see ArrayConstructor */ fun createArray( arrayType: Type, dimensions: List<Instruction>, arguments: List<Instruction> ): ArrayConstructor = ArrayConstructor(arrayType, dimensions, arguments) /** * @see ArrayConstructor */ fun createArray1D(arrayType: Type, arguments: List<Instruction>): ArrayConstructor = ArrayConstructor(arrayType, listOf(Literals.INT(arguments.size)), arguments) /** * Creates array of type [arrayType] with [dimension] for receiver instructions. * * @see ArrayConstructor */ fun List<Instruction>.createArray( arrayType: Type, dimensions: List<Instruction> ): ArrayConstructor = ArrayConstructor(arrayType = arrayType, dimensions = dimensions, arguments = this) /** * @see ArrayStore */ fun setArrayValue( arrayType: Type, target: Instruction, index: Instruction, valueType: Type, valueToStore: Instruction ): ArrayStore = ArrayStore(arrayType, target, index, valueType, valueToStore) /** * Sets value at [index] of [receiver array][Instruction] of type [arrayType] to [valueToStore]. * * @see ArrayStore */ fun Instruction.setArrayValue( arrayType: Type, index: Instruction, valueType: Type, valueToStore: Instruction ): ArrayStore = ArrayStore( arrayType = arrayType, target = this, index = index, valueType = valueType, valueToStore = valueToStore ) /** * Sets value at [index] of [receiver array][TypedInstruction] of type [arrayType][TypedInstruction.type] to [valueToStore]. * * @see ArrayStore */ fun TypedInstruction.setArrayValue( index: Instruction, valueType: Type, valueToStore: Instruction ): ArrayStore = ArrayStore( arrayType = this.type, target = this, index = index, valueType = valueType, valueToStore = valueToStore ) /** * @see ArrayLoad */ fun accessArrayValue( arrayType: Type, target: Instruction, index: Instruction, valueType: Type ): ArrayLoad = ArrayLoad(arrayType, target, index, valueType) /** * @see ArrayLoad */ fun TypedInstruction.accessArrayValue( index: Instruction, valueType: Type ): ArrayLoad = ArrayLoad(this.type, this, index, valueType) /** * Accesses the value of [valueType] of [receiver array][Instruction] at [index]. * * @see ArrayLoad */ fun Instruction.accessArrayValue( arrayType: Type, index: Instruction, valueType: Type ): ArrayLoad = ArrayLoad(arrayType = arrayType, target = this, index = index, valueType = valueType) /** * @see ArrayLength */ fun arrayLength(arrayType: Type, target: Instruction): ArrayLength = ArrayLength(arrayType, target) /** * Accesses the length of [receiver array][Instruction] of type [arrayType]. * @see ArrayLength */ fun Instruction.arrayLength(arrayType: Type): ArrayLength = ArrayLength(arrayType, target = this) /** * Accesses the length of [receiver array][Instruction] of type [arrayType]. * @see ArrayLength */ fun TypedInstruction.arrayLength(): ArrayLength = ArrayLength(this.type, target = this) // Enum /** * @see EnumEntry */ fun enumEntry(name: String): EnumEntry = EnumEntry.Builder.builder() .name(name) .build() /** * @see EnumValue */ fun enumValue(enumType: Type, enumEntry: String): EnumValue = EnumValue(enumType, enumEntry) // Variable /** * @see VariableAccess */ fun accessVariable(type: Type, name: String): VariableAccess = VariableAccess(type, name) /** * @see VariableAccess */ fun accessVariable(variable: VariableBase): VariableAccess = accessVariable(variable.type, variable.name) /** * @see VariableDefinition */ fun setVariableValue(type: Type, name: String, value: Instruction): VariableDefinition = VariableDefinition(type, name, value) /** * @see VariableDefinition */ fun setVariableValue(name: String, value: TypedInstruction): VariableDefinition = VariableDefinition(value.type, name, value) /** * @see VariableDefinition */ fun setVariableValue(variable: VariableBase, value: Instruction): VariableDefinition = VariableDefinition(variable.type, variable.name, value) // Field /** * @see FieldAccess */ fun accessField( localization: Type, target: Instruction, type: Type, name: String ): FieldAccess = FieldAccess(localization, target, type, name) /** * Access field with [name] and [type] of [receiver][Instruction] in [localization]. * * @see FieldAccess */ fun Instruction.accessField( localization: Type, type: Type, name: String ): FieldAccess = FieldAccess(localization = localization, target = this, type = type, name = name) /** * Access field with [name] and [type][TypedInstruction.type] of [receiver][Instruction] in [localization]. * * @see FieldAccess */ fun TypedInstruction.accessField( localization: Type, name: String ): FieldAccess = FieldAccess(localization = localization, target = this, type = this.type, name = name) /** * @see FieldAccess */ fun accessThisField(type: Type, name: String): FieldAccess = accessField(Alias.THIS, accessThis(), type, name) /** * @see FieldAccess */ @JvmOverloads fun accessStaticField(localization: Type = Alias.THIS, type: Type, name: String): FieldAccess = accessField(localization, accessStatic(), type, name) /** * @see FieldDefinition */ fun setFieldValue( localization: Type, target: Instruction, type: Type, name: String, value: Instruction ): FieldDefinition = FieldDefinition(localization, target, type, name, value) /** * Sets field [name] of [type] of [receiver][Instruction] in [localization]. * * @see FieldDefinition */ fun Instruction.setFieldValue( localization: Type, type: Type, name: String, value: Instruction ): FieldDefinition = FieldDefinition( localization = localization, target = this, type = type, name = name, value = value ) /** * Sets field [name] of [receiver type][TypedInstruction.type] of [receiver][TypedInstruction] in [localization]. * * @see FieldDefinition */ fun TypedInstruction.setFieldValue( localization: Type, name: String, value: Instruction ): FieldDefinition = FieldDefinition( localization = localization, target = this, type = this.type, name = name, value = value ) /** * @see FieldDefinition */ fun setThisFieldValue(type: Type, name: String, value: Instruction): FieldDefinition = setFieldValue(Alias.THIS, Access.THIS, type, name, value) /** * @see FieldDefinition */ fun TypedInstruction.setToThisFieldValue(name: String): FieldDefinition = setFieldValue(Alias.THIS, Access.THIS, this.type, name, this) /** * @see FieldDefinition */ @JvmOverloads fun setStaticFieldValue( localization: Type = Alias.THIS, type: Type, name: String, value: Instruction ): FieldDefinition = setFieldValue(localization, Access.STATIC, type, name, value) /** * @see FieldDefinition */ @JvmOverloads fun setStaticFieldValue( localization: Type = Alias.THIS, name: String, value: TypedInstruction ): FieldDefinition = setFieldValue(localization, Access.STATIC, value.type, name, value) /** * Invoke getter of a field (`get`+`capitalize(fieldName)`). * * @param invokeType Type of invocation * @param localization Localization of getter * @param target Target of invocation * @param type Type of field. * @param name Name of field. */ fun invokeFieldGetter( invokeType: InvokeType, localization: Type, target: Instruction, type: Type, name: String ): MethodInvocation = invoke(invokeType, localization, target, "get${name.capitalize()}", TypeSpec(type), emptyList()) /** * Invoke getter of a field (`get`+`capitalize(fieldName)`) of [receiver][Instruction]. * * @param invokeType Type of invocation * @param localization Localization of getter * @param type Type of field. * @param name Name of field. */ fun Instruction.invokeFieldGetter( invokeType: InvokeType, localization: Type, type: Type, name: String ): MethodInvocation = invoke( invokeType = invokeType, localization = localization, target = this, name = "get${name.capitalize()}", spec = TypeSpec(type), arguments = emptyList() ) /** * Invoke getter of a field (`get`+`capitalize(fieldName)`) of [receiver][TypedInstruction] and [receiver type][TypedInstruction.type]. * * @param invokeType Type of invocation * @param localization Localization of getter * @param type Type of field. * @param name Name of field. */ fun TypedInstruction.invokeFieldGetter( invokeType: InvokeType, localization: Type, name: String ): MethodInvocation = invoke( invokeType = invokeType, localization = localization, target = this, name = "get${name.capitalize()}", spec = TypeSpec(this.type), arguments = emptyList() ) /** * Invoke setter of a field (`set`+`capitalize(fieldName)`) with [value]. * * @param invokeType Type of invocation * @param localization Localization of setter * @param target Target of invocation * @param type Type of field. * @param name Name of field. * @param value Value to pass to setter */ fun invokeFieldSetter( invokeType: InvokeType, localization: Type, target: Instruction, type: Type, name: String, value: Instruction ): MethodInvocation = invoke( invokeType, localization, target, "set${name.capitalize()}", TypeSpec(Void.type, listOf(type)), listOf(value) ) /** * Invoke setter of a field (`set`+`capitalize(fieldName)`) of [receiver][Instruction] with [value]. * * @param invokeType Type of invocation * @param localization Localization of setter * @param type Type of field. * @param name Name of field. * @param value Value to pass to setter */ fun Instruction.invokeFieldSetter( invokeType: InvokeType, localization: Type, type: Type, name: String, value: Instruction ): MethodInvocation = invoke( invokeType = invokeType, localization = localization, target = this, name = "set${name.capitalize()}", spec = TypeSpec(Void.type, listOf(type)), arguments = listOf(value) ) /** * Invoke setter of a field (`set`+`capitalize(fieldName)`) of [receiver][Instruction] of [receiver type][Instruction.type] with [value]. * * @param invokeType Type of invocation * @param localization Localization of setter * @param type Type of field. * @param name Name of field. * @param value Value to pass to setter */ fun TypedInstruction.invokeFieldSetter( invokeType: InvokeType, localization: Type, name: String, value: Instruction ): MethodInvocation = invoke( invokeType = invokeType, localization = localization, target = this, name = "set${name.capitalize()}", spec = TypeSpec(Void.type, listOf(this.type)), arguments = listOf(value) ) // Return /** * @see Return */ fun returnValue(type: Type, value: Instruction) = Return(type, value) /** * @see Return */ fun returnValue(value: TypedInstruction) = Return(value.type, value) /** * Void return (Java: `return;`) * @see Return */ fun returnVoid(): Return = returnValue(Void.type, Void) /** * Creates a [Return] of receiver instruction of type [type]. */ fun Instruction.returnValue(type: Type) = returnValue(type, this) /** * Creates a [Return] of receiver instruction of type [type]. */ fun TypedInstruction.returnSelfValue() = returnValue(this.type, this) // Parameter /** * @see KoresParameter */ @JvmOverloads fun parameter( annotations: List<Annotation> = emptyList(), modifiers: Set<KoresModifier> = emptySet(), type: Type, name: String ) = KoresParameter(annotations, modifiers, type, name) /** * @see KoresParameter */ @JvmOverloads fun finalParameter(annotations: List<Annotation> = emptyList(), type: Type, name: String) = KoresParameter(annotations, EnumSet.of(KoresModifier.FINAL), type, name) // Operate /** * @see Operate */ fun operate(target: Instruction, operation: Operator.Math, value: Instruction): Operate = Operate(target, operation, value) /** * Operate variable value and assign the result to the variable * * @see Operate */ fun operateAndAssign( variable: VariableBase, operation: Operator.Math, value: Instruction ): VariableDefinition = setVariableValue( variable.variableType, variable.name, operate(accessVariable(variable.variableType, variable.name), operation, value) ) /** * Operate variable value and assign the result to the variable * * @see Operate */ fun operateAndAssign( type: Type, name: String, operation: Operator.Math, value: Instruction ): VariableDefinition = setVariableValue(type, name, operate(accessVariable(type, name), operation, value)) /** * Operate field value and assign the result to the field * * @see Operate */ fun operateAndAssign( field: FieldBase, operation: Operator.Math, value: Instruction ): FieldDefinition = setFieldValue( field.localization, field.target, field.type, field.name, operate( accessField(field.localization, field.target, field.type, field.name), operation, value ) ) /** * Operate field value and assign the result to the field * * @see Operate */ fun operateAndAssign( localization: Type, target: Instruction, type: Type, name: String, operation: Operator.Math, value: Instruction ): FieldDefinition = setFieldValue( localization, target, type, name, operate(accessField(localization, target, type, name), operation, value) ) // Throw /** * @see ThrowException */ fun throwException(part: Instruction) = ThrowException(part) /** * Throws [receiver][Instruction] as exception. * * @see ThrowException */ fun Instruction.throwThisException() = ThrowException(this) // Cast /** * @see Cast */ fun cast(from: Type?, to: Type, part: Instruction): Cast = Cast(from, to, part) /** * @see Cast */ fun cast(to: Type, part: TypedInstruction): Cast = Cast(part.type, to, part) /** * Creates a cast of receiver from type [from] to type [to]. */ fun Instruction.cast(from: Type?, to: Type) = cast(from, to, this) /** * Creates a cast of receiver from type [from] to type [to]. */ fun TypedInstruction.cast(to: Type) = cast(this.type, to, this) // IfExpr /** * @see IfExpr */ fun ifExpr( expr1: Instruction, operation: Operator.Conditional, expr2: Instruction ): IfExpr = IfExpr(expr1, operation, expr2) /** * @see IfExpr */ fun check(expr1: Instruction, operation: Operator.Conditional, expr2: Instruction): IfExpr = ifExpr(expr1, operation, expr2) /** * Helper function to create if expressions. This function converts a sequence of: [IfExpr], * [Operator], [IfGroup], [List] and [KoresPart] into a list of expressions (which for the three first types * no conversion is done), if a [List] is found, it will be converted to a [IfGroup]. If a [KoresPart] is found * it will be converted to a [IfExpr] that checks if the `codePart` is equal to `true`. * * @param objects Sequence of operations. * @return Sequence of if expressions. * @throws IllegalArgumentException If an element is not of a valid type. */ fun ifExprs(vararg objects: Any): List<Instruction> { val list = ArrayList<Instruction>() for (any in objects) { if (any is IfExpr || any is Operator || any is IfGroup) { if (any is Operator) if (any != Operators.OR && any != Operators.AND && any != Operators.BITWISE_INCLUSIVE_OR && any != Operators.BITWISE_EXCLUSIVE_OR && any != Operators.BITWISE_AND ) throw IllegalArgumentException("Input object is not a valid operator, it must be: OR or AND or short-circuit BITWISE_INCLUSIVE_OR, BITWISE_EXCLUSIVE_OR or BITWISE_AND. Current: $any") list.add(any as Instruction) } else if (any is Instruction) { list.add(checkTrue(any)) } else if (any is List<*>) { @Suppress("UNCHECKED_CAST") val other = any as List<Instruction> list.add(IfGroup(other)) } else { throw IllegalArgumentException("Illegal input object: '$any'.") } } return list } /** * [IfExpr] that checks if [part] is not `null` */ fun checkNotNull(part: Instruction) = ifExpr(part, Operators.NOT_EQUAL_TO, Literals.NULL) /** * [IfExpr] that checks if [receiver][Instruction] is not `null` */ fun Instruction.checkThisNotNull() = ifExpr(this, Operators.NOT_EQUAL_TO, Literals.NULL) /** * [IfExpr] that checks if [part] is `null` */ fun checkNull(part: Instruction) = ifExpr(part, Operators.EQUAL_TO, Literals.NULL) /** * [IfExpr] that checks if [receiver][Instruction] is `null` */ fun Instruction.checkThisNull() = ifExpr(this, Operators.EQUAL_TO, Literals.NULL) /** * [IfExpr] that checks if [part] is `true` */ fun checkTrue(part: Instruction) = ifExpr(part, Operators.EQUAL_TO, Literals.TRUE) /** * [IfExpr] that checks if [receiver][Instruction] is `true` */ fun Instruction.checThiskTrue() = ifExpr(this, Operators.EQUAL_TO, Literals.TRUE) /** * [IfExpr] that checks if [part] is `false` */ fun checkFalse(part: Instruction) = ifExpr(part, Operators.EQUAL_TO, Literals.FALSE) /** * [IfExpr] that checks if [receiver][Instruction] is `false` */ fun Instruction.checkThisFalse() = ifExpr(this, Operators.EQUAL_TO, Literals.FALSE) // IfStatement /** * @see IfStatement */ @JvmOverloads fun ifStatement( expressions: List<Instruction>, body: Instructions, elseStatement: Instructions = Instructions.empty() ): IfStatement = IfStatement(expressions, body, elseStatement) /** * @see IfStatement */ @JvmOverloads fun ifStatement( ifExpr: IfExpr, body: Instructions, elseStatement: Instructions = Instructions.empty() ): IfStatement = IfStatement(listOf(ifExpr), body, elseStatement) // Label /** * @see Label */ @JvmOverloads fun label(name: String, body: Instructions = Instructions.empty()): Label = Label(name, body) // ControlFlow /** * @see ControlFlow */ @JvmOverloads fun controlFlow(type: ControlFlow.Type, at: Label? = null): ControlFlow = ControlFlow(type, at) /** * `break` * * `break @at` * * @see ControlFlow */ @JvmOverloads fun breakFlow(at: Label? = null) = controlFlow(ControlFlow.Type.BREAK, at) /** * `continue` * * `continue @at` * * @see ControlFlow */ @JvmOverloads fun continueFlow(at: Label? = null) = controlFlow(ControlFlow.Type.CONTINUE, at) // InstanceOfCheck /** * Checks if [part] is instance of [type] * * @see InstanceOfCheck */ fun isInstanceOf(part: Instruction, type: Type): InstanceOfCheck = InstanceOfCheck(part, type) /** * Checks if [receiver][Instruction] is instance of [type] * * @see InstanceOfCheck */ fun Instruction.isThisInstanceOf(type: Type): InstanceOfCheck = InstanceOfCheck(this, type) // TryStatement /** * @see TryStatement */ @JvmOverloads fun tryStatement( body: Instructions, catchStatements: List<CatchStatement>, finallyStatement: Instructions = Instructions.empty() ): TryStatement = TryStatement(body, catchStatements, finallyStatement) // CatchStatement /** * @see CatchStatement */ fun catchStatement( exceptionTypes: List<Type>, variable: VariableDeclaration, body: Instructions ): CatchStatement = CatchStatement(exceptionTypes, variable, body) /** * @see CatchStatement */ fun catchStatement( exceptionType: Type, variable: VariableDeclaration, body: Instructions ): CatchStatement = catchStatement(listOf(exceptionType), variable, body) // TryWithResources /** * @see TryWithResources */ @JvmOverloads fun tryWithResources( variable: VariableDeclaration, body: Instructions, catchStatements: List<CatchStatement> = emptyList(), finallyStatement: Instructions = Instructions.empty() ): TryWithResources = TryWithResources(variable, body, catchStatements, finallyStatement) // WhileStatement /** * @see [WhileStatement] */ @JvmOverloads fun whileStatement( type: WhileStatement.Type = WhileStatement.Type.WHILE, expressions: List<Instruction>, body: Instructions ): WhileStatement = WhileStatement(type, expressions, body) /** * @see [WhileStatement] */ fun doWhileStatement(expressions: List<Instruction>, body: Instructions): WhileStatement = WhileStatement(WhileStatement.Type.DO_WHILE, expressions, body) // ForStatement /** * @see ForStatement */ fun forStatement( forInit: Instruction, forExpression: List<Instruction>, forUpdate: Instruction, body: Instructions ): ForStatement = ForStatement(listOf(forInit), forExpression, listOf(forUpdate), body) /** * @see ForStatement */ fun forStatement( forInit: List<Instruction>, forExpression: List<Instruction>, forUpdate: List<Instruction>, body: Instructions ): ForStatement = ForStatement(forInit, forExpression, forUpdate, body) /** * @see ForStatement */ fun forStatement( forInit: Instruction, forExpression: IfExpr, forUpdate: Instruction, body: Instructions ): ForStatement = forStatement(forInit, listOf(forExpression), forUpdate, body) // ForEachStatement /** * @see ForEachStatement */ fun forEachStatement( variable: VariableDeclaration, iterationType: IterationType, iterableElement: Instruction, body: Instructions ): ForEachStatement = ForEachStatement(variable, iterationType, iterableElement, body) /** * Loop elements of an iterable element. * * @see ForEachStatement */ fun forEachIterable( variable: VariableDeclaration, iterableElement: Instruction, body: Instructions ): ForEachStatement = forEachStatement(variable, IterationType.ITERABLE_ELEMENT, iterableElement, body) /** * Loop elements of an array. * * @see ForEachStatement */ fun forEachArray( variable: VariableDeclaration, iterableElement: Instruction, body: Instructions ): ForEachStatement = forEachStatement(variable, IterationType.ARRAY, iterableElement, body) // Switch & Case /** * @see SwitchStatement */ fun switchStatement( value: Instruction, switchType: SwitchType, cases: List<Case> ): SwitchStatement = SwitchStatement(value, switchType, cases) /** * Switch [receiver][Instruction] * * @see SwitchStatement */ fun Instruction.switchThisStatement( switchType: SwitchType, cases: List<Case> ): SwitchStatement = SwitchStatement(this, switchType, cases) /** * @see SwitchStatement */ fun switchInt(value: Instruction, cases: List<Case>): SwitchStatement = switchStatement(value, SwitchType.NUMERIC, cases) /** * Case [receiver][Instruction] int. * * @see SwitchStatement */ fun Instruction.switchThisInt(cases: List<Case>): SwitchStatement = switchStatement(this, SwitchType.NUMERIC, cases) /** * @see SwitchStatement */ fun switchString(value: Instruction, cases: List<Case>): SwitchStatement = switchStatement(value, SwitchType.STRING, cases) /** * Case [receiver][Instruction] string. * @see SwitchStatement */ fun Instruction.switchThisString(cases: List<Case>): SwitchStatement = switchStatement(this, SwitchType.STRING, cases) /** * @see SwitchStatement */ fun switchEnum(value: Instruction, cases: List<Case>): SwitchStatement = switchStatement(value, SwitchType.ENUM, cases) /** * Case [receiver][Instruction] enum. * @see SwitchStatement */ fun Instruction.switchThisEnum(cases: List<Case>): SwitchStatement = switchStatement(this, SwitchType.ENUM, cases) /** * @see Case */ fun caseStatement(value: Instruction, body: Instructions): Case = Case(value, body) /** * Case [receiver][Instruction] value. * @see Case */ fun Instruction.caseThis(body: Instructions): Case = Case(this, body) /** * @see Case */ fun defaultCase(body: Instructions): Case = caseStatement(KoresNothing, body) // PlainKoresType /** * @see PlainKoresType */ fun plainType(name: String, isInterface: Boolean): PlainKoresType = PlainKoresType(name, isInterface) /** * @see PlainKoresType */ fun plainInterfaceType(name: String): PlainKoresType = plainType(name, true) /** * @see PlainKoresType */ fun plainClassType(name: String): PlainKoresType = plainType(name, false) // TypeSpec /** * @see TypeSpec */ fun typeSpec(rtype: Type) = TypeSpec(rtype, emptyList()) /** * @see TypeSpec */ fun typeSpec(rtype: Type, ptypes: List<Type>) = TypeSpec(rtype, ptypes.toList()) /** * @see TypeSpec */ fun typeSpec(rtype: Type, ptype: Type) = typeSpec(rtype, listOf(ptype)) /** * @see TypeSpec */ fun typeSpec(rtype: Type, vararg ptypes: Type) = typeSpec(rtype, ptypes.toList()) /** * @see TypeSpec */ fun voidTypeSpec(vararg ptypes: Type) = typeSpec(Types.VOID, ptypes.toList()) /** * @see TypeSpec */ fun constructorTypeSpec(vararg ptypes: Type) = typeSpec(Types.VOID, ptypes.toList()) /** * Creates a [Line] instance linking [value] to [line number][line]. */ fun line(line: Int, value: Instruction): Line = if (value is Typed) Line.TypedLine(line, value, value.type) else Line.NormalLine(line, value) /** * Creates a [Line] of number [line] */ fun Instruction.line(line: Int) = line(line, this)
mit
53f78ab340273102ffda459e5afbb74d
23.270492
203
0.684116
3.926402
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/binarysearch/binary-search6.kt
1
1113
package katas.kotlin.binarysearch import datsok.shouldEqual import org.junit.Test class BinarySearchTests { @Test fun `find index of an element in the sorted list`() { listOf(1).findIndexOf(0) shouldEqual -1 listOf(1).findIndexOf(1) shouldEqual 0 listOf(1).findIndexOf(2) shouldEqual -1 listOf(1, 2).findIndexOf(0) shouldEqual -1 listOf(1, 2).findIndexOf(1) shouldEqual 0 listOf(1, 2).findIndexOf(2) shouldEqual 1 listOf(1, 2).findIndexOf(3) shouldEqual -1 listOf(1, 2, 3).findIndexOf(0) shouldEqual -1 listOf(1, 2, 3).findIndexOf(1) shouldEqual 0 listOf(1, 2, 3).findIndexOf(2) shouldEqual 1 listOf(1, 2, 3).findIndexOf(3) shouldEqual 2 listOf(1, 2, 3).findIndexOf(4) shouldEqual -1 } } private fun <E: Comparable<E>> List<E>.findIndexOf(element: E): Int { var from = 0 var to = size while (from < to) { val index = (from + to) / 2 if (element < this[index]) to = index else if (this[index] < element) from = index + 1 else return index } return -1 }
unlicense
c64484b29495f42980d9eb6b4341961d
30.8
69
0.621743
3.637255
false
true
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/redshift/src/main/kotlin/com/kotlin/redshift/ListEvents.kt
1
2151
// snippet-sourcedescription:[ListEvents.kt demonstrates how to list events for a given cluster.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Redshift] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.redshift // snippet-start:[redshift.kotlin._events.import] import aws.sdk.kotlin.services.redshift.RedshiftClient import aws.sdk.kotlin.services.redshift.model.DescribeEventsRequest import aws.sdk.kotlin.services.redshift.model.SourceType import kotlin.system.exitProcess // snippet-end:[redshift.kotlin._events.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <clusterId> <eventSourceType> Where: clusterId - The id of the cluster. eventSourceType - The event type (ie, cluster). """ if (args.size != 2) { println(usage) exitProcess(0) } val clusterId = args[0] val eventSourceType = args[1] listRedShiftEvents(clusterId, eventSourceType) } // snippet-start:[redshift.kotlin._events.main] suspend fun listRedShiftEvents(clusterId: String?, eventSourceType: String) { val request = DescribeEventsRequest { sourceIdentifier = clusterId sourceType = SourceType.fromValue(eventSourceType) startTime = aws.smithy.kotlin.runtime.time.Instant.fromEpochSeconds("1634058260") maxRecords = 20 } RedshiftClient { region = "us-west-2" }.use { redshiftClient -> val eventsResponse = redshiftClient.describeEvents(request) eventsResponse.events?.forEach { event -> println("Source type is ${event.sourceType}") println("Event message is ${event.message}") } } } // snippet-end:[redshift.kotlin._events.main]
apache-2.0
c366d5be8d399f2edcf93a570113d364
31.609375
97
0.680149
4.02809
false
false
false
false
encircled/Joiner
joiner-kotlin/src/main/java/cz/encircled/joiner/kotlin/JoinOps.kt
1
3024
package cz.encircled.joiner.kotlin import com.querydsl.core.types.EntityPath import com.querydsl.core.types.Predicate import com.querydsl.core.types.dsl.CollectionPathBase import cz.encircled.joiner.query.join.J import cz.encircled.joiner.query.join.JoinDescription interface JoinOps { var lastJoin: JoinDescription? infix fun JoinDescription.leftJoin(p: EntityPath<*>): JoinDescription { return this.nested(J.left(p)) } infix fun JoinDescription.innerJoin(p: EntityPath<*>): JoinDescription { return this.nested(J.inner(p)) } infix fun EntityPath<*>.leftJoin(p: EntityPath<*>): JoinDescription { return JoinDescription(this).nested(J.left(p)) } infix fun EntityPath<*>.leftJoin(p: JoinDescription): JoinDescription { return JoinDescription(this).nested(p.left()) } infix fun EntityPath<*>.innerJoin(p: JoinDescription): JoinDescription { return JoinDescription(this).nested(p.inner()) } infix fun EntityPath<*>.innerJoin(p: EntityPath<*>): JoinDescription { return JoinDescription(this).nested(J.inner(p)) } infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.leftJoin(j: JoinDescription): JoinerKtQuery<FROM_C, PROJ, FROM> { val join = j.left() lastJoin = j delegate.joins(join) return this } infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.leftJoin(p: EntityPath<*>): JoinerKtQuery<FROM_C, PROJ, FROM> { val join = J.left(p) lastJoin = join delegate.joins(join) return this } infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.leftJoin(p: CollectionPathBase<*, *, *>): JoinerKtQuery<FROM_C, PROJ, FROM> { val join = J.left(p) lastJoin = join delegate.joins(join) return this } infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.innerJoin(j: JoinDescription): JoinerKtQuery<FROM_C, PROJ, FROM> { val join = j.inner() lastJoin = j delegate.joins(join) return this } infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.innerJoin(p: EntityPath<*>): JoinerKtQuery<FROM_C, PROJ, FROM> { val join = J.inner(p) lastJoin = join delegate.joins(join) return this } infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.innerJoin(p: CollectionPathBase<*, *, *>): JoinerKtQuery<FROM_C, PROJ, FROM> { val join = J.inner(p) lastJoin = join delegate.joins(join) return this } infix fun <FROM_C, PROJ, FROM : EntityPath<FROM_C>> JoinerKtQuery<FROM_C, PROJ, FROM>.on(p: Predicate): JoinerKtQuery<FROM_C, PROJ, FROM> { val join = lastJoin ?: throw IllegalStateException("Add a join statement before 'on' condition") join.on(p) return this } }
apache-2.0
d301c454e1581eed74265f18c78fb35f
34.576471
168
0.650794
3.483871
false
false
false
false
paplorinc/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/AccessorProcessor.kt
1
2112
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors import com.intellij.lang.java.beans.PropertyKind import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.ResolveState import com.intellij.psi.scope.ElementClassHint import com.intellij.util.SmartList import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.util.checkKind import org.jetbrains.plugins.groovy.lang.psi.util.getAccessorName import org.jetbrains.plugins.groovy.lang.resolve.AccessorResolveResult import org.jetbrains.plugins.groovy.lang.resolve.GenericAccessorResolveResult import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments import org.jetbrains.plugins.groovy.lang.resolve.imports.importedNameKey class AccessorProcessor( propertyName: String, private val propertyKind: PropertyKind, private val arguments: Arguments?, private val place: PsiElement ) : ProcessorWithCommonHints(), GrResolverProcessor<GroovyResolveResult> { private val accessorName = propertyKind.getAccessorName(propertyName) init { nameHint(accessorName) elementClassHint(ElementClassHint.DeclarationKind.METHOD) hint(GroovyResolveKind.HINT_KEY, GroovyResolveKind.EMPTY_HINT) } override fun execute(element: PsiElement, state: ResolveState): Boolean { if (element !is PsiMethod) return true val elementName = state[importedNameKey] ?: element.name if (elementName != accessorName) return true if (!element.checkKind(propertyKind)) return true myResults += if (element.hasTypeParameters()) { GenericAccessorResolveResult(element, place, state, arguments) } else { AccessorResolveResult(element, place, state, arguments) } return true } private val myResults = SmartList<GroovyResolveResult>() override val results: List<GroovyResolveResult> get() = myResults }
apache-2.0
c91c8afa2598a7ec90bd3c33677a26f1
38.111111
140
0.797822
4.390852
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/ide/navbar/ide/NavBarService.kt
2
1107
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.navbar.ide import com.intellij.ide.IdeEventQueue import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow class NavBarService(val myProject: Project) : Disposable { private val cs = CoroutineScope(CoroutineName("NavigationBarStore")) private val myEventFlow = MutableSharedFlow<Unit>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) private val navigationBar = NavigationBar(myProject, cs, myEventFlow.asSharedFlow()) init { IdeEventQueue.getInstance().addActivityListener(Runnable { myEventFlow.tryEmit(Unit) }, this) } override fun dispose() { cs.coroutineContext.cancel() } fun getPanel() = navigationBar.getComponent() }
apache-2.0
a980efd335a0e769b9191fc540e878af
31.558824
120
0.794941
4.651261
false
false
false
false
NeatoRobotics/neato-sdk-android
Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/models/RobotState.kt
1
4276
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.models import android.os.Parcelable import kotlinx.android.parcel.Parcelize import java.util.ArrayList import java.util.HashMap @Parcelize data class RobotState(var state: State = State.INVALID, var action: Action = Action.INVALID, var cleaningCategory: CleaningCategory = CleaningCategory.HOUSE, var cleaningModifier: CleaningModifier = CleaningModifier.NORMAL, var cleaningMode: CleaningMode = CleaningMode.TURBO, var navigationMode: NavigationMode = NavigationMode.NORMAL, var isCharging: Boolean = false, var isDocked: Boolean = false, var isDockHasBeenSeen: Boolean = false, var isScheduleEnabled: Boolean = false, var isStartAvailable: Boolean = false, var isStopAvailable: Boolean = false, var isPauseAvailable: Boolean = false, var isResumeAvailable: Boolean = false, var isGoToBaseAvailable: Boolean = false, var cleaningSpotWidth: Int = 0, var cleaningSpotHeight: Int = 0, var mapId: String? = null, var boundary: Boundary? = null, var boundaries: MutableList<Boundary> = mutableListOf(), var scheduleEvents: ArrayList<ScheduleEvent> = ArrayList(), var availableServices: HashMap<String, String> = HashMap(), var message: String? = null, var error: String? = null, var alert: String? = null, var charge: Double = 0.toDouble(), var serial: String? = null, var result: String? = null, var robotRemoteProtocolVersion: Int = 0, var robotModelName: String? = null, var firmware: String? = null) : Parcelable enum class State(val value: Int) { INVALID(0), IDLE(1), BUSY(2), PAUSED(3), ERROR(4); companion object { fun fromValue(value: Int): State { val state = State.values().firstOrNull { it.value == value } return state?:INVALID } } } enum class Action(val value: Int) { INVALID(0), HOUSE_CLEANING(1), SPOT_CLEANING(2), MANUAL_CLEANING(3), DOCKING(4), USER_MENU_ACTIVE(5), SUSPENDED_CLEANING(6), UPDATING(7), COPYING_LOGS(8), RECOVERING_LOCATION(9), IEC_TEST(10), MAP_CLEANING(11), EXPLORING_MAP(12), MAP_RETRIEVING(13), MAP_CREATING(14), EXPLORATION_SUSPENDED(15); companion object { fun fromValue(value: Int): Action { val action = Action.values().firstOrNull { it.value == value } return action?: Action.INVALID } } } enum class CleaningCategory(val value: Int) { INVALID(0), MANUAL(1), HOUSE(2), SPOT(3), MAP(4); companion object { fun fromValue(value: Int): CleaningCategory { val cc = CleaningCategory.values().firstOrNull { it.value == value } return cc?:INVALID } } } enum class CleaningModifier(val value: Int) { INVALID(0), NORMAL(1), DOUBLE(2); companion object { fun fromValue(value: Int): CleaningModifier { val cm = CleaningModifier.values().firstOrNull { it.value == value } return cm?:INVALID } } } enum class CleaningMode(val value: Int) { INVALID(0), ECO(1), TURBO(2); companion object { fun fromValue(value: Int): CleaningMode { val cm = CleaningMode.values().firstOrNull { it.value == value } return cm?:INVALID } } } enum class NavigationMode(val value: Int) { NORMAL(1), EXTRA_CARE(2), DEEP(3); companion object { fun fromValue(value: Int): NavigationMode { val nm = NavigationMode.values().firstOrNull { it.value == value } return nm?:NORMAL } } }
mit
a35a2e331141305dafe4ddbe7122edda
28.902098
87
0.551918
4.431088
false
false
false
false
BartoszJarocki/Design-patterns-in-Kotlin
src/structural/Composite.kt
1
1498
package structural import java.util.* /** "Component" */ interface Graphic { fun print() } /** "Composite" */ class CompositeGraphic(val graphics: ArrayList<Graphic> = ArrayList()) : Graphic { //Prints the graphic. override fun print() = graphics.forEach(Graphic::print) //Adds the graphic to the composition. fun add(graphic: Graphic) { graphics.add(graphic) } //Removes the graphic from the composition. fun remove(graphic: Graphic) { graphics.remove(graphic) } } class Ellipse : Graphic { override fun print() = println("Ellipse") } class Square : Graphic { override fun print() = println("Square") } fun main(args: Array<String>) { //Initialize four ellipses val ellipse1 = Ellipse() val ellipse2 = Ellipse() val ellipse3 = Ellipse() val ellipse4 = Ellipse() //Initialize four squares val square1 = Square() val square2 = Square() val square3 = Square() val square4 = Square() //Initialize three composite graphics val graphic = CompositeGraphic() val graphic1 = CompositeGraphic() val graphic2 = CompositeGraphic() //Composes the graphics graphic1.add(ellipse1) graphic1.add(ellipse2) graphic1.add(square1) graphic1.add(ellipse3) graphic2.add(ellipse4) graphic2.add(square2) graphic2.add(square3) graphic2.add(square4) graphic.add(graphic1) graphic.add(graphic2) //Prints the complete graphic graphic.print() }
apache-2.0
ac596bf1935599f9446dc2e1367b0d7b
20.724638
82
0.661549
3.841026
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/index/AemComponentClassicDialogIndex.kt
1
1474
package com.aemtools.index import com.aemtools.index.dataexternalizer.AemComponentClassicDialogDefinitionExternalizer import com.aemtools.index.indexer.AemComponentClassicDialogIndexer import com.aemtools.index.model.dialog.AemComponentClassicDialogDefinition import com.intellij.util.indexing.DataIndexer import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FileContent import com.intellij.util.indexing.ID import com.intellij.util.io.DataExternalizer import com.intellij.xml.index.XmlIndex /** * Indexes classic dialog files (dialog.xml). * * @author Dmytro Troynikov */ class AemComponentClassicDialogIndex : XmlIndex<AemComponentClassicDialogDefinition>() { companion object { val AEM_COMPONENT_CLASSIC_DIALOG_INDEX_ID: ID<String, AemComponentClassicDialogDefinition> = ID.create<String, AemComponentClassicDialogDefinition>("AemComponentClassicDialogDefinitionIndex") } override fun getValueExternalizer(): DataExternalizer<AemComponentClassicDialogDefinition> = AemComponentClassicDialogDefinitionExternalizer override fun getName(): ID<String, AemComponentClassicDialogDefinition> = AEM_COMPONENT_CLASSIC_DIALOG_INDEX_ID override fun getIndexer(): DataIndexer<String, AemComponentClassicDialogDefinition, FileContent> = AemComponentClassicDialogIndexer override fun getInputFilter(): FileBasedIndex.InputFilter = FileBasedIndex.InputFilter { it.name == "dialog.xml" } }
gpl-3.0
6b7211cd97291cb064e2460b13b29344
35.85
108
0.818182
4.63522
false
false
false
false
matrix-org/matrix-android-sdk
matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/cryptostore/db/model/DeviceInfoEntity.kt
1
1778
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.androidsdk.crypto.cryptostore.db.model import io.realm.RealmObject import io.realm.RealmResults import io.realm.annotations.LinkingObjects import io.realm.annotations.PrimaryKey import org.matrix.androidsdk.crypto.cryptostore.db.deserializeFromRealm import org.matrix.androidsdk.crypto.cryptostore.db.serializeForRealm import org.matrix.androidsdk.crypto.data.MXDeviceInfo fun DeviceInfoEntity.Companion.createPrimaryKey(userId: String, deviceId: String) = "$userId|$deviceId" // deviceInfoData contains serialized data open class DeviceInfoEntity(@PrimaryKey var primaryKey: String = "", var deviceId: String? = null, var identityKey: String? = null, var deviceInfoData: String? = null) : RealmObject() { // Deserialize data fun getDeviceInfo(): MXDeviceInfo? { return deserializeFromRealm(deviceInfoData) } // Serialize data fun putDeviceInfo(deviceInfo: MXDeviceInfo?) { deviceInfoData = serializeForRealm(deviceInfo) } @LinkingObjects("devices") val users: RealmResults<UserEntity>? = null companion object }
apache-2.0
67618a447362c5cec9e50bfa9641fd5b
34.56
103
0.723285
4.501266
false
false
false
false
Tolriq/yatse-avreceiverplugin-api
sample/src/main/java/tv/yatse/plugin/avreceiver/sample/SettingsActivity.kt
1
4598
/* * Copyright 2015 Tolriq / Genimee. * 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 tv.yatse.plugin.avreceiver.sample import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.EditText import android.widget.ImageButton import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.google.android.material.snackbar.Snackbar import tv.yatse.plugin.avreceiver.api.AVReceiverPluginService import tv.yatse.plugin.avreceiver.api.YatseLogger import tv.yatse.plugin.avreceiver.sample.helpers.PreferencesHelper /** * Sample SettingsActivity that handle correctly the parameters passed by Yatse. * * * You need to save the passed extra [AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID] * and return it in the result intent. * * * **Production plugin should make input validation and tests before accepting the user input and returning RESULT_OK.** */ class SettingsActivity : AppCompatActivity() { private var mMediaCenterUniqueId: String = "" private var mMediaCenterName: String = "" private var mMuted = false private lateinit var mViewSettingsTitle: TextView private lateinit var mViewReceiverIP: EditText private lateinit var mViewMute: ImageButton @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) if (intent != null) { mMediaCenterUniqueId = intent.getStringExtra(AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID) ?: "" mMediaCenterName = intent.getStringExtra(AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_NAME) ?: "" } if (TextUtils.isEmpty(mMediaCenterUniqueId)) { YatseLogger.logError(applicationContext, TAG, "Error : No media center unique id sent") Snackbar.make(findViewById(R.id.receiver_settings_content), "Wrong data sent by Yatse !", Snackbar.LENGTH_LONG).show() } mViewSettingsTitle = findViewById(R.id.receiver_settings_title) mViewReceiverIP = findViewById(R.id.receiver_ip) mViewMute = findViewById(R.id.btn_toggle_mute) mViewSettingsTitle.text = "${getString(R.string.sample_plugin_settings)} $mMediaCenterName" mViewReceiverIP.setText( PreferencesHelper.getInstance(applicationContext).hostIp(mMediaCenterUniqueId) ) findViewById<View>(R.id.btn_toggle_mute).setOnClickListener { mViewMute.setImageResource(if (!mMuted) R.drawable.ic_volume_low else R.drawable.ic_volume_off) mMuted = !mMuted Snackbar.make(findViewById(R.id.receiver_settings_content), "Toggling mute", Snackbar.LENGTH_LONG).show() } findViewById<View>(R.id.btn_vol_down).setOnClickListener { Snackbar.make(findViewById(R.id.receiver_settings_content), "Volume down", Snackbar.LENGTH_LONG).show() } findViewById<View>(R.id.btn_vol_up).setOnClickListener { Snackbar.make(findViewById(R.id.receiver_settings_content), "Volume up", Snackbar.LENGTH_LONG).show() } findViewById<View>(R.id.btn_ok).setOnClickListener { PreferencesHelper.getInstance(applicationContext) .hostIp(mMediaCenterUniqueId, mViewReceiverIP.text.toString()) setResult( Activity.RESULT_OK, Intent() .putExtra(AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID, mMediaCenterUniqueId) ) finish() } findViewById<View>(R.id.btn_cancel).setOnClickListener { setResult( Activity.RESULT_CANCELED, Intent() .putExtra(AVReceiverPluginService.EXTRA_STRING_MEDIA_CENTER_UNIQUE_ID, mMediaCenterUniqueId) ) finish() } } companion object { private const val TAG = "SettingsActivity" } }
apache-2.0
61c24e59dc31d75d2cf25c30f32dff2d
42.8
130
0.709004
4.370722
false
false
false
false
udevbe/westford
compositor/src/main/kotlin/org/westford/compositor/core/Rectangle.kt
3
2193
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.compositor.core import javax.annotation.Nonnegative data class Rectangle(val x: Int, val y: Int, @param:Nonnegative val width: Int, @param:Nonnegative val height: Int) { constructor(position: Point, width: Int, height: Int) : this(position.x, position.y, width, height) val position: Point get() = Point(x, y) companion object { val ZERO = Rectangle(0, 0, 0, 0) fun create(a: Point, b: Point): Rectangle { val width: Int val x: Int if (a.x > b.x) { width = a.x - b.x x = b.x } else { width = b.x - a.x x = a.x } val height: Int val y: Int if (a.x > b.y) { height = a.y - b.y y = b.y } else { height = b.y - a.y y = a.y } return Rectangle(x, y, width, height) } } }
agpl-3.0
60f25a494c8ab68f3107357e2208c4b5
27.855263
75
0.458732
4.767391
false
false
false
false
zdary/intellij-community
platform/built-in-server/src/org/jetbrains/ide/ToolboxUpdateActions.kt
1
2913
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.ide import com.intellij.ide.actions.SettingsEntryPointAction import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.* import com.intellij.openapi.util.Disposer import com.intellij.util.Alarm import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import java.util.concurrent.ConcurrentHashMap internal class ToolboxSettingsActionRegistryState: BaseState() { val knownActions by list<String>() } @Service(Service.Level.APP) @State(name = "toolbox-update-state", storages = [Storage(StoragePathMacros.CACHE_FILE)], allowLoadInTests = true) internal class ToolboxSettingsActionRegistry : SimplePersistentStateComponent<ToolboxSettingsActionRegistryState>(ToolboxSettingsActionRegistryState()), Disposable { private val pendingActions : MutableMap<String, AnAction> = ConcurrentHashMap() private val alarm = MergingUpdateQueue("toolbox-updates", 500, true, null, this, null, Alarm.ThreadToUse.POOLED_THREAD).usePassThroughInUnitTestMode() override fun dispose() = Unit fun scheduleUpdate() { alarm.queue(object: Update(this){ override fun run() { //we would not like it to overflow if (state.knownActions.size > 300) { val tail = state.knownActions.toList().takeLast(30).toHashSet() state.knownActions.clear() state.knownActions.addAll(tail) state.intIncrementModificationCount() } val ids = pendingActions.keys.toSortedSet() val iconState = if (!state.knownActions.containsAll(ids)) { state.knownActions.addAll(ids) state.intIncrementModificationCount() SettingsEntryPointAction.IconState.ApplicationUpdate } else { SettingsEntryPointAction.IconState.Current } invokeLater { SettingsEntryPointAction.updateState(iconState) } } }) } fun registerUpdateAction(lifetime: Disposable, persistentActionId: String, action: AnAction) { val dispose = Disposable { pendingActions.remove(persistentActionId, action) scheduleUpdate() } pendingActions[persistentActionId] = action if (!Disposer.tryRegister(lifetime, dispose)) { Disposer.dispose(dispose) return } scheduleUpdate() } fun getActions() : List<AnAction> = pendingActions.entries.sortedBy { it.key }.map { it.value } } class ToolboxSettingsActionRegistryActionProvider : SettingsEntryPointAction.ActionProvider { override fun getUpdateActions(context: DataContext) = service<ToolboxSettingsActionRegistry>().getActions() }
apache-2.0
ec925597f92c27d8888c1b702fe3e713
36.831169
165
0.745623
4.668269
false
false
false
false