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
imageprocessor/cv4j
app/src/main/java/com/cv4j/app/activity/DetectQRActivity.kt
1
1274
package com.cv4j.app.activity import android.os.Bundle import androidx.fragment.app.Fragment import com.cv4j.app.R import com.cv4j.app.adapter.QRAdapter import com.cv4j.app.app.BaseActivity import com.cv4j.app.fragment.QRFragment import kotlinx.android.synthetic.main.activity_detect_qr.* import java.util.* /** * * @FileName: * com.cv4j.app.activity.DetectQRActivity * @author: Tony Shen * @date: 2020-05-05 16:13 * @version: V1.0 <描述当前版本功能> */ class DetectQRActivity : BaseActivity() { var title: String? = null private val mList: MutableList<Fragment> = ArrayList<Fragment>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detect_qr) intent.extras?.let { title = it.getString("Title","") }?:{ title = "" }() toolbar.setOnClickListener { finish() } initData() } private fun initData() { toolbar.title = "< $title" for (i in 0..3) { mList.add(QRFragment.newInstance(i)) } viewpager.adapter = QRAdapter(this.supportFragmentManager, mList) tablayout.setupWithViewPager(viewpager) } }
apache-2.0
89306f47fcb36f40f0c3e56e5a3f890f
23.211538
73
0.63911
3.800604
false
false
false
false
paplorinc/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/PopupActions.kt
1
12465
/* * 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.codeInsight.hints import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.HintInfo.MethodInfo import com.intellij.codeInsight.hints.settings.Diff import com.intellij.codeInsight.hints.settings.ParameterNameHintsConfigurable import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.injected.editor.EditorWindow import com.intellij.lang.Language import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil class ShowSettingsWithAddedPattern : AnAction() { init { templatePresentation.description = CodeInsightBundle.message("inlay.hints.show.settings.description") templatePresentation.text = CodeInsightBundle.message("inlay.hints.show.settings", "_") } override fun update(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) if (info is HintInfo.MethodInfo) { e.presentation.setText(CodeInsightBundle.message("inlay.hints.show.settings", info.getMethodName()), false) } else { e.presentation.isVisible = false } } override fun actionPerformed(e: AnActionEvent) { showParameterHintsDialog(e) { when (it) { is HintInfo.OptionInfo -> null is HintInfo.MethodInfo -> it.toPattern() }} } } class ShowParameterHintsSettings : AnAction() { override fun actionPerformed(e: AnActionEvent) { showParameterHintsDialog(e) {null} } } fun showParameterHintsDialog(e: AnActionEvent, getPattern: (HintInfo) -> String?) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val fileLanguage = file.language InlayParameterHintsExtension.forLanguage(fileLanguage) ?: return val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) ?: return val selectedLanguage = (info as? HintInfo.MethodInfo)?.language ?: fileLanguage val dialog = ParameterNameHintsConfigurable(selectedLanguage, getPattern(info)) dialog.show() } class BlacklistCurrentMethodIntention : IntentionAction, LowPriorityAction { companion object { private val presentableText = CodeInsightBundle.message("inlay.hints.blacklist.method") private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } override fun getText(): String = presentableText override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { val language = file.language val hintsProvider = InlayParameterHintsExtension.forLanguage(language) ?: return false return hintsProvider.isBlackListSupported && hasEditorParameterHintAtOffset(editor, file) && isMethodHintAtOffset(editor, file) } private fun isMethodHintAtOffset(editor: Editor, file: PsiFile): Boolean { val offset = editor.caretModel.offset return getHintInfoFromProvider(offset, file, editor) is MethodInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) as? MethodInfo ?: return val language = info.language ?: file.language ParameterNameHintsSettings.getInstance().addIgnorePattern(language, info.toPattern()) refreshAllOpenEditors() showHint(project, language, info) } private fun showHint(project: Project, language: Language, info: MethodInfo) { val methodName = info.getMethodName() val listener = NotificationListener { notification, event -> when (event.description) { "settings" -> showSettings(language) "undo" -> undo(language, info) } notification.expire() } val notification = Notification("Parameter Name Hints", "Method \"$methodName\" added to blacklist", "<html><a href='settings'>Show Parameter Hints Settings</a> or <a href='undo'>Undo</a></html>", NotificationType.INFORMATION, listener) notification.notify(project) } private fun showSettings(language: Language) { val dialog = ParameterNameHintsConfigurable(language, null) dialog.show() } private fun undo(language: Language, info: MethodInfo) { val settings = ParameterNameHintsSettings.getInstance() val languageForSettings = getLanguageForSettingKey(language) val diff = settings.getBlackListDiff(languageForSettings) val updated = diff.added.toMutableSet().apply { remove(info.toPattern()) } settings.setBlackListDiff(languageForSettings, Diff(updated, diff.removed)) refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } class DisableCustomHintsOption: IntentionAction, LowPriorityAction { companion object { private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } private var lastOptionName = "" override fun getText(): String = getIntentionText() private fun getIntentionText(): String { if (lastOptionName.startsWith("show", ignoreCase = true)) { return "Do not ${lastOptionName.toLowerCase()}" } return CodeInsightBundle.message("inlay.hints.disable.custom.option", lastOptionName) } override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { InlayParameterHintsExtension.forLanguage(file.language) ?: return false if (!hasEditorParameterHintAtOffset(editor, file)) return false val option = getOptionHintAtOffset(editor, file) ?: return false lastOptionName = option.optionName return true } private fun getOptionHintAtOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? { val offset = editor.caretModel.offset return getHintInfoFromProvider(offset, file, editor) as? HintInfo.OptionInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val option = getOptionHintAtOffset(editor, file) ?: return option.disable() refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } class EnableCustomHintsOption: IntentionAction, HighPriorityAction { companion object { private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } private var lastOptionName = "" override fun getText(): String { if (lastOptionName.startsWith("show", ignoreCase = true)) { return lastOptionName.capitalizeFirstLetter() } return CodeInsightBundle.message("inlay.hints.enable.custom.option", lastOptionName) } override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { if (!EditorSettingsExternalizable.getInstance().isShowParameterNameHints) return false if (editor !is EditorImpl) return false InlayParameterHintsExtension.forLanguage(file.language) ?: return false val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return false lastOptionName = option.optionName return true } private fun getDisabledOptionInfoAtCaretOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? { val offset = editor.caretModel.offset val element = file.findElementAt(offset) ?: return null val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val target = PsiTreeUtil.findFirstParent(element, { provider.hasDisabledOptionHintInfo(it) }) ?: return null return provider.getHintInfo(target) as? HintInfo.OptionInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return option.enable() refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false } private fun InlayParameterHintsProvider.hasDisabledOptionHintInfo(element: PsiElement): Boolean { val info = getHintInfo(element) return info is HintInfo.OptionInfo && !info.isOptionEnabled() } class ToggleInlineHintsAction : AnAction() { companion object { private val disableText = CodeInsightBundle.message("inlay.hints.disable.action.text").capitalize() private val enableText = CodeInsightBundle.message("inlay.hints.enable.action.text").capitalize() } override fun update(e: AnActionEvent) { if (!InlayParameterHintsExtension.hasAnyExtensions()) { e.presentation.isEnabledAndVisible = false return } val isHintsShownNow = EditorSettingsExternalizable.getInstance().isShowParameterNameHints e.presentation.text = if (isHintsShownNow) disableText else enableText e.presentation.isEnabledAndVisible = true } override fun actionPerformed(e: AnActionEvent) { val settings = EditorSettingsExternalizable.getInstance() val before = settings.isShowParameterNameHints settings.isShowParameterNameHints = !before refreshAllOpenEditors() } } private fun hasEditorParameterHintAtOffset(editor: Editor, file: PsiFile): Boolean { if (editor is EditorWindow) return false val offset = editor.caretModel.offset val element = file.findElementAt(offset) val startOffset = element?.textRange?.startOffset ?: offset val endOffset = element?.textRange?.endOffset ?: offset return !ParameterHintsPresentationManager.getInstance().getParameterHintsInRange(editor, startOffset, endOffset).isEmpty() } private fun refreshAllOpenEditors() { ParameterHintsPassFactory.forceHintsUpdateOnNextPass(); ProjectManager.getInstance().openProjects.forEach { val psiManager = PsiManager.getInstance(it) val daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(it) val fileEditorManager = FileEditorManager.getInstance(it) fileEditorManager.selectedFiles.forEach { psiManager.findFile(it)?.let { daemonCodeAnalyzer.restart(it) } } } } private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor): HintInfo? { val element = file.findElementAt(offset) ?: return null val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val isHintOwnedByElement: (PsiElement) -> Boolean = { e -> provider.getHintInfo(e) != null && e.isOwnsInlayInEditor(editor) } val method = PsiTreeUtil.findFirstParent(element, isHintOwnedByElement) ?: return null return provider.getHintInfo(method) } fun PsiElement.isOwnsInlayInEditor(editor: Editor): Boolean { if (textRange == null) return false val start = if (textRange.isEmpty) textRange.startOffset else textRange.startOffset + 1 return editor.inlayModel.hasInlineElementsInRange(start, textRange.endOffset) } fun MethodInfo.toPattern(): String = this.fullyQualifiedName + '(' + this.paramNames.joinToString(",") + ')' private fun String.capitalize() = StringUtil.capitalizeWords(this, true) private fun String.capitalizeFirstLetter() = StringUtil.capitalize(this)
apache-2.0
479e80b4286d78e2e1314c56ec413bbd
36.10119
140
0.761091
4.958234
false
false
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/codeInsight/completion/PyModulePackageCompletionContributor.kt
6
2530
// 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.jetbrains.python.codeInsight.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.jetbrains.python.codeInsight.imports.PythonImportUtils import com.jetbrains.python.psi.PyStringLiteralExpression import com.jetbrains.python.psi.resolve.PyQualifiedNameResolveContext import com.jetbrains.python.psi.resolve.QualifiedNameFinder import com.jetbrains.python.psi.resolve.fromFoothold import com.jetbrains.python.psi.resolve.resolveQualifiedName import com.jetbrains.python.psi.stubs.PyModuleNameIndex /** * Add completion variants for modules and packages. * * The completion contributor ensures that completion variants are resolvable with project source root configuration. * The list of completion variants does not include namespace packages (but includes their modules where appropriate). */ class PyModulePackageCompletionContributor : PyExtendedCompletionContributor() { override fun doFillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { val targetFile = parameters.originalFile val inStringLiteral = parameters.position.parent is PyStringLiteralExpression val moduleKeys = PyModuleNameIndex.getAllKeys(targetFile.project) val modulesFromIndex = moduleKeys.asSequence() .filter { result.prefixMatcher.prefixMatches(it) } .flatMap { PyModuleNameIndex.find(it, targetFile.project, true).asSequence() } .toList() val resolveContext = fromFoothold(targetFile) val builders = modulesFromIndex.asSequence() .flatMap { resolve(it, resolveContext) } .filter { PythonImportUtils.isImportable(targetFile, it) } .mapNotNull { createLookupElementBuilder(targetFile, it) } .map { it.withInsertHandler( if (inStringLiteral) stringLiteralInsertHandler else importingInsertHandler) } builders.forEach { result.addElement(it) } } private fun resolve(module: PsiFile, resolveContext: PyQualifiedNameResolveContext): Sequence<PsiFileSystemItem> { val qualifiedName = QualifiedNameFinder.findCanonicalImportPath(module, null) ?: return emptySequence() return resolveQualifiedName(qualifiedName, resolveContext).asSequence() .filterIsInstance<PsiFileSystemItem>() } }
apache-2.0
3e84881919ced5eaa6bfa49f57b38847
47.653846
140
0.799605
4.931774
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/projectActions/RemoveSelectedProjectsAction.kt
1
1848
// 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.openapi.wm.impl.welcomeScreen.projectActions import com.intellij.ide.IdeBundle import com.intellij.ide.RecentProjectsManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ui.Messages import com.intellij.openapi.wm.impl.welcomeScreen.cloneableProjects.CloneableProjectsService import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.* /** * @author Konstantin Bulenkov */ internal class RemoveSelectedProjectsAction : RecentProjectsWelcomeScreenActionBase() { override fun actionPerformed(event: AnActionEvent) { val item = getSelectedItem(event) ?: return removeItem(item) } override fun update(event: AnActionEvent) { event.presentation.isEnabled = getSelectedItem(event) != null } companion object { fun removeItem(item: RecentProjectTreeItem) { val recentProjectsManager = RecentProjectsManager.getInstance() val cloneableProjectsService = CloneableProjectsService.getInstance() val exitCode = Messages.showYesNoDialog( IdeBundle.message("dialog.message.remove.0.from.recent.projects.list", item.displayName()), IdeBundle.message("dialog.title.remove.recent.project"), IdeBundle.message("button.remove"), IdeBundle.message("button.cancel"), Messages.getQuestionIcon() ) if (exitCode == Messages.OK) { when (item) { is ProjectsGroupItem -> recentProjectsManager.removeGroup(item.group) is RecentProjectItem -> recentProjectsManager.removePath(item.projectPath) is CloneableProjectItem -> cloneableProjectsService.removeCloneableProject(item.cloneableProject) is RootItem -> {} } } } } }
apache-2.0
6c1ceb5539f0ce97a1950b8c4d8ec54e
38.340426
120
0.74513
4.738462
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/dialog/ShellWindow.kt
2
2245
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.ui.dialog import io.kvision.panel.SimplePanel import org.apache.causeway.client.kroviz.to.ValueType import org.apache.causeway.client.kroviz.ui.core.FormItem import org.apache.causeway.client.kroviz.ui.core.RoDialog import org.apache.causeway.client.kroviz.ui.core.ViewManager import org.apache.causeway.client.kroviz.utils.DomUtil import org.apache.causeway.client.kroviz.utils.UUID import org.apache.causeway.client.kroviz.utils.js.Xterm class ShellWindow(val host: String) : Controller() { val uuid = UUID() init { val formItems = mutableListOf<FormItem>() formItems.add(FormItem("SSH", ValueType.SHELL, host, callBack = uuid)) dialog = RoDialog( caption = host, items = formItems, controller = this, widthPerc = 70, heightPerc = 70, defaultAction = "Pin" ) } override fun open() { //https://stackoverflow.com/questions/61607823/how-to-create-interactive-ssh-terminal-and-enter-commands-from-the-browser-using/61632083#61632083 super.open() Xterm().open(DomUtil.getById(uuid.toString())!!) Xterm().write("Hello from \\x1B[1;3;31mxterm.js\\x1B[0m $ ") } fun execute() { pin() } private fun pin() { ViewManager.add(host, dialog.formPanel as SimplePanel) dialog.close() } }
apache-2.0
3dc03a2a001d178d52c3dd9ebef13ff8
35.209677
153
0.690869
3.837607
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/processings/processings.kt
1
3639
// 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.j2k.post.processing.processings import com.intellij.openapi.application.runReadAction import com.intellij.openapi.editor.RangeMarker import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.refactoring.suggested.range import org.jetbrains.kotlin.idea.imports.KotlinImportOptimizer import org.jetbrains.kotlin.idea.j2k.post.processing.FileBasedPostProcessing import org.jetbrains.kotlin.idea.j2k.post.processing.GeneralPostProcessing import org.jetbrains.kotlin.idea.j2k.post.processing.runUndoTransparentActionInEdt import org.jetbrains.kotlin.j2k.JKPostProcessingTarget import org.jetbrains.kotlin.j2k.elements import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.asLabel import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.elementsInRange internal class FormatCodeProcessing : FileBasedPostProcessing() { override fun runProcessing(file: KtFile, allFiles: List<KtFile>, rangeMarker: RangeMarker?, converterContext: NewJ2kConverterContext) { val codeStyleManager = CodeStyleManager.getInstance(file.project) runUndoTransparentActionInEdt(inWriteAction = true) { if (rangeMarker != null) { if (rangeMarker.isValid) { codeStyleManager.reformatRange(file, rangeMarker.startOffset, rangeMarker.endOffset) } } else { codeStyleManager.reformat(file) } } } } internal class ClearUnknownLabelsProcessing : GeneralPostProcessing { override fun runProcessing(target: JKPostProcessingTarget, converterContext: NewJ2kConverterContext) { val comments = mutableListOf<PsiComment>() runUndoTransparentActionInEdt(inWriteAction = true) { target.elements().forEach { element -> element.accept(object : PsiElementVisitor() { override fun visitElement(element: PsiElement) { element.acceptChildren(this) } override fun visitComment(comment: PsiComment) { if (comment.text.asLabel() != null) { comments += comment } } }) } comments.forEach { it.delete() } } } } internal class OptimizeImportsProcessing : FileBasedPostProcessing() { override fun runProcessing(file: KtFile, allFiles: List<KtFile>, rangeMarker: RangeMarker?, converterContext: NewJ2kConverterContext) { val elements = runReadAction { when { rangeMarker != null && rangeMarker.isValid -> file.elementsInRange(rangeMarker.range!!) rangeMarker != null && !rangeMarker.isValid -> emptyList() else -> file.children.asList() } } val shouldOptimize = elements.any { element -> element is KtElement && element !is KtImportDirective && element !is KtImportList && element !is KtPackageDirective } if (shouldOptimize) { val importsReplacer = runReadAction { KotlinImportOptimizer().processFile(file) } runUndoTransparentActionInEdt(inWriteAction = true) { importsReplacer.run() } } } }
apache-2.0
8fb9ffeef218fac16f4f376e4e777bda
41.811765
139
0.664193
5.251082
false
false
false
false
JetBrains/intellij-community
plugins/performanceTesting/src/com/jetbrains/performancePlugin/commands/CodeAnalysisCommand.kt
1
4632
package com.jetbrains.performancePlugin.commands import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.ui.playback.PlaybackContext import com.intellij.openapi.ui.playback.commands.AbstractCommand import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import com.jetbrains.performancePlugin.utils.ActionCallbackProfilerStopper import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.toPromise class CodeAnalysisCommand(text: String, line: Int) : AbstractCommand(text, line) { companion object { const val PREFIX = CMD_PREFIX + "codeAnalysis" private val LOG = Logger.getInstance(CodeAnalysisCommand::class.java) } override fun _execute(context: PlaybackContext): Promise<Any?> { val actionCallback = ActionCallbackProfilerStopper() val project = context.project val commandArgs = extractCommandArgument(PREFIX).split(" ", limit = 2) val commandType = commandArgs[0] DumbService.getInstance(project).waitForSmartMode() val busConnection = project.messageBus.connect() busConnection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, object : DaemonCodeAnalyzer.DaemonListener { @Suppress("TestOnlyProblems") override fun daemonFinished() { val myDaemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(project) as DaemonCodeAnalyzerImpl val editor = FileEditorManager.getInstance(project).selectedTextEditor require(editor != null) val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) require(psiFile != null) if (myDaemonCodeAnalyzer.isErrorAnalyzingFinished(psiFile)) { busConnection.disconnect() when (commandType) { "CHECK_ON_RED_CODE" -> { val errorsOnHighlighting = DaemonCodeAnalyzerImpl.getHighlights(editor.document, HighlightSeverity.ERROR, project) if (errorsOnHighlighting.size > 0) { val errorMessages = StringBuilder("Analysis on red code detected some errors: " + errorsOnHighlighting.size) errorsOnHighlighting.forEach { errorMessages.append("\n").append(it.description) } actionCallback.reject(errorMessages.toString()) } else { context.message("Analysis on red code performed successfully", line) actionCallback.setDone() } } "WARNINGS_ANALYSIS" -> { val warningsOnHighlighting = DaemonCodeAnalyzerImpl.getHighlights(editor.document, HighlightSeverity.WARNING, project) if (warningsOnHighlighting.size > 0) { val warnings = StringBuilder("Highlighting detected some warnings: " + warningsOnHighlighting.size) for (warning in warningsOnHighlighting) { warnings.append("\n").append(warning.description) } LOG.info(warnings.toString()) val args = when (commandArgs.size > 1) { true -> commandArgs[1].split(",") false -> listOf() } if (args.isNotEmpty()) { args.forEach { var found = false for (warning in warningsOnHighlighting) { if (warning.description.contains(it)) { found = true break } } if (!found) { actionCallback.reject("Highlighting did not detect the warning $it") } } } if (!actionCallback.isRejected) { actionCallback.setDone() } } else { actionCallback.reject("Highlighting did not detect any warning") } } else -> error("Wrong type of code analysis: $commandType") } } } }) DumbService.getInstance(project).smartInvokeLater { PsiManager.getInstance(project).dropPsiCaches() context.message("Code highlighting started", line) DaemonCodeAnalyzer.getInstance(project).restart() } return actionCallback.toPromise() } }
apache-2.0
01155b46b6de0ed94579560bba594ef5
41.495413
132
0.631908
5.45583
false
false
false
false
StepicOrg/stepik-android
app/src/test/java/org/stepik/android/data/search/SearchRepositoryTest.kt
1
1835
package org.stepik.android.data.search import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.whenever import io.reactivex.Single import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.mock import org.mockito.junit.MockitoJUnitRunner import ru.nobird.app.core.model.PagedList import org.stepik.android.data.search_result.repository.SearchResultRepositoryImpl import org.stepik.android.data.search_result.source.SearchResultRemoteDataSource import org.stepik.android.domain.filter.model.CourseListFilterQuery import org.stepik.android.domain.search_result.model.SearchResultQuery import org.stepik.android.model.SearchResult @RunWith(MockitoJUnitRunner::class) class SearchRepositoryTest { @Mock private lateinit var searchResultRemoteDataSource: SearchResultRemoteDataSource @Test fun searchResultsLoadingTest() { val searchRepository = SearchResultRepositoryImpl(searchResultRemoteDataSource) val page = 1 val rawQuery = "python" val lang = "en" val remoteResult = PagedList(listOf(mock(SearchResult::class.java))) whenever(searchResultRemoteDataSource.getSearchResults( SearchResultQuery( page = page, query = rawQuery, filterQuery = CourseListFilterQuery(language = lang) ) )) doReturn Single.just(remoteResult) searchRepository .getSearchResults( SearchResultQuery( page = page, query = rawQuery, filterQuery = CourseListFilterQuery(language = lang) ) ) .test() .assertNoErrors() .assertComplete() .assertResult(remoteResult) } }
apache-2.0
9e641750bed6daa69bbd21e4613e0212
32.381818
87
0.690463
5.125698
false
true
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/modding/ModdingGame.kt
2
1511
package io.github.chrislo27.rhre3.modding import java.util.* import kotlin.math.roundToInt enum class ModdingGame(val id: String, val gameName: String, val console: String, val tickflowUnits: Int, val tickflowUnitName: String = "", val underdeveloped: Boolean = true) { TENGOKU("gba", "Rhythm Tengoku (リズム天国)", "GBA", 0x18), DS_NA("rhds", "Rhythm Heaven", "NDS", 0x0C), FEVER("rhFever", "Rhythm Heaven Fever", "Wii", 0x30), MEGAMIX_NA("rhMegamix", "Rhythm Heaven Megamix", "3DS", 0x30, underdeveloped = false); // τ companion object { val DEFAULT_GAME = MEGAMIX_NA val VALUES = values().toList() } private val tickflowUnitsStr: String = "0x${tickflowUnits.toString(16).toUpperCase(Locale.ROOT)}" val fullName: String = "$gameName ($console)" fun beatsToTickflow(beats: Float): Int = (beats * tickflowUnits).roundToInt() fun tickflowToBeats(tickflow: Int): Float = tickflow.toFloat() / tickflowUnits fun beatsToTickflowString(beats: Float): String { val tickflow = beatsToTickflow(beats) val wholes = tickflow / tickflowUnits val leftover = tickflow % tickflowUnits return "${if (wholes > 0) if (wholes > 1) "$wholes × $tickflowUnitsStr" else tickflowUnitsStr else ""}${if (wholes > 0 && leftover > 0) " + " else ""}${if (leftover > 0) "0x${leftover.toString(16).toUpperCase(Locale.ROOT)}" else ""} $tickflowUnitName".trim() } }
gpl-3.0
c6e6f9367c37b2d0435aa885ed849a67
44.454545
266
0.643763
3.353468
false
false
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/commands/subcommands/player/setcommands/PlayerSetNameCommand.kt
1
1260
package com.masahirosaito.spigot.homes.commands.subcommands.player.setcommands import com.masahirosaito.spigot.homes.Configs.onNamedHome import com.masahirosaito.spigot.homes.Homes.Companion.homes import com.masahirosaito.spigot.homes.Permission.home_command_set import com.masahirosaito.spigot.homes.Permission.home_command_set_name import com.masahirosaito.spigot.homes.PlayerDataManager import com.masahirosaito.spigot.homes.commands.PlayerSubCommand import com.masahirosaito.spigot.homes.commands.subcommands.player.PlayerCommand import com.masahirosaito.spigot.homes.strings.commands.SetCommandStrings.SET_NAMED_HOME import org.bukkit.entity.Player class PlayerSetNameCommand(playerSetCommand: PlayerSetCommand) : PlayerSubCommand(playerSetCommand), PlayerCommand { override val permissions: List<String> = listOf(home_command_set, home_command_set_name) override fun configs(): List<Boolean> = listOf(onNamedHome) override fun fee(): Double = homes.fee.SET_NAME override fun isValidArgs(args: List<String>): Boolean = args.size == 1 override fun execute(player: Player, args: List<String>) { PlayerDataManager.setNamedHome(player, player.location, args[0]) send(player, SET_NAMED_HOME(args[0])) } }
apache-2.0
5befd5f39a6c8c19a88b6d6d3e650d80
44
92
0.796032
4.064516
false
true
false
false
scenerygraphics/scenery
src/main/kotlin/graphics/scenery/Light.kt
1
2487
package graphics.scenery import graphics.scenery.net.Networkable import graphics.scenery.utils.extensions.plus import graphics.scenery.utils.extensions.times import org.joml.Vector3f import kotlin.math.sqrt import kotlin.reflect.full.createInstance /** * Abstract class for light [Node]s. * * @author Ulrik Guenther <[email protected]> */ abstract class Light(name: String = "Light") : Mesh(name), Networkable { /** Enum class to determine light type. */ enum class LightType { PointLight, DirectionalLight, AmbientLight } /** Emission color of the light. */ @ShaderProperty abstract var emissionColor: Vector3f /** Intensity of the light. */ @ShaderProperty abstract var intensity: Float /** The light's type, stored as [LightType]. */ @ShaderProperty abstract val lightType: LightType override fun update(fresh: Networkable, getNetworkable: (Int) -> Networkable, additionalData: Any?) { super.update(fresh, getNetworkable,additionalData) if (fresh !is Light) throw IllegalArgumentException("Update called with object of foreign class") emissionColor = fresh.emissionColor intensity = fresh.intensity } companion object { /** * Creates a tetrahedron lights of type [T] and returns them as a list. * The [center] of the tetrahedron can be specified, as can be the [spread] of it, the light's [intensity], [color], and [radius]. */ inline fun <reified T: Light> createLightTetrahedron(center: Vector3f = Vector3f(0.0f), spread: Float = 1.0f, intensity: Float = 1.0f, color: Vector3f = Vector3f(1.0f), radius: Float = 5.0f): List<T> { val tetrahedron = listOf( Vector3f(1.0f, 0f, -1.0f/ sqrt(2.0).toFloat()) * spread, Vector3f(-1.0f,0f,-1.0f/ sqrt(2.0).toFloat()) * spread, Vector3f(0.0f,1.0f,1.0f/ sqrt(2.0).toFloat()) * spread, Vector3f(0.0f,-1.0f,1.0f/ sqrt(2.0).toFloat()) * spread) return tetrahedron.map { position -> val light = T::class.createInstance() light.spatial { this.position = position + center } light.emissionColor = color light.intensity = intensity if(light is PointLight) { light.lightRadius = radius } light } } } }
lgpl-3.0
dde71dc876a27e855d1abb64c3e51bdc
35.043478
210
0.609168
4.017771
false
false
false
false
android/wear-os-samples
WatchFaceKotlin/app/src/main/java/com/example/android/wearable/alpha/data/watchface/ColorStyleIdAndResourceIds.kt
1
6970
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.wearable.alpha.data.watchface import android.content.Context import android.graphics.drawable.Icon import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.wear.watchface.style.UserStyleSetting import androidx.wear.watchface.style.UserStyleSetting.ListUserStyleSetting import com.example.android.wearable.alpha.R // Defaults for all styles. // X_COLOR_STYLE_ID - id in watch face database for each style id. // X_COLOR_STYLE_NAME_RESOURCE_ID - String name to display in the user settings UI for the style. // X_COLOR_STYLE_ICON_ID - Icon to display in the user settings UI for the style. const val AMBIENT_COLOR_STYLE_ID = "ambient_style_id" private const val AMBIENT_COLOR_STYLE_NAME_RESOURCE_ID = R.string.ambient_style_name private const val AMBIENT_COLOR_STYLE_ICON_ID = R.drawable.white_style const val RED_COLOR_STYLE_ID = "red_style_id" private const val RED_COLOR_STYLE_NAME_RESOURCE_ID = R.string.red_style_name private const val RED_COLOR_STYLE_ICON_ID = R.drawable.red_style const val GREEN_COLOR_STYLE_ID = "green_style_id" private const val GREEN_COLOR_STYLE_NAME_RESOURCE_ID = R.string.green_style_name private const val GREEN_COLOR_STYLE_ICON_ID = R.drawable.green_style const val BLUE_COLOR_STYLE_ID = "blue_style_id" private const val BLUE_COLOR_STYLE_NAME_RESOURCE_ID = R.string.blue_style_name private const val BLUE_COLOR_STYLE_ICON_ID = R.drawable.blue_style const val WHITE_COLOR_STYLE_ID = "white_style_id" private const val WHITE_COLOR_STYLE_NAME_RESOURCE_ID = R.string.white_style_name private const val WHITE_COLOR_STYLE_ICON_ID = R.drawable.white_style /** * Represents watch face color style options the user can select (includes the unique id, the * complication style resource id, and general watch face color style resource ids). * * The companion object offers helper functions to translate a unique string id to the correct enum * and convert all the resource ids to their correct resources (with the Context passed in). The * renderer will use these resources to render the actual colors and ComplicationDrawables of the * watch face. */ enum class ColorStyleIdAndResourceIds( val id: String, @StringRes val nameResourceId: Int, @DrawableRes val iconResourceId: Int, @DrawableRes val complicationStyleDrawableId: Int, @ColorRes val primaryColorId: Int, @ColorRes val secondaryColorId: Int, @ColorRes val backgroundColorId: Int, @ColorRes val outerElementColorId: Int ) { AMBIENT( id = AMBIENT_COLOR_STYLE_ID, nameResourceId = AMBIENT_COLOR_STYLE_NAME_RESOURCE_ID, iconResourceId = AMBIENT_COLOR_STYLE_ICON_ID, complicationStyleDrawableId = R.drawable.complication_white_style, primaryColorId = R.color.ambient_primary_color, secondaryColorId = R.color.ambient_secondary_color, backgroundColorId = R.color.ambient_background_color, outerElementColorId = R.color.ambient_outer_element_color ), RED( id = RED_COLOR_STYLE_ID, nameResourceId = RED_COLOR_STYLE_NAME_RESOURCE_ID, iconResourceId = RED_COLOR_STYLE_ICON_ID, complicationStyleDrawableId = R.drawable.complication_red_style, primaryColorId = R.color.red_primary_color, secondaryColorId = R.color.red_secondary_color, backgroundColorId = R.color.red_background_color, outerElementColorId = R.color.red_outer_element_color ), GREEN( id = GREEN_COLOR_STYLE_ID, nameResourceId = GREEN_COLOR_STYLE_NAME_RESOURCE_ID, iconResourceId = GREEN_COLOR_STYLE_ICON_ID, complicationStyleDrawableId = R.drawable.complication_green_style, primaryColorId = R.color.green_primary_color, secondaryColorId = R.color.green_secondary_color, backgroundColorId = R.color.green_background_color, outerElementColorId = R.color.green_outer_element_color ), BLUE( id = BLUE_COLOR_STYLE_ID, nameResourceId = BLUE_COLOR_STYLE_NAME_RESOURCE_ID, iconResourceId = BLUE_COLOR_STYLE_ICON_ID, complicationStyleDrawableId = R.drawable.complication_blue_style, primaryColorId = R.color.blue_primary_color, secondaryColorId = R.color.blue_secondary_color, backgroundColorId = R.color.blue_background_color, outerElementColorId = R.color.blue_outer_element_color ), WHITE( id = WHITE_COLOR_STYLE_ID, nameResourceId = WHITE_COLOR_STYLE_NAME_RESOURCE_ID, iconResourceId = WHITE_COLOR_STYLE_ICON_ID, complicationStyleDrawableId = R.drawable.complication_white_style, primaryColorId = R.color.white_primary_color, secondaryColorId = R.color.white_secondary_color, backgroundColorId = R.color.white_background_color, outerElementColorId = R.color.white_outer_element_color ); companion object { /** * Translates the string id to the correct ColorStyleIdAndResourceIds object. */ fun getColorStyleConfig(id: String): ColorStyleIdAndResourceIds { return when (id) { AMBIENT.id -> AMBIENT RED.id -> RED GREEN.id -> GREEN BLUE.id -> BLUE WHITE.id -> WHITE else -> WHITE } } /** * Returns a list of [UserStyleSetting.ListUserStyleSetting.ListOption] for all * ColorStyleIdAndResourceIds enums. The watch face settings APIs use this to set up * options for the user to select a style. */ fun toOptionList(context: Context): List<ListUserStyleSetting.ListOption> { val colorStyleIdAndResourceIdsList = enumValues<ColorStyleIdAndResourceIds>() return colorStyleIdAndResourceIdsList.map { colorStyleIdAndResourceIds -> ListUserStyleSetting.ListOption( UserStyleSetting.Option.Id(colorStyleIdAndResourceIds.id), context.resources, colorStyleIdAndResourceIds.nameResourceId, Icon.createWithResource( context, colorStyleIdAndResourceIds.iconResourceId ) ) } } } }
apache-2.0
247078a1ff32b2380398ee83ccae636c
42.291925
99
0.698996
4.16866
false
false
false
false
ursjoss/sipamato
core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/jobs/paper/SyncShortFieldWithEmptyMainFieldConcatenator.kt
2
5039
package ch.difty.scipamato.core.sync.jobs.paper import ch.difty.scipamato.common.logger import ch.difty.scipamato.common.paper.AbstractShortFieldConcatenator import ch.difty.scipamato.core.db.Tables import ch.difty.scipamato.core.db.tables.Paper import ch.difty.scipamato.core.db.tables.records.PaperRecord import org.jooq.TableField import org.springframework.stereotype.Component import java.sql.ResultSet import java.sql.SQLException private val log = logger() /** * Gathers the content for the fields methods, population and result. * * There are some main fields (result, population and method) that could alternatively * be represented with a number of Short field (Kurzerfassung). If the main field is populated, it will always * have precedence, regardless of whether there's content in the respective short fields. If the main field is null, * all respective short fields with content are concatenated into the respective field in SciPaMaTo-Public. Note * that there's a known deficiency: The labels that are included with the short fields are always in english, they * will not adapt to the browser locale of a viewer. */ @Component internal open class SyncShortFieldWithEmptyMainFieldConcatenator : AbstractShortFieldConcatenator(false), SyncShortFieldConcatenator { override fun methodsFrom(rs: ResultSet): String? = try { methodsFrom(rs, Tables.PAPER.METHODS, Tables.PAPER.METHOD_STUDY_DESIGN, Tables.PAPER.METHOD_OUTCOME, Tables.PAPER.POPULATION_PLACE, Tables.PAPER.EXPOSURE_POLLUTANT, Tables.PAPER.EXPOSURE_ASSESSMENT, Tables.PAPER.METHOD_STATISTICS, Tables.PAPER.METHOD_CONFOUNDERS) } catch (se: SQLException) { log.error(UNABLE_MSG, se) null } @Suppress("LongParameterList", "kotlin:S107") @Throws(SQLException::class) open fun methodsFrom( rs: ResultSet, methodField: TableField<PaperRecord, String?>, methodStudyDesignField: TableField<PaperRecord, String?>, methodOutcomeField: TableField<PaperRecord, String?>, populationPlaceField: TableField<PaperRecord, String?>, exposurePollutantField: TableField<PaperRecord, String?>, exposureAssessmentField: TableField<PaperRecord, String?>, methodStatisticsField: TableField<PaperRecord, String?>, methodConfoundersField: TableField<PaperRecord, String?> ): String = methodsFrom( rs.getString(methodField.name), rs.getString(methodStudyDesignField.name), rs.getString(methodOutcomeField.name), rs.getString(populationPlaceField.name), rs.getString(exposurePollutantField.name), rs.getString(exposureAssessmentField.name), rs.getString(methodStatisticsField.name), rs.getString(methodConfoundersField.name) ) override fun populationFrom(rs: ResultSet): String? = try { populationFrom( rs, Tables.PAPER.POPULATION, Tables.PAPER.POPULATION_PLACE, Tables.PAPER.POPULATION_PARTICIPANTS, Tables.PAPER.POPULATION_DURATION ) } catch (se: SQLException) { log.error(UNABLE_MSG, se) null } // package-private for stubbing purposes @Throws(SQLException::class) open fun populationFrom( rs: ResultSet, populationField: TableField<PaperRecord, String?>, populationPlaceField: TableField<PaperRecord, String?>, populationParticipantsField: TableField<PaperRecord, String?>, populationDurationField: TableField<PaperRecord, String?> ): String = populationFrom( rs.getString(populationField.name), rs.getString(populationPlaceField.name), rs.getString(populationParticipantsField.name), rs.getString(populationDurationField.name) ) override fun resultFrom(rs: ResultSet): String? = try { resultFrom( rs, Paper.PAPER.RESULT, Paper.PAPER.RESULT_MEASURED_OUTCOME, Paper.PAPER.RESULT_EXPOSURE_RANGE, Paper.PAPER.RESULT_EFFECT_ESTIMATE, Paper.PAPER.CONCLUSION ) } catch (se: SQLException) { log.error(UNABLE_MSG, se) null } // package-private for stubbing purposes @Throws(SQLException::class) open fun resultFrom( rs: ResultSet, resultField: TableField<PaperRecord, String?>, resultMeasuredOutcomeField: TableField<PaperRecord, String?>, resultExposureRangeField: TableField<PaperRecord, String?>, resultEffectEstimateField: TableField<PaperRecord, String?>, conclusionField: TableField<PaperRecord, String?> ): String = resultFrom( rs.getString(resultField.name), rs.getString(resultMeasuredOutcomeField.name), rs.getString(resultExposureRangeField.name), rs.getString(resultEffectEstimateField.name), rs.getString(conclusionField.name) ) companion object { private const val UNABLE_MSG = "Unable to evaluate recordset" } }
gpl-3.0
aa85d6984690b62db34307fc9bb42397
40.303279
141
0.707879
4.580909
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/openapi/observable/properties/AtomicLazyProperty.kt
2
1970
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.observable.properties import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicReference open class AtomicLazyProperty<T>(private val initial: () -> T) : AtomicProperty<T> { private val value = AtomicReference<Any?>(UNINITIALIZED_VALUE) private val changeListeners = CopyOnWriteArrayList<(T) -> Unit>() private val resetListeners = CopyOnWriteArrayList<() -> Unit>() override fun get(): T { return update { it } } override fun set(value: T) { this.value.set(value) changeListeners.forEach { it(value) } } override fun updateAndGet(update: (T) -> T): T { val newValue = update(update) changeListeners.forEach { it(newValue) } return newValue } @Suppress("UNCHECKED_CAST") private fun update(update: (T) -> T): T { val resolve = { it: Any? -> if (it === UNINITIALIZED_VALUE) initial() else it as T } return value.updateAndGet { update(resolve(it)) } as T } override fun reset() { value.set(UNINITIALIZED_VALUE) resetListeners.forEach { it() } } override fun afterChange(listener: (T) -> Unit) { changeListeners.add(listener) } override fun afterReset(listener: () -> Unit) { resetListeners.add(listener) } override fun afterChange(listener: (T) -> Unit, parentDisposable: Disposable) { changeListeners.add(listener) Disposer.register(parentDisposable, Disposable { changeListeners.remove(listener) }) } override fun afterReset(listener: () -> Unit, parentDisposable: Disposable) { resetListeners.add(listener) Disposer.register(parentDisposable, Disposable { resetListeners.remove(listener) }) } companion object { private val UNINITIALIZED_VALUE = Any() } }
apache-2.0
efbf27c4ac9e5eb6c1dcd47971f3b16c
30.285714
140
0.71066
4.18259
false
false
false
false
leafclick/intellij-community
platform/platform-tests/testSrc/com/intellij/internal/statistics/whitelist/validator/SensitiveDataValidatorTest.kt
1
25452
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistics.whitelist.validator import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.validator.SensitiveDataValidator import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.persistence.EventLogWhitelistPersistence import com.intellij.internal.statistic.eventLog.validator.rules.EventContext import com.intellij.internal.statistic.eventLog.validator.rules.FUSRule import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomWhiteListRule import com.intellij.internal.statistic.eventLog.validator.rules.impl.LocalEnumCustomWhitelistRule import com.intellij.internal.statistic.eventLog.validator.rules.impl.RegexpWhiteListRule import com.intellij.internal.statistic.eventLog.validator.rules.utils.WhiteListSimpleRuleFactory.parseSimpleExpression import com.intellij.internal.statistic.eventLog.whitelist.WhitelistStorage import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.UsefulTestCase import com.intellij.testFramework.fixtures.CodeInsightTestFixture import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory import junit.framework.TestCase import org.junit.Assert import org.junit.Test import java.io.File import java.util.* import java.util.regex.Pattern import kotlin.test.assertTrue @Suppress("SameParameterValue") class SensitiveDataValidatorTest : UsefulTestCase() { private var myFixture: CodeInsightTestFixture? = null override fun setUp() { super.setUp() val factory = IdeaTestFixtureFactory.getFixtureFactory() val fixtureBuilder = factory.createFixtureBuilder("SensitiveDataValidatorTest") myFixture = IdeaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(fixtureBuilder.fixture) myFixture?.setUp() } override fun tearDown() { super.tearDown() try { myFixture?.tearDown() } catch (e: Throwable) { addSuppressedException(e) } finally { myFixture = null } } @Test fun test_refexg_escapes() { val foo = "[aa] \\ \\p{Lower} (a|b|c) [a-zA-Z_0-9] X?+ X*+ X?? [\\p{L}&&[^\\p{Lu}]] " val pattern = Pattern.compile(RegexpWhiteListRule.escapeText(foo)) assertTrue(pattern.matcher(foo).matches()) assert(true) } @Test fun test_parse_simple_expression() { assertOrderedEquals(parseSimpleExpression("aa"), "aa") assertOrderedEquals(parseSimpleExpression("aa{bb}cc"), "aa", "{bb}", "cc") assertOrderedEquals(parseSimpleExpression("{bb}{cc}"), "{bb}", "{cc}") assertOrderedEquals(parseSimpleExpression("a{bb}v{cc}d"), "a", "{bb}", "v", "{cc}", "d") assertOrderedEquals(parseSimpleExpression("ccc}ddd"), "ccc}ddd") // incorrect assertSize(0, parseSimpleExpression("")) assertSize(0, parseSimpleExpression("{aaaa")) assertSize(0, parseSimpleExpression("{bb}{cc")) assertSize(0, parseSimpleExpression("{bb{vv}vv}")) assertSize(0, parseSimpleExpression("{{v}")) } @Test fun test_empty_rule() { val validator = createTestSensitiveDataValidator(loadContent("test_empty_rule.json")) val eventLogGroup = EventLogGroup("build.gradle.actions", 1) assertEmpty(validator.getEventRules(eventLogGroup)) assertTrue(validator.getEventDataRules(eventLogGroup).isEmpty()) assertUndefinedRule(validator, eventLogGroup, "<any-string-accepted>") assertEventDataUndefinedRule(validator, eventLogGroup, "<any-key-accepted>", "<any-string-accepted>") } @Test fun test_simple_enum_rules() { val validator = createTestSensitiveDataValidator(loadContent("test_simple_enum_rules.json")) var elg = EventLogGroup("my.simple.enum.value", 1) assertEventAccepted(validator, elg, "AAA") assertEventAccepted(validator, elg, "BBB") assertEventAccepted(validator, elg, "CCC") assertEventRejected(validator, elg, "ABC") elg = EventLogGroup("my.simple.enum.node.value", 1) assertEventAccepted(validator, elg, "NODE_AAA") assertEventAccepted(validator, elg, "NODE_BBB") assertEventAccepted(validator, elg, "NODE_CCC") assertEventRejected(validator, elg, "NODE_ABC") elg = EventLogGroup("my.simple.enum.ref", 1) assertEventAccepted(validator, elg, "REF_AAA") assertEventAccepted(validator, elg, "REF_BBB") assertEventAccepted(validator, elg, "REF_CCC") assertEventRejected(validator, elg, "REF_ABC") elg = EventLogGroup("my.simple.enum.node.ref", 1) assertEventAccepted(validator, elg, "NODE_REF_AAA") assertEventAccepted(validator, elg, "NODE_REF_BBB") assertEventAccepted(validator, elg, "NODE_REF_CCC") assertEventRejected(validator, elg, "NODE_REF_ABC") } @Test fun test_simple_enum_rules_with_spaces() { val validator = createTestSensitiveDataValidator(loadContent("test_simple_enum_rules.json")) val elg = EventLogGroup("my.simple.enum.node.ref", 1) assertEventAccepted(validator, elg, "NODE REF AAA") assertEventAccepted(validator, elg, "NOD'E;REF:BBB") assertEventAccepted(validator, elg, "NO\"DE REF CCC") assertEventRejected(validator, elg, "NODEREFCCC") } @Test fun test_simple_regexp_rules() { // custom regexp is: (.+)\s*:\s*(.*) => matches 'aaa/java.lang.String' val validator = createTestSensitiveDataValidator(loadContent("test_simple_regexp_rules.json")) var elg = EventLogGroup("my.simple.regexp.value", 1) assertEventAccepted(validator, elg, "aaa/java.lang.String") assertEventRejected(validator, elg, "java.lang.String") elg = EventLogGroup("my.simple.regexp.node.value", 1) assertEventAccepted(validator, elg, "aaa/java.lang.String") assertEventRejected(validator, elg, "java.lang.String") elg = EventLogGroup("my.simple.regexp.ref", 1) assertEventAccepted(validator, elg, "aaa/java.lang.String") assertEventRejected(validator, elg, "java.lang.String") elg = EventLogGroup("my.simple.regexp.node.ref", 1) assertEventAccepted(validator, elg, "aaa/java.lang.String") assertEventRejected(validator, elg, "java.lang.String") } @Test fun test_simple_regexp_rules_with_spaces() { // custom regexp is: [AB]_(.*) => matches 'A_x', 'A x' val validator = createTestSensitiveDataValidator(loadContent("test_simple_regexp_rules.json")) val elg = EventLogGroup("my.simple.regexp.with.underscore", 1) assertEventAccepted(validator, elg, "A_x") assertEventAccepted(validator, elg, "A x") assertEventAccepted(validator, elg, "B:x") assertEventAccepted(validator, elg, "B x") assertEventRejected(validator, elg, "Bxx") } @Test fun test_simple_expression_rules() { // custom expression is: "JUST_TEXT[_{regexp:\\d+(\\+)?}_]_xxx_{enum:AAA|BBB|CCC}_zzz{enum#myEnum}_yyy" val validator = createTestSensitiveDataValidator(loadContent("test_simple_expression_rules.json")) var elg = EventLogGroup("my.simple.expression", 1) assertSize(1, validator.getEventRules(elg)) assertEventAccepted(validator, elg, "JUST_TEXT[_123456_]_xxx_CCC_zzzREF_AAA_yyy") assertEventRejected(validator, elg, "JUST_TEXT[_FOO_]_xxx_CCC_zzzREF_AAA_yyy") assertEventRejected(validator, elg, "") // {enum:AAA|}foo elg = EventLogGroup("my.simple.enum.node.with.empty.value", 1) assertEventAccepted(validator, elg, "AAAfoo") assertEventAccepted(validator, elg, "foo") assertEventRejected(validator, elg, " foo") assertEventRejected(validator, elg, " AAA foo") } @Test fun test_simple_expression_rules_with_spaces() { // custom expression is: "JUST_TEXT[_{regexp:\\d+(\\+)?}_]_xxx_{enum:AAA|BBB|CCC}_zzz{enum#myEnum}_yyy" val validator = createTestSensitiveDataValidator(loadContent("test_simple_expression_rules.json")) val elg = EventLogGroup("my.simple.expression", 1) assertEventAccepted(validator, elg, "JUST_TEXT[_123456_]_xxx_CCC_zzzREF_AAA_yyy") assertEventAccepted(validator, elg, "JUST TEXT[_123456_]_xxx CCC,zzzREF:AAA;yyy") assertEventRejected(validator, elg, "JUSTTEXT[_123456_]_xxx!CCC_zzzREF:AAA;yyy") } // @Test // fun test_simple_util_rules() { // val validator = createTestSensitiveDataValidator(loadContent("test_simple_util_rules.json")) // val elg = EventLogGroup("diagram.usages.trigger", 1) // // assertSize(1, validator.getEventRules(elg)) // // assertEventAccepted(validator, elg, "show.diagram->JAVA") // assertEventAccepted(validator, elg, "show.diagram->MAVEN") // assertEventAccepted(validator, elg, "show.diagram->third.party") // assertEventRejected(validator, elg, "show.diagram->foo") // } @Test fun test_regexp_rule_with_global_regexps() { val validator = createTestSensitiveDataValidator(loadContent("test_regexp_rule-with-global-regexp.json")) val elg = EventLogGroup("ui.fonts", 1) assertSize(10, validator.getEventRules(elg)) assertTrue(validator.getEventDataRules(elg).isEmpty()) assertEventAccepted(validator, elg, "Presentation.mode.font.size[24]") assertEventAccepted(validator, elg, "IDE.editor.font.name[Monospaced]") assertEventAccepted(validator, elg, "IDE.editor.font.name[DejaVu_Sans_Mono]") assertEventAccepted(validator, elg, "Console.font.size[10]") assertEventRejected(validator, elg, "foo") } @Test fun test_validate_system_event_data() { val validator = createTestSensitiveDataValidator(loadContent("test_validate_event_data.json")) val elg = EventLogGroup("system.keys.group", 1) val platformDataKeys: MutableList<String> = Arrays.asList("plugin", "project", "os", "plugin_type", "lang", "current_file", "input_event", "place") for (platformDataKey in platformDataKeys) { assertEventDataAccepted(validator, elg, platformDataKey, "<validated>") } assertEventDataAccepted(validator, elg, "ed_1", "AA") assertEventDataAccepted(validator, elg, "ed_2", "REF_BB") assertEventDataRejected(validator, elg, "ed_1", "CC") assertEventDataRejected(validator, elg, "ed_2", "REF_XX") assertEventDataRuleUndefined(validator, elg, "undefined", "<unknown>") } @Test fun test_validate_escaped_event_data() { val validator = createTestSensitiveDataValidator(loadContent("test_validate_event_data.json")) val elg = EventLogGroup("system.keys.group", 1) assertEventDataAccepted(validator, elg, "ed.1", "AA") assertEventDataAccepted(validator, elg, "ed 2", "REF_BB") assertEventDataAccepted(validator, elg, "ed_1", "AA") assertEventDataAccepted(validator, elg, "ed_2", "REF_BB") assertEventDataUndefinedRule(validator, elg, "ed+2", "REF_BB") } @Test fun test_validate_custom_rule_with_local_enum() { val rule = TestLocalEnumCustomWhitelistRule() Assert.assertEquals(ValidationResultType.ACCEPTED, rule.validate("FIRST", EventContext.create("FIRST", emptyMap()))) Assert.assertEquals(ValidationResultType.ACCEPTED, rule.validate("SECOND", EventContext.create("FIRST", emptyMap()))) Assert.assertEquals(ValidationResultType.ACCEPTED, rule.validate("THIRD", EventContext.create("FIRST", emptyMap()))) Assert.assertEquals(ValidationResultType.REJECTED, rule.validate("FORTH", EventContext.create("FIRST", emptyMap()))) Assert.assertEquals(ValidationResultType.REJECTED, rule.validate("", EventContext.create("FIRST", emptyMap()))) Assert.assertEquals(ValidationResultType.REJECTED, rule.validate("UNKNOWN", EventContext.create("FIRST", emptyMap()))) } fun test_validate_event_id_with_enum_and_existing_rule() { doTestWithRuleList("test_rules_list_event_id.json") { validator -> val elg = EventLogGroup("enum.and.existing.util.rule", 1) assertSize(2, validator.getEventRules(elg)) assertEventAccepted(validator, elg, "AAA") assertEventAccepted(validator, elg, "BBB") assertEventAccepted(validator, elg, "CCC") assertEventRejected(validator, elg, "DDD") assertEventAccepted(validator, elg, "FIRST") } } fun test_validate_event_id_with_enum_and_not_existing_rule() { doTestWithRuleList("test_rules_list_event_id.json") { validator -> val elg = EventLogGroup("enum.and.not.existing.util.rule", 1) assertSize(2, validator.getEventRules(elg)) assertEventAccepted(validator, elg, "AAA") assertEventAccepted(validator, elg, "BBB") assertEventAccepted(validator, elg, "CCC") assertIncorrectRule(validator, elg, "DDD") assertIncorrectRule(validator, elg, "FIRST") } } fun test_validate_event_id_with_enum_and_third_party_rule() { doTestWithRuleList("test_rules_list_event_id.json") { validator -> val elg = EventLogGroup("enum.and.third.party.util.rule", 1) assertSize(2, validator.getEventRules(elg)) assertEventAccepted(validator, elg, "AAA") assertEventAccepted(validator, elg, "BBB") assertEventAccepted(validator, elg, "CCC") assertThirdPartyRule(validator, elg, "DDD") assertEventAccepted(validator, elg, "FIRST") assertThirdPartyRule(validator, elg, "SECOND") } } fun test_validate_event_id_with_existing_rule_and_enum() { doTestWithRuleList("test_rules_list_event_id.json") { validator -> val elg = EventLogGroup("existing.util.rule.and.enum", 1) assertSize(2, validator.getEventRules(elg)) assertEventAccepted(validator, elg, "AAA") assertEventAccepted(validator, elg, "BBB") assertEventAccepted(validator, elg, "CCC") assertEventRejected(validator, elg, "DDD") assertEventAccepted(validator, elg, "FIRST") } } fun test_validate_event_id_with_not_existing_rule_and_enum() { doTestWithRuleList("test_rules_list_event_id.json") { validator -> val elg = EventLogGroup("not.existing.util.rule.and.enum", 1) assertSize(2, validator.getEventRules(elg)) assertEventAccepted(validator, elg, "AAA") assertEventAccepted(validator, elg, "BBB") assertEventAccepted(validator, elg, "CCC") assertEventRejected(validator, elg, "DDD") assertEventRejected(validator, elg, "FIRST") } } fun test_validate_event_id_with_third_party_rule_and_enum() { doTestWithRuleList("test_rules_list_event_id.json") { validator -> val elg = EventLogGroup("third.party.util.rule.and.enum", 1) assertSize(2, validator.getEventRules(elg)) assertEventAccepted(validator, elg, "AAA") assertEventAccepted(validator, elg, "BBB") assertEventAccepted(validator, elg, "CCC") assertEventRejected(validator, elg, "DDD") assertEventAccepted(validator, elg, "FIRST") assertEventRejected(validator, elg, "SECOND") } } fun test_validate_event_data_with_enum_and_existing_rule() { doTestWithRuleList("test_rules_list_event_data.json") { validator -> val elg = EventLogGroup("enum.and.existing.util.rule", 1) val dataRules = validator.getEventDataRules(elg) assertSize(2, dataRules["data_1"] ?: error("Cannot find rules for 'data_1' field")) assertEventDataAccepted(validator, elg, "data_1", "AAA") assertEventDataAccepted(validator, elg, "data_1", "BBB") assertEventDataAccepted(validator, elg, "data_1", "CCC") assertEventDataRejected(validator, elg, "data_1", "DDD") assertEventDataAccepted(validator, elg, "data_1", "FIRST") } } fun test_validate_event_data_with_enum_and_not_existing_rule() { doTestWithRuleList("test_rules_list_event_data.json") { validator -> val elg = EventLogGroup("enum.and.not.existing.util.rule", 1) val dataRules = validator.getEventDataRules(elg) assertSize(2, dataRules["data_1"] ?: error("Cannot find rules for 'data_1' field")) assertEventDataAccepted(validator, elg, "data_1", "AAA") assertEventDataAccepted(validator, elg, "data_1", "BBB") assertEventDataAccepted(validator, elg, "data_1", "CCC") assertEventDataIncorrectRule(validator, elg, "data_1", "DDD") assertEventDataIncorrectRule(validator, elg, "data_1", "FIRST") } } fun test_validate_event_data_with_enum_and_third_party_rule() { doTestWithRuleList("test_rules_list_event_data.json") { validator -> val elg = EventLogGroup("enum.and.third.party.util.rule", 1) val dataRules = validator.getEventDataRules(elg) assertSize(2, dataRules["data_1"] ?: error("Cannot find rules for 'data_1' field")) assertEventDataAccepted(validator, elg, "data_1", "AAA") assertEventDataAccepted(validator, elg, "data_1", "BBB") assertEventDataAccepted(validator, elg, "data_1", "CCC") assertEventDataThirdParty(validator, elg, "data_1", "DDD") assertEventDataAccepted(validator, elg, "data_1", "FIRST") assertEventDataThirdParty(validator, elg, "data_1", "SECOND") } } fun test_validate_event_data_with_existing_rule_and_enum() { doTestWithRuleList("test_rules_list_event_data.json") { validator -> val elg = EventLogGroup("existing.util.rule.and.enum", 1) val dataRules = validator.getEventDataRules(elg) assertSize(2, dataRules["data_1"] ?: error("Cannot find rules for 'data_1' field")) assertEventDataAccepted(validator, elg, "data_1", "AAA") assertEventDataAccepted(validator, elg, "data_1", "BBB") assertEventDataAccepted(validator, elg, "data_1", "CCC") assertEventDataRejected(validator, elg, "data_1", "DDD") assertEventDataAccepted(validator, elg, "data_1", "FIRST") } } fun test_validate_event_data_with_not_existing_rule_and_enum() { doTestWithRuleList("test_rules_list_event_data.json") { validator -> val elg = EventLogGroup("not.existing.util.rule.and.enum", 1) val dataRules = validator.getEventDataRules(elg) assertSize(2, dataRules["data_1"] ?: error("Cannot find rules for 'data_1' field")) assertEventDataAccepted(validator, elg, "data_1", "AAA") assertEventDataAccepted(validator, elg, "data_1", "BBB") assertEventDataAccepted(validator, elg, "data_1", "CCC") assertEventDataRejected(validator, elg, "data_1", "DDD") assertEventDataRejected(validator, elg, "data_1", "FIRST") } } fun test_validate_event_data_with_third_party_rule_and_enum() { doTestWithRuleList("test_rules_list_event_data.json") { validator -> val elg = EventLogGroup("third.party.util.rule.and.enum", 1) val dataRules = validator.getEventDataRules(elg) assertSize(2, dataRules["data_1"] ?: error("Cannot find rules for 'data_1' field")) assertEventDataAccepted(validator, elg, "data_1", "AAA") assertEventDataAccepted(validator, elg, "data_1", "BBB") assertEventDataAccepted(validator, elg, "data_1", "CCC") assertEventDataRejected(validator, elg, "data_1", "DDD") assertEventDataAccepted(validator, elg, "data_1", "FIRST") assertEventDataRejected(validator, elg, "data_1", "SECOND") } } private fun doTestWithRuleList(fileName: String, func: (TestSensitiveDataValidator) -> Unit) { val disposable = Disposer.newDisposable() try { val ep = Extensions.getRootArea().getExtensionPoint(CustomWhiteListRule.EP_NAME) ep.registerExtension(TestExistingWhitelistRule(), disposable) ep.registerExtension(TestThirdPartyWhitelistRule(), disposable) val validator = createTestSensitiveDataValidator(loadContent(fileName)) func(validator) } finally { Disposer.dispose(disposable) } } private fun assertEventAccepted(validator: SensitiveDataValidator, eventLogGroup: EventLogGroup, s: String) { TestCase.assertEquals(ValidationResultType.ACCEPTED, validator.validateEvent(eventLogGroup, EventContext.create(s, Collections.emptyMap()))) } private fun assertUndefinedRule(validator: SensitiveDataValidator, eventLogGroup: EventLogGroup, s: String) { TestCase.assertEquals(ValidationResultType.UNDEFINED_RULE, validator.validateEvent(eventLogGroup, EventContext.create(s, Collections.emptyMap()))) } private fun assertIncorrectRule(validator: SensitiveDataValidator, eventLogGroup: EventLogGroup, s: String) { TestCase.assertEquals(ValidationResultType.INCORRECT_RULE, validator.validateEvent(eventLogGroup, EventContext.create(s, Collections.emptyMap()))) } private fun assertThirdPartyRule(validator: SensitiveDataValidator, eventLogGroup: EventLogGroup, s: String) { TestCase.assertEquals(ValidationResultType.THIRD_PARTY, validator.validateEvent(eventLogGroup, EventContext.create(s, Collections.emptyMap()))) } private fun assertEventRejected(validator: SensitiveDataValidator, eventLogGroup: EventLogGroup, s: String) { TestCase.assertEquals(ValidationResultType.REJECTED, validator.validateEvent(eventLogGroup, EventContext.create(s, Collections.emptyMap()))) } private fun assertEventDataAccepted(validator: TestSensitiveDataValidator, eventLogGroup: EventLogGroup, key: String, dataValue: String) { val data = FeatureUsageData().addData(key, dataValue) val (preparedKey, preparedValue) = data.build().entries.iterator().next() TestCase.assertEquals(ValidationResultType.ACCEPTED, validator.validateEventData(eventLogGroup, preparedKey, preparedValue)) } private fun assertEventDataUndefinedRule(validator: TestSensitiveDataValidator, eventLogGroup: EventLogGroup, key: String, dataValue: String) { TestCase.assertEquals(ValidationResultType.UNDEFINED_RULE, validator.validateEventData(eventLogGroup, key, dataValue)) } private fun assertEventDataIncorrectRule(validator: TestSensitiveDataValidator, eventLogGroup: EventLogGroup, key: String, dataValue: String) { TestCase.assertEquals(ValidationResultType.INCORRECT_RULE, validator.validateEventData(eventLogGroup, key, dataValue)) } private fun assertEventDataThirdParty(validator: TestSensitiveDataValidator, eventLogGroup: EventLogGroup, key: String, dataValue: String) { TestCase.assertEquals(ValidationResultType.THIRD_PARTY, validator.validateEventData(eventLogGroup, key, dataValue)) } private fun assertEventDataRejected(validator: TestSensitiveDataValidator, eventLogGroup: EventLogGroup, key: String, dataValue: String) { TestCase.assertEquals(ValidationResultType.REJECTED, validator.validateEventData(eventLogGroup, key, dataValue)) } private fun assertEventDataRuleUndefined(validator: TestSensitiveDataValidator, eventLogGroup: EventLogGroup, key: String, dataValue: String) { TestCase.assertEquals(ValidationResultType.UNDEFINED_RULE, validator.validateEventData(eventLogGroup, key, dataValue)) } private fun createTestSensitiveDataValidator(content: String): TestSensitiveDataValidator { return TestSensitiveDataValidator(content) } private fun loadContent(fileName: String): String { val file = File(PlatformTestUtil.getPlatformTestDataPath() + "fus/validation/" + fileName) assertTrue { file.exists() } return FileUtil.loadFile(file) } internal inner class TestSensitiveDataValidator constructor(myContent: String) : SensitiveDataValidator(TestWhitelistStorage(myContent)) { fun getEventRules(group: EventLogGroup): Array<FUSRule> { val whiteListRule = myWhiteListStorage.getGroupRules(group.id) return if (whiteListRule == null) FUSRule.EMPTY_ARRAY else whiteListRule.eventIdRules } fun getEventDataRules(group: EventLogGroup): Map<String, Array<FUSRule>> { val whiteListRule = myWhiteListStorage.getGroupRules(group.id) return if (whiteListRule == null) emptyMap() else whiteListRule.eventDataRules } fun validateEventData(group: EventLogGroup, key: String, value: Any): ValidationResultType { if (FeatureUsageData.platformDataKeys.contains(key)) return ValidationResultType.ACCEPTED val whiteListRule = myWhiteListStorage.getGroupRules(group.id) return if (whiteListRule == null || !whiteListRule.areEventDataRulesDefined()) ValidationResultType.UNDEFINED_RULE else whiteListRule.validateEventData(key, value, EventContext.create("", Collections.emptyMap())) // there are no configured rules } } class TestWhitelistStorage(myContent: String) : WhitelistStorage("TEST", TestEventLogWhitelistPersistence(myContent)) class TestEventLogWhitelistPersistence(private val myContent: String) : EventLogWhitelistPersistence("TEST") { override fun getCachedWhitelist(): String? { return myContent } } internal enum class TestCustomActionId {FIRST, SECOND, THIRD} internal inner class TestLocalEnumCustomWhitelistRule : LocalEnumCustomWhitelistRule("custom_action_id", TestCustomActionId::class.java) internal inner class TestExistingWhitelistRule : LocalEnumCustomWhitelistRule("existing_rule", TestCustomActionId::class.java) internal inner class TestThirdPartyWhitelistRule : CustomWhiteListRule() { override fun acceptRuleId(ruleId: String?): Boolean = "third_party_rule" == ruleId override fun doValidate(data: String, context: EventContext): ValidationResultType { return if (data == "FIRST") ValidationResultType.ACCEPTED else ValidationResultType.THIRD_PARTY } } }
apache-2.0
212dfba798e4484b22b3ec0fe2b34844
43.112652
150
0.731495
3.959552
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/callBy/manyArgumentsOnlyOneDefault.kt
2
2257
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.test.assertEquals // Generate: // (1..70).map { " p${"%02d".format(it)}: Int," }.joinToString("\n") class A { fun foo( p01: Int, p02: Int, p03: Int, p04: Int, p05: Int, p06: Int, p07: Int, p08: Int, p09: Int, p10: Int, p11: Int, p12: Int, p13: Int, p14: Int, p15: Int, p16: Int, p17: Int, p18: Int, p19: Int, p20: Int, p21: Int, p22: Int, p23: Int, p24: Int, p25: Int, p26: Int, p27: Int, p28: Int, p29: Int, p30: Int, p31: Int, p32: Int, p33: Int, p34: Int, p35: Int, p36: Int, p37: Int, p38: Int, p39: Int, p40: Int, p41: Int, p42: Int = 239, p43: Int, p44: Int, p45: Int, p46: Int, p47: Int, p48: Int, p49: Int, p50: Int, p51: Int, p52: Int, p53: Int, p54: Int, p55: Int, p56: Int, p57: Int, p58: Int, p59: Int, p60: Int, p61: Int, p62: Int, p63: Int, p64: Int, p65: Int, p66: Int, p67: Int, p68: Int, p69: Int, p70: Int ) { assertEquals(1, p01) assertEquals(41, p41) assertEquals(239, p42) assertEquals(43, p43) assertEquals(70, p70) } } fun box(): String { val f = A::class.members.single { it.name == "foo" } val parameters = f.parameters f.callBy(mapOf( parameters.first() to A(), *((1..41) + (43..70)).map { i -> parameters[i] to i }.toTypedArray() )) return "OK" }
apache-2.0
c8ce4c88e02578627028cc332b216ecd
21.127451
80
0.363757
3.565561
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/controlStructures/kt3087.kt
5
377
fun putNumberCompareAsUnit() { if (1 == 1) { } else if (1 == 1) { } } fun putNumberCompareAsVoid() { if (1 == 1) { 1 == 1 } else { } } fun putInvertAsUnit(b: Boolean) { if (1 == 1) { } else if (!b) { } } fun box(): String { putNumberCompareAsUnit() putNumberCompareAsVoid() putInvertAsUnit(true) return "OK" }
apache-2.0
9082a2db1d7dfd224be6343ee310489b
13.5
33
0.509284
2.877863
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/OnnxConverter.kt
1
4666
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx import lombok.SneakyThrows import onnx.Onnx import org.apache.commons.io.IOUtils import org.bytedeco.javacpp.BytePointer import org.bytedeco.onnx.DefaultVersionConverter import org.bytedeco.onnx.ModelProto import org.bytedeco.onnx.OpSetID import java.io.BufferedInputStream import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.nio.ByteBuffer class OnnxConverter { @SneakyThrows fun convertModel(inputModel: File,outputModelFilePath: File) { val converter = DefaultVersionConverter() var bytes = ByteBuffer.wrap(IOUtils.toByteArray(BufferedInputStream(FileInputStream(inputModel)))) val bytePointer = BytePointer(bytes) val proto = ModelProto() proto.ParseFromString(bytePointer) //done: read in the pointer bytePointer.releaseReference() //clean up on heap reference for the pointer bytes = null System.gc() Thread.sleep(5000) val initialId = OpSetID(0) for(i in 0 until proto.opset_import_size()) { val opSetImport = proto.opset_import(i) if(!opSetImport.has_domain() || opSetImport.domain().string == "ai.onnx") { //approximates default opset from https://github.com/onnx/onnx/blob/master/onnx/version_converter/convert.cc#L14 initialId.setVersion(opSetImport.version()) break } } val convertVersion = converter.convert_version(proto, initialId, OpSetID(13)) proto.releaseReference() val save = convertVersion.SerializeAsString() IOUtils.write(save.stringBytes, FileOutputStream(outputModelFilePath)) } fun addConstValueInfoToGraph(graph: Onnx.GraphProto): Onnx.GraphProto { val inputs = graph.inputList.map { input -> input.name } val existingInfoNames = graph.valueInfoList.map { input -> input.name to input}.toMap() val graphBuilder = graph.toBuilder() for(init in graphBuilder.initializerList) { if(inputs.contains(init.name)) { continue } val elemType = init.dataType val shape = init.dimsList val vi = if(existingInfoNames.containsKey(init.name)) { existingInfoNames[init.name]!! } else { val newAdd = graphBuilder.addValueInfoBuilder() newAdd.name = init.name newAdd.build() } if(!inputs.contains(init.name)) { graphBuilder.addInput(vi) } val ttElem = vi.type.tensorType val ttDType = vi.type.tensorType.elemType if(ttDType == Onnx.TensorProto.DataType.UNDEFINED.ordinal) { ttElem.toBuilder().elemType = ttElem.elemType } if(!ttElem.hasShape()) { for(dim in shape) { ttElem.toBuilder().shape.toBuilder().addDimBuilder().dimValue = dim } } } for(node in graphBuilder.nodeList) { for(attr in node.attributeList) { if(attr.name != "") { if(attr.type == Onnx.AttributeProto.AttributeType.GRAPH) { attr.toBuilder().g = addConstValueInfoToGraph(attr.g) } if(attr.type == Onnx.AttributeProto.AttributeType.GRAPHS) { for(i in 0 until attr.graphsCount) { attr.toBuilder().setGraphs(i,addConstValueInfoToGraph(attr.getGraphs(i))) } } } } } return graphBuilder.build() } }
apache-2.0
a4428589990bd329253df10d0abcd76e
35.178295
128
0.593228
4.465072
false
false
false
false
AndroidX/androidx
navigation/navigation-fragment/src/androidTest/java/androidx/navigation/fragment/FragmentNavigatorTest.kt
3
32009
/* * Copyright 2018 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.navigation.fragment import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentFactory import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.navigation.NavBackStackEntry import androidx.navigation.NavOptions import androidx.navigation.fragment.test.EmptyFragment import androidx.navigation.fragment.test.R import androidx.navigation.testing.TestNavigatorState import androidx.test.annotation.UiThreadTest import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import kotlin.reflect.KClass @LargeTest @RunWith(AndroidJUnit4::class) class FragmentNavigatorTest { companion object { private const val INITIAL_FRAGMENT = 1 private const val SECOND_FRAGMENT = 2 private const val THIRD_FRAGMENT = 3 private const val FOURTH_FRAGMENT = 4 private const val TEST_LABEL = "test_label" } @Suppress("DEPRECATION") @get:Rule var activityRule = androidx.test.rule.ActivityTestRule(EmptyActivity::class.java) private lateinit var emptyActivity: EmptyActivity private lateinit var fragmentManager: FragmentManager private lateinit var navigatorState: TestNavigatorState private lateinit var fragmentNavigator: FragmentNavigator @Before fun setup() { emptyActivity = activityRule.activity fragmentManager = emptyActivity.supportFragmentManager navigatorState = TestNavigatorState() fragmentNavigator = FragmentNavigator(emptyActivity, fragmentManager, R.id.container) fragmentNavigator.onAttach(navigatorState) } @UiThreadTest @Test fun testNavigate() { val entry = createBackStackEntry() fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() assertWithMessage("Fragment should be the correct type") .that(fragment) .isInstanceOf(EmptyFragment::class.java) assertWithMessage("Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(fragment) } @UiThreadTest @Test fun testNavigateWithFragmentFactory() { fragmentManager.fragmentFactory = NonEmptyFragmentFactory() val entry = createBackStackEntry(clazz = NonEmptyConstructorFragment::class) fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() assertWithMessage("Fragment should be the correct type") .that(fragment) .isInstanceOf(NonEmptyConstructorFragment::class.java) assertWithMessage("Fragment should be the primary navigation Fragment") .that(fragment) .isSameInstanceAs(fragmentManager.primaryNavigationFragment) } @UiThreadTest @Test fun testNavigateTwice() { val entry = createBackStackEntry() fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() assertWithMessage("Fragment should be the correct type") .that(fragment) .isInstanceOf(EmptyFragment::class.java) assertWithMessage("Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(fragment) // Now push a second fragment val replacementEntry = createBackStackEntry(SECOND_FRAGMENT) fragmentNavigator.navigate(listOf(replacementEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, replacementEntry).inOrder() fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the correct type") .that(replacementFragment) .isInstanceOf(EmptyFragment::class.java) assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) } @UiThreadTest @Test fun testNavigateWithPopUpToThenPop() { val entry = createBackStackEntry() // Push initial fragment fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() // Push a second fragment val secondEntry = createBackStackEntry(SECOND_FRAGMENT) fragmentNavigator.navigate(listOf(secondEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, secondEntry).inOrder() fragmentManager.executePendingTransactions() // Pop and then push third fragment, simulating popUpTo to initial. fragmentNavigator.popBackStack(secondEntry, false) assertThat(navigatorState.backStack.value) .containsExactly(entry) val thirdEntry = createBackStackEntry(THIRD_FRAGMENT) fragmentNavigator.navigate(listOf(thirdEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, thirdEntry).inOrder() fragmentManager.executePendingTransactions() // Now pop the Fragment fragmentNavigator.popBackStack(thirdEntry, false) assertThat(navigatorState.backStack.value) .containsExactly(entry) } @UiThreadTest @Test fun testSingleTopInitial() { val entry = createBackStackEntry() fragmentNavigator.navigate(listOf(entry), null, null) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() val lifecycle = fragment!!.lifecycle fragmentNavigator.onLaunchSingleTop(entry) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the correct type") .that(replacementFragment) .isInstanceOf(EmptyFragment::class.java) assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) assertWithMessage("Replacement should be a new instance") .that(replacementFragment) .isNotSameInstanceAs(fragment) assertWithMessage("Old instance should be destroyed") .that(lifecycle.currentState) .isEqualTo(Lifecycle.State.DESTROYED) } @UiThreadTest @Test fun testSingleTop() { val entry = createBackStackEntry() // First push an initial Fragment fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val initialFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Initial Fragment should be added") .that(initialFragment) .isNotNull() // Now push the Fragment that we want to replace with a singleTop operation val replacementEntry = createBackStackEntry(SECOND_FRAGMENT) fragmentNavigator.navigate(listOf(replacementEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, replacementEntry).inOrder() fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() val lifecycle = fragment!!.lifecycle fragmentNavigator.onLaunchSingleTop(replacementEntry) assertThat(navigatorState.backStack.value) .containsExactly(entry, replacementEntry).inOrder() fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the correct type") .that(replacementFragment) .isInstanceOf(EmptyFragment::class.java) assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) assertWithMessage("Replacement should be a new instance") .that(replacementFragment) .isNotSameInstanceAs(fragment) assertWithMessage("Old instance should be destroyed") .that(lifecycle.currentState) .isEqualTo(Lifecycle.State.DESTROYED) fragmentNavigator.popBackStack(replacementEntry, false) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() assertWithMessage("Initial Fragment should be on top of back stack after pop") .that(fragmentManager.findFragmentById(R.id.container)) .isSameInstanceAs(initialFragment) assertWithMessage("Initial Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(initialFragment) } @UiThreadTest @Test fun testPopInitial() { val entry = createBackStackEntry() // First push an initial Fragment fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) // Now pop the initial Fragment fragmentNavigator.popBackStack(entry, false) assertThat(navigatorState.backStack.value) .isEmpty() } @UiThreadTest @Test fun testPop() { val entry = createBackStackEntry() // First push an initial Fragment fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() // Now push the Fragment that we want to pop val replacementEntry = createBackStackEntry(SECOND_FRAGMENT) fragmentNavigator.navigate(listOf(replacementEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, replacementEntry).inOrder() fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the correct type") .that(replacementFragment) .isInstanceOf(EmptyFragment::class.java) assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) // Now pop the Fragment fragmentNavigator.popBackStack(replacementEntry, false) fragmentManager.executePendingTransactions() assertThat(navigatorState.backStack.value) .containsExactly(entry) assertWithMessage("Fragment should be the primary navigation Fragment after pop") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(fragment) } @UiThreadTest @Test fun testPopWithSameDestinationTwice() { val entry = createBackStackEntry() // First push an initial Fragment fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() // Now push a second Fragment val secondEntry = createBackStackEntry(SECOND_FRAGMENT) fragmentNavigator.navigate(listOf(secondEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, secondEntry).inOrder() fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) // Push the same Fragment a second time, creating a stack of two // identical Fragments val replacementEntry = createBackStackEntry(SECOND_FRAGMENT) fragmentNavigator.navigate(listOf(replacementEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, secondEntry, replacementEntry).inOrder() fragmentManager.executePendingTransactions() val fragmentToPop = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment to pop should be added") .that(fragmentToPop) .isNotNull() assertWithMessage("Fragment to pop should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(fragmentToPop) // Now pop the Fragment fragmentNavigator.popBackStack(replacementEntry, false) fragmentManager.executePendingTransactions() assertThat(navigatorState.backStack.value) .containsExactly(entry, secondEntry).inOrder() assertWithMessage( "Replacement Fragment should be the primary navigation Fragment " + "after pop" ) .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) } @UiThreadTest @Test fun testPopWithChildFragmentBackStack() { val entry = createBackStackEntry() // First push an initial Fragment fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() // Now push the Fragment that we want to pop val replacementEntry = createBackStackEntry(SECOND_FRAGMENT) fragmentNavigator.navigate(listOf(replacementEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, replacementEntry).inOrder() fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the correct type") .that(replacementFragment) .isInstanceOf(EmptyFragment::class.java) assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) // Add a Fragment to the replacementFragment's childFragmentManager back stack replacementFragment?.childFragmentManager?.run { beginTransaction() .add(EmptyFragment(), "child") .addToBackStack(null) .commit() executePendingTransactions() } // Now pop the Fragment fragmentNavigator.popBackStack(replacementEntry, false) fragmentManager.executePendingTransactions() assertThat(navigatorState.backStack.value) .containsExactly(entry) assertWithMessage("Fragment should be the primary navigation Fragment after pop") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(fragment) } @UiThreadTest @Test fun testDeepLinkPop() { val entry = createBackStackEntry() val secondEntry = createBackStackEntry(SECOND_FRAGMENT) // First push two Fragments as our 'deep link' fragmentNavigator.navigate(listOf(entry, secondEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, secondEntry) // Now push the Fragment that we want to pop val thirdEntry = createBackStackEntry(THIRD_FRAGMENT) fragmentNavigator.navigate(listOf(thirdEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, secondEntry, thirdEntry) fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the correct type") .that(replacementFragment) .isInstanceOf(EmptyFragment::class.java) assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) // Now pop the Fragment fragmentNavigator.popBackStack(thirdEntry, false) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be the primary navigation Fragment after pop") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(fragment) } @UiThreadTest @Test fun testMultipleNavigateFragmentTransactionsThenPop() { val entry = createBackStackEntry() val secondEntry = createBackStackEntry(SECOND_FRAGMENT, clazz = Fragment::class) val thirdEntry = createBackStackEntry(THIRD_FRAGMENT) // Push 3 fragments without executing pending transactions. fragmentNavigator.navigate(listOf(entry, secondEntry, thirdEntry), null, null) // Now pop the Fragment fragmentNavigator.popBackStack(thirdEntry, false) fragmentManager.executePendingTransactions() assertThat(navigatorState.backStack.value) .containsExactly(entry, secondEntry) // We should ensure the fragment manager is on the proper fragment at the end assertWithMessage("FragmentManager back stack should have only SECOND_FRAGMENT") .that(fragmentManager.backStackEntryCount) .isEqualTo(1) assertWithMessage("PrimaryFragment should be the correct type") .that(fragmentManager.primaryNavigationFragment) .isNotInstanceOf(EmptyFragment::class.java) } @UiThreadTest @Test fun testMultiplePopFragmentTransactionsThenPop() { val entry = createBackStackEntry() val secondEntry = createBackStackEntry(SECOND_FRAGMENT) val thirdEntry = createBackStackEntry(THIRD_FRAGMENT) val fourthEntry = createBackStackEntry(FOURTH_FRAGMENT) // Push 4 fragments fragmentNavigator.navigate( listOf(entry, secondEntry, thirdEntry, fourthEntry), null, null ) fragmentManager.executePendingTransactions() // Pop 2 fragments without executing pending transactions. fragmentNavigator.popBackStack(thirdEntry, false) fragmentNavigator.popBackStack(secondEntry, false) fragmentManager.executePendingTransactions() assertThat(navigatorState.backStack.value) .containsExactly(entry) } @UiThreadTest @Test fun testSaveRestoreState() { val entry = createBackStackEntry() // First push an initial Fragment fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() // Now push the Fragment that we want to save val replacementEntry = createBackStackEntry(SECOND_FRAGMENT, SavedStateFragment::class) fragmentNavigator.navigate(listOf(replacementEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, replacementEntry).inOrder() fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the correct type") .that(replacementFragment) .isInstanceOf(SavedStateFragment::class.java) assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) // Save some state into the replacement fragment (replacementFragment as SavedStateFragment).savedState = "test" // Now save the Fragment fragmentNavigator.popBackStack(replacementEntry, true) fragmentManager.executePendingTransactions() assertThat(navigatorState.backStack.value) .containsExactly(entry) assertWithMessage("Fragment should be the primary navigation Fragment after pop") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(fragment) // And now restore the fragment val restoredEntry = navigatorState.restoreBackStackEntry(replacementEntry) fragmentNavigator.navigate( listOf(restoredEntry), NavOptions.Builder().setRestoreState(true).build(), null ) assertThat(navigatorState.backStack.value) .containsExactly(entry, restoredEntry).inOrder() fragmentManager.executePendingTransactions() val restoredFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Restored Fragment should be added") .that(restoredFragment) .isNotNull() assertWithMessage("Restored Fragment should be the correct type") .that(restoredFragment) .isInstanceOf(SavedStateFragment::class.java) assertWithMessage("Restored Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(restoredFragment) assertWithMessage("Restored Fragment should have its state restored") .that((restoredFragment as SavedStateFragment).savedState) .isEqualTo("test") } @UiThreadTest @Test fun testSaveRestoreStateAfterSaveState() { val entry = createBackStackEntry() // First push an initial Fragment fragmentNavigator.navigate(listOf(entry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry) fragmentManager.executePendingTransactions() val fragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Fragment should be added") .that(fragment) .isNotNull() // Now push the Fragment that we want to save val replacementEntry = createBackStackEntry(SECOND_FRAGMENT, SavedStateFragment::class) fragmentNavigator.navigate(listOf(replacementEntry), null, null) assertThat(navigatorState.backStack.value) .containsExactly(entry, replacementEntry).inOrder() fragmentManager.executePendingTransactions() val replacementFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Replacement Fragment should be added") .that(replacementFragment) .isNotNull() assertWithMessage("Replacement Fragment should be the correct type") .that(replacementFragment) .isInstanceOf(SavedStateFragment::class.java) assertWithMessage("Replacement Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(replacementFragment) // Save some state into the replacement fragment (replacementFragment as SavedStateFragment).savedState = "test" // Now save the Fragment fragmentNavigator.popBackStack(replacementEntry, true) fragmentManager.executePendingTransactions() assertThat(navigatorState.backStack.value) .containsExactly(entry) assertWithMessage("Fragment should be the primary navigation Fragment after pop") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(fragment) // Create a new FragmentNavigator, replacing the previous one val savedState = fragmentNavigator.onSaveState() as Bundle fragmentNavigator = FragmentNavigator( emptyActivity, fragmentManager, R.id.container ) fragmentNavigator.onAttach(navigatorState) fragmentNavigator.onRestoreState(savedState) // And now restore the fragment val restoredEntry = navigatorState.restoreBackStackEntry(replacementEntry) fragmentNavigator.navigate( listOf(restoredEntry), NavOptions.Builder().setRestoreState(true).build(), null ) assertThat(navigatorState.backStack.value) .containsExactly(entry, restoredEntry).inOrder() fragmentManager.executePendingTransactions() val restoredFragment = fragmentManager.findFragmentById(R.id.container) assertWithMessage("Restored Fragment should be added") .that(restoredFragment) .isNotNull() assertWithMessage("Restored Fragment should be the correct type") .that(restoredFragment) .isInstanceOf(SavedStateFragment::class.java) assertWithMessage("Restored Fragment should be the primary navigation Fragment") .that(fragmentManager.primaryNavigationFragment) .isSameInstanceAs(restoredFragment) assertWithMessage("Restored Fragment should have its state restored") .that((restoredFragment as SavedStateFragment).savedState) .isEqualTo("test") } @Test fun testToString() { val destination = fragmentNavigator.createDestination().apply { id = INITIAL_FRAGMENT setClassName(EmptyFragment::class.java.name) label = TEST_LABEL } val expected = "Destination(0x${INITIAL_FRAGMENT.toString(16)}) label=test_label " + "class=${EmptyFragment::class.java.name}" assertThat(destination.toString()).isEqualTo(expected) } @Test fun testToStringNoClassName() { val destination = fragmentNavigator.createDestination().apply { id = INITIAL_FRAGMENT label = TEST_LABEL } val expected = "Destination(0x${INITIAL_FRAGMENT.toString(16)}) label=test_label " + "class=null" assertThat(destination.toString()).isEqualTo(expected) } private fun createBackStackEntry( destId: Int = INITIAL_FRAGMENT, clazz: KClass<out Fragment> = EmptyFragment::class ): NavBackStackEntry { val destination = fragmentNavigator.createDestination().apply { id = destId setClassName(clazz.java.name) } return navigatorState.createBackStackEntry(destination, null) } } class EmptyActivity : FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.empty_activity) } } class SavedStateFragment : Fragment() { var savedState: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedState = savedInstanceState?.getString("savedState") } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("savedState", savedState) } } class NonEmptyConstructorFragment(val test: String) : Fragment() class NonEmptyFragmentFactory : FragmentFactory() { override fun instantiate( classLoader: ClassLoader, className: String ) = if (className == NonEmptyConstructorFragment::class.java.name) { NonEmptyConstructorFragment("test") } else { super.instantiate(classLoader, className) } }
apache-2.0
57fda6d8d273e8bb6fbbd32eae7be5f4
41.850067
95
0.695148
5.688466
false
true
false
false
AndroidX/androidx
camera/camera-core/src/androidTest/java/androidx/camera/core/imagecapture/FakeTakePictureCallback.kt
3
2711
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.camera.core.imagecapture import androidx.camera.core.ImageCapture.OutputFileResults import androidx.camera.core.ImageCaptureException import androidx.camera.core.ImageProxy import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine /** * Fake [TakePictureCallback] for getting the results asynchronously. */ class FakeTakePictureCallback : TakePictureCallback { private var inMemoryResult: ImageProxy? = null private var inMemoryResultCont: Continuation<ImageProxy>? = null private var onDiskResult: OutputFileResults? = null private var onDiskResultCont: Continuation<OutputFileResults>? = null override fun onImageCaptured() { TODO("Not yet implemented") } override fun onFinalResult(outputFileResults: OutputFileResults) { val cont = onDiskResultCont if (cont != null) { cont.resume(outputFileResults) onDiskResultCont = null } else { onDiskResult = outputFileResults } } override fun onFinalResult(imageProxy: ImageProxy) { val cont = inMemoryResultCont if (cont != null) { cont.resume(imageProxy) inMemoryResultCont = null } else { inMemoryResult = imageProxy } } override fun onCaptureFailure(imageCaptureException: ImageCaptureException) { TODO("Not yet implemented") } override fun onProcessFailure(imageCaptureException: ImageCaptureException) { TODO("Not yet implemented") } override fun isAborted(): Boolean { return false } internal suspend fun getInMemoryResult() = suspendCoroutine { cont -> if (inMemoryResult != null) { cont.resume(inMemoryResult!!) } else { inMemoryResultCont = cont } } internal suspend fun getOnDiskResult() = suspendCoroutine { cont -> if (onDiskResult != null) { cont.resume(onDiskResult!!) } else { onDiskResultCont = cont } } }
apache-2.0
91f0831748a308c7a6b4e47fceeeaed4
30.172414
81
0.682405
4.781305
false
false
false
false
zielu/GitToolBox
src/test/kotlin/zielu/intellij/test/MockItemSelectable.kt
1
860
package zielu.intellij.test import java.awt.ItemSelectable import java.awt.event.ItemEvent import java.awt.event.ItemListener internal class MockItemSelectable : ItemSelectable { private val listeners = mutableListOf<ItemListener>() private var selected: Array<Any>? = null fun setSelectedObjects(selected: Array<Any>?) { this.selected = selected } fun fireSelected() { val item = if (selected != null) selected!![0] else null val event = ItemEvent( this, ItemEvent.ITEM_STATE_CHANGED, item, ItemEvent.SELECTED ) listeners.forEach { it.itemStateChanged(event) } } override fun getSelectedObjects(): Array<Any>? { return selected } override fun addItemListener(l: ItemListener) { listeners.add(l) } override fun removeItemListener(l: ItemListener) { listeners.remove(l) } }
apache-2.0
6339358e3c1f1be09d1761ba41255acf
22.243243
60
0.702326
4.174757
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/top-mpp/src/jsJvm18iOSMain/kotlin/transitiveStory/bottomActual/intermediateSrc/InBottomActualIntermediate.kt
2
1108
package transitiveStory.bottomActual.intermediateSrc import transitiveStory.bottomActual.mppBeginning.MPOuter import transitiveStory.bottomActual.mppBeginning.Outer import transitiveStory.bottomActual.mppBeginning.tlInternalInCommon //import transitiveStory.bottomActual.mppBeginning.tlInternalInCommon class InBottomActualIntermediate { val p = 42 // https://youtrack.jetbrains.com/issue/KT-37264 val callingInteral = tlInternalInCommon } expect class <!LINE_MARKER("descr='Has actuals in Native, JS, JVM'")!>IntermediateMPPClassInBottomActual<!>() class Subclass : Outer() { // a is not visible // b, c and d are visible // Nested and e are visible override val <!LINE_MARKER("descr='Overrides property in 'Outer''")!>b<!> = 5 // 'b' is protected } class ChildOfCommonInShared : Outer() { override val <!LINE_MARKER("descr='Overrides property in 'Outer''")!>b<!>: Int get() = super.b + 243 // val callAlso = super.c // internal in Outer private val other = Nested() } class ChildOfMPOuterInShared : MPOuter() { private val sav = MPNested() }
apache-2.0
8e47ab1ea63b24292b661dfb4ada897b
28.945946
109
0.726534
4.134328
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/util/Animation.kt
1
484
package com.cout970.modeler.util import kotlin.math.absoluteValue import kotlin.math.ceil import kotlin.math.roundToInt fun Float.toFrame(): Int = (this * 60f).roundToInt() fun Int.fromFrame(): Float = this / 60f fun Double.roundTo(value: Double): Double = ceil(this * value) / value inline fun Int.isOdd(): Boolean = this % 2 != 0 inline fun Int.isEven(): Boolean = this % 2 == 0 fun Double.aprox(other: Double, epsilon: Double = 0.001) = (this - other).absoluteValue < epsilon
gpl-3.0
31fe4148f3e8efde3403590241838834
29.3125
97
0.719008
3.432624
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/export/ExportManager.kt
1
3781
package com.cout970.modeler.core.export import com.cout970.modeler.PathConstants import com.cout970.modeler.api.model.IModel import com.cout970.modeler.core.export.project.ProjectLoaderV10 import com.cout970.modeler.core.export.project.ProjectLoaderV11 import com.cout970.modeler.core.export.project.ProjectLoaderV12 import com.cout970.modeler.core.export.project.ProjectLoaderV13 import com.cout970.modeler.core.log.Level import com.cout970.modeler.core.log.log import com.cout970.modeler.core.log.print import com.cout970.modeler.core.model.material.TexturedMaterial import com.cout970.modeler.core.project.ProjectManager import com.cout970.modeler.core.project.ProjectProperties import com.cout970.modeler.core.resource.ResourceLoader import com.cout970.modeler.gui.Gui import com.cout970.modeler.gui.event.pushNotification import com.cout970.modeler.util.createParentsIfNeeded import com.google.gson.GsonBuilder import java.io.File import java.util.* import java.util.zip.ZipFile /** * Created by cout970 on 2017/01/02. */ class ExportManager(val resourceLoader: ResourceLoader) { companion object { const val CURRENT_SAVE_VERSION = "1.3" val VERSION_GSON = GsonBuilder().create()!! } fun loadProject(path: String): ProgramSave { val zip = ZipFile(path) val version = zip.load<String>("version.json", VERSION_GSON) ?: throw IllegalStateException("Missing file 'version.json' inside '$path'") return when (version) { "1.0" -> ProjectLoaderV10.loadProject(zip, path) "1.1" -> ProjectLoaderV11.loadProject(zip, path) "1.2" -> ProjectLoaderV12.loadProject(zip, path) "1.3" -> ProjectLoaderV13.loadProject(zip, path) else -> throw IllegalStateException("Invalid save version $version") } } fun saveProject(path: String, save: ProgramSave) { log(Level.FINE) { "Starting project save" } File(path).createParentsIfNeeded() ProjectLoaderV13.saveProject(path, save) log(Level.FINE) { "Project saved" } } fun saveProject(path: String, manager: ProjectManager, saveImages: Boolean) { saveProject(path, ProgramSave(CURRENT_SAVE_VERSION, manager.projectProperties, manager.model, if (saveImages) manager.materialPaths else emptyList())) } fun import(file: String): IModel { return loadProject(file).model.modifyObjects({ true }) { _, obj -> obj.withId(UUID.randomUUID()) } } fun loadLastProjectIfExists(projectManager: ProjectManager, gui: Gui) { val path = File(PathConstants.LAST_BACKUP_FILE_PATH) if (path.exists()) { try { log(Level.FINE) { "Found last project, loading..." } val save = loadProject(path.path) projectManager.loadProjectProperties(save.projectProperties) projectManager.updateModel(save.model) gui.windowHandler.updateTitle(save.projectProperties.name) save.model.materials.forEach { it.loadTexture(resourceLoader) } log(Level.FINE) { "Last project loaded" } pushNotification("Project loaded", "Loaded project from last execution") } catch (e: Exception) { log(Level.ERROR) { "Unable to load last project" } e.print() pushNotification("Error loading project", "Unable to load project at '${path.absolutePath}': $e") } } else { log(Level.FINE) { "No last project found, ignoring" } } } } data class ProgramSave( val version: String, val projectProperties: ProjectProperties, val model: IModel, val textures: List<TexturedMaterial> )
gpl-3.0
fad5380de00f893adad8f7d4e5613282
38.395833
113
0.675747
4.123228
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/coverage/src/org/jetbrains/kotlin/idea/coverage/KotlinCoverageExtension.kt
2
7773
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.coverage import com.intellij.coverage.* import com.intellij.execution.configurations.RunConfigurationBase import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiClass import com.intellij.psi.PsiFile import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.PsiUtilCore import org.jetbrains.kotlin.config.TestSourceKotlinRootType import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.idea.base.projectStructure.getKotlinSourceRootType import org.jetbrains.kotlin.idea.run.KotlinRunConfiguration import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import java.io.File class KotlinCoverageExtension : JavaCoverageEngineExtension() { override fun isApplicableTo(conf: RunConfigurationBase<*>?): Boolean = conf is KotlinRunConfiguration override fun suggestQualifiedName(sourceFile: PsiFile, classes: Array<out PsiClass>, names: MutableSet<String>): Boolean { if (sourceFile is KtFile) { val qNames = collectGeneratedClassQualifiedNames(findOutputRoots(sourceFile), sourceFile) if (qNames != null) { names.addAll(qNames) return true } } return false } override fun getSummaryCoverageInfo( coverageAnnotator: JavaCoverageAnnotator, element: PsiNamedElement ): PackageAnnotator.ClassCoverageInfo? { if (element is KtClassOrObject) { val searchScope = CoverageDataManager.getInstance(element.project) ?.currentSuitesBundle ?.getSearchScope(element.project) ?: return null val vFile = PsiUtilCore.getVirtualFile(element) ?: return null if (!searchScope.contains(vFile)) return null return coverageAnnotator.getClassCoverageInfo(element.fqName?.asString()) } if (element !is KtFile) { return null } LOG.info("Retrieving coverage for " + element.name) val qualifiedNames = collectGeneratedClassQualifiedNames(findOutputRoots(element), element) return if (qualifiedNames.isNullOrEmpty()) null else totalCoverageForQualifiedNames(coverageAnnotator, qualifiedNames) } override fun keepCoverageInfoForClassWithoutSource(bundle: CoverageSuitesBundle, classFile: File): Boolean { // TODO check scope and source roots return true // keep everything, sort it out later } override fun collectOutputFiles( srcFile: PsiFile, output: VirtualFile?, testoutput: VirtualFile?, suite: CoverageSuitesBundle, classFiles: MutableSet<File> ): Boolean { if (srcFile is KtFile) { val fileIndex = ProjectRootManager.getInstance(srcFile.getProject()).fileIndex if (fileIndex.isInLibraryClasses(srcFile.getVirtualFile()) || fileIndex.isInLibrarySource(srcFile.getVirtualFile()) ) { return false } return runReadAction { val outputRoots = findOutputRoots(srcFile) ?: return@runReadAction false val existingClassFiles = getClassesGeneratedFromFile(outputRoots, srcFile) existingClassFiles.mapTo(classFiles) { File(it.path) } true } } return false } companion object { private val LOG = Logger.getInstance(KotlinCoverageExtension::class.java) fun collectGeneratedClassQualifiedNames(outputRoots: Array<VirtualFile>?, file: KtFile): List<String>? = outputRoots?.flatMap { collectGeneratedClassQualifiedNames(it, file) ?: emptyList() } fun collectGeneratedClassQualifiedNames(outputRoot: VirtualFile?, file: KtFile): List<String>? { val existingClassFiles = getClassesGeneratedFromFile(outputRoot, file) if (existingClassFiles.isEmpty()) { return null } LOG.debug("ClassFiles: [${existingClassFiles.joinToString { it.name }}]") return existingClassFiles.map { val relativePath = VfsUtilCore.getRelativePath(it, outputRoot!!)!! StringUtil.trimEnd(relativePath, ".class").replace("/", ".") } } private fun totalCoverageForQualifiedNames( coverageAnnotator: JavaCoverageAnnotator, qualifiedNames: List<String> ): PackageAnnotator.ClassCoverageInfo { val result = PackageAnnotator.ClassCoverageInfo() result.totalClassCount = 0 qualifiedNames.forEach { val classInfo = coverageAnnotator.getClassCoverageInfo(it) if (classInfo != null) { result.totalClassCount += classInfo.totalClassCount result.coveredClassCount += classInfo.coveredClassCount result.totalMethodCount += classInfo.totalMethodCount result.coveredMethodCount += classInfo.coveredMethodCount result.totalLineCount += classInfo.totalLineCount result.fullyCoveredLineCount += classInfo.fullyCoveredLineCount result.partiallyCoveredLineCount += classInfo.partiallyCoveredLineCount } else { LOG.debug("Found no coverage for $it") } } return result } private fun getClassesGeneratedFromFile(outputRoots: Array<VirtualFile>, file: KtFile): List<VirtualFile> = outputRoots.flatMap { getClassesGeneratedFromFile(it, file) } private fun getClassesGeneratedFromFile(outputRoot: VirtualFile?, file: KtFile): List<VirtualFile> { val relativePath = file.packageFqName.asString().replace('.', '/') val packageOutputDir = outputRoot?.findFileByRelativePath(relativePath) ?: return listOf() val prefixes = collectClassFilePrefixes(file) LOG.debug("ClassFile prefixes: [${prefixes.joinToString(", ")}]") return packageOutputDir.children.filter { packageFile -> prefixes.any { (packageFile.name.startsWith("$it$") && FileUtilRt.getExtension(packageFile.name) == "class") || packageFile.name == "$it.class" } } } private fun findOutputRoots(file: KtFile): Array<VirtualFile>? { val module = ModuleUtilCore.findModuleForPsiElement(file) ?: return null val fileIndex = ProjectRootManager.getInstance(file.project).fileIndex val inTests = fileIndex.getKotlinSourceRootType(file.virtualFile) == TestSourceKotlinRootType return JavaCoverageClassesEnumerator.getRoots(CoverageDataManager.getInstance(file.project), module, inTests) } private fun collectClassFilePrefixes(file: KtFile): Collection<String> { val result = file.children.filterIsInstance<KtClassOrObject>().mapNotNull { it.name } val packagePartFqName = JvmFileClassUtil.getFileClassInfoNoResolve(file).fileClassFqName return result.union(arrayListOf(packagePartFqName.shortName().asString())) } } }
apache-2.0
28e05d990aed13be4e8eeab942ee4689
46.396341
158
0.675415
5.36069
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceAssociateFunctionInspection.kt
1
10988
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING import com.intellij.codeInspection.ProblemHighlightType.INFORMATION import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.getLastLambdaExpression import org.jetbrains.kotlin.idea.inspections.AssociateFunction.* import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ReplaceAssociateFunctionInspection : AbstractKotlinInspection() { companion object { private val associateFunctionNames = listOf("associate", "associateTo") private val associateFqNames = listOf(FqName("kotlin.collections.associate"), FqName("kotlin.sequences.associate")) private val associateToFqNames = listOf(FqName("kotlin.collections.associateTo"), FqName("kotlin.sequences.associateTo")) fun getAssociateFunctionAndProblemHighlightType( dotQualifiedExpression: KtDotQualifiedExpression, context: BindingContext = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL) ): Pair<AssociateFunction, ProblemHighlightType>? { val callExpression = dotQualifiedExpression.callExpression ?: return null val lambda = callExpression.lambda() ?: return null if (lambda.valueParameters.size > 1) return null val functionLiteral = lambda.functionLiteral if (functionLiteral.anyDescendantOfType<KtReturnExpression> { it.labelQualifier != null }) return null val lastStatement = functionLiteral.lastStatement() ?: return null val (keySelector, valueTransform) = lastStatement.pair(context) ?: return null val lambdaParameter = context[BindingContext.FUNCTION, functionLiteral]?.valueParameters?.singleOrNull() ?: return null return when { keySelector.isReferenceTo(lambdaParameter, context) -> { val receiver = dotQualifiedExpression.receiverExpression.getResolvedCall(context)?.resultingDescriptor?.returnType ?: return null if ((KotlinBuiltIns.isArray(receiver) || KotlinBuiltIns.isPrimitiveArray(receiver)) && dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_4 ) return null ASSOCIATE_WITH to GENERIC_ERROR_OR_WARNING } valueTransform.isReferenceTo(lambdaParameter, context) -> ASSOCIATE_BY to GENERIC_ERROR_OR_WARNING else -> { if (functionLiteral.bodyExpression?.statements?.size != 1) return null ASSOCIATE_BY_KEY_AND_VALUE to INFORMATION } } } private fun KtExpression.isReferenceTo(descriptor: ValueParameterDescriptor, context: BindingContext): Boolean { return (this as? KtNameReferenceExpression)?.getResolvedCall(context)?.resultingDescriptor == descriptor } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = dotQualifiedExpressionVisitor(fun(dotQualifiedExpression) { if (dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_3) return val callExpression = dotQualifiedExpression.callExpression ?: return val calleeExpression = callExpression.calleeExpression ?: return if (calleeExpression.text !in associateFunctionNames) return val context = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL) val fqName = callExpression.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe ?: return val isAssociate = fqName in associateFqNames val isAssociateTo = fqName in associateToFqNames if (!isAssociate && !isAssociateTo) return val (associateFunction, highlightType) = getAssociateFunctionAndProblemHighlightType(dotQualifiedExpression, context) ?: return holder.registerProblemWithoutOfflineInformation( calleeExpression, KotlinBundle.message("replace.0.with.1", calleeExpression.text, associateFunction.name(isAssociateTo)), isOnTheFly, highlightType, ReplaceAssociateFunctionFix(associateFunction, isAssociateTo) ) }) } class ReplaceAssociateFunctionFix(private val function: AssociateFunction, private val hasDestination: Boolean) : LocalQuickFix { private val functionName = function.name(hasDestination) override fun getName() = KotlinBundle.message("replace.with.0", functionName) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val dotQualifiedExpression = descriptor.psiElement.getStrictParentOfType<KtDotQualifiedExpression>() ?: return val receiverExpression = dotQualifiedExpression.receiverExpression val callExpression = dotQualifiedExpression.callExpression ?: return val lambda = callExpression.lambda() ?: return val lastStatement = lambda.functionLiteral.lastStatement() ?: return val (keySelector, valueTransform) = lastStatement.pair() ?: return val psiFactory = KtPsiFactory(dotQualifiedExpression) if (function == ASSOCIATE_BY_KEY_AND_VALUE) { val destination = if (hasDestination) { callExpression.valueArguments.firstOrNull()?.getArgumentExpression() ?: return } else { null } val newExpression = psiFactory.buildExpression { appendExpression(receiverExpression) appendFixedText(".") appendFixedText(functionName) appendFixedText("(") if (destination != null) { appendExpression(destination) appendFixedText(",") } appendLambda(lambda, keySelector) appendFixedText(",") appendLambda(lambda, valueTransform) appendFixedText(")") } dotQualifiedExpression.replace(newExpression) } else { lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector) val newExpression = psiFactory.buildExpression { appendExpression(receiverExpression) appendFixedText(".") appendFixedText(functionName) val valueArgumentList = callExpression.valueArgumentList if (valueArgumentList != null) { appendValueArgumentList(valueArgumentList) } if (callExpression.lambdaArguments.isNotEmpty()) { appendLambda(lambda) } } dotQualifiedExpression.replace(newExpression) } } private fun BuilderByPattern<KtExpression>.appendLambda(lambda: KtLambdaExpression, body: KtExpression? = null) { appendFixedText("{") lambda.valueParameters.firstOrNull()?.nameAsName?.also { appendName(it) appendFixedText("->") } if (body != null) { appendExpression(body) } else { lambda.bodyExpression?.allChildren?.let(this::appendChildRange) } appendFixedText("}") } private fun BuilderByPattern<KtExpression>.appendValueArgumentList(valueArgumentList: KtValueArgumentList) { appendFixedText("(") valueArgumentList.arguments.forEachIndexed { index, argument -> if (index > 0) appendFixedText(",") appendExpression(argument.getArgumentExpression()) } appendFixedText(")") } companion object { fun replaceLastStatementForAssociateFunction(callExpression: KtCallExpression, function: AssociateFunction) { val lastStatement = callExpression.lambda()?.functionLiteral?.lastStatement() ?: return val (keySelector, valueTransform) = lastStatement.pair() ?: return lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector) } } } enum class AssociateFunction(val functionName: String) { ASSOCIATE_WITH("associateWith"), ASSOCIATE_BY("associateBy"), ASSOCIATE_BY_KEY_AND_VALUE("associateBy"); fun name(hasDestination: Boolean): String { return if (hasDestination) "${functionName}To" else functionName } } private fun KtCallExpression.lambda(): KtLambdaExpression? { return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression() } private fun KtFunctionLiteral.lastStatement(): KtExpression? { return bodyExpression?.statements?.lastOrNull() } private fun KtExpression.pair(context: BindingContext = analyze(BodyResolveMode.PARTIAL)): Pair<KtExpression, KtExpression>? { return when (this) { is KtBinaryExpression -> { if (operationReference.text != "to") return null val left = left ?: return null val right = right ?: return null left to right } is KtCallExpression -> { if (calleeExpression?.text != "Pair") return null if (valueArguments.size != 2) return null if (getResolvedCall(context)?.resultingDescriptor?.containingDeclaration?.fqNameSafe != FqName("kotlin.Pair")) return null val first = valueArguments[0]?.getArgumentExpression() ?: return null val second = valueArguments[1]?.getArgumentExpression() ?: return null first to second } else -> return null } }
apache-2.0
bcac6312d6def9b2de7aaff14831b7bb
48.95
158
0.695213
5.994544
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/tests/test/org/jetbrains/kotlin/gradle/GradleMultiplatformHighlightingTest.kt
1
8368
// 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.gradle import com.intellij.codeInsight.EditorInfo import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.testFramework.ExpectedHighlightingData import com.intellij.testFramework.VfsTestUtil import com.intellij.testFramework.runInEdtAndWait import junit.framework.TestCase import org.jetbrains.kotlin.idea.codeInsight.gradle.MultiplePluginVersionGradleImportingTestCase import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.TagsTestDataUtil import org.jetbrains.kotlin.test.TagsTestDataUtil.TagInfo import org.jetbrains.plugins.gradle.tooling.annotation.PluginTargetVersions import org.junit.Assert import org.junit.Test import java.io.File class GradleMultiplatformHighlightingTest : MultiplePluginVersionGradleImportingTestCase() { @Test @PluginTargetVersions(pluginVersion = "1.3.0+") fun testFirst() { doTest() } @Test @PluginTargetVersions(pluginVersion = "1.3.0+") fun testNoErrors() { doTest() } private fun doTest() { val files = importProjectFromTestData() val project = myTestFixture.project checkFiles( files.filter { it.extension == "kt" }, project, object : GradleDaemonAnalyzerTestCase( testLineMarkers = true, checkWarnings = true, checkInfos = false, rootDisposable = testRootDisposable ) {} ) } override fun testDataDirName(): String { return "newMultiplatformHighlighting" } } abstract class GradleDaemonAnalyzerTestCase( val testLineMarkers: Boolean, val checkWarnings: Boolean, val checkInfos: Boolean, private val rootDisposable: Disposable, private val sanitizer: (String) -> String = { it } ) : DaemonAnalyzerTestCase() { override fun doTestLineMarkers() = testLineMarkers fun checkHighlighting(project: Project, editor: Editor) { myProject = project try { runInEdtAndWait { // This will prepare ExpectedHighlightingData, clear current editor from testing tags, and then // call doCheckResult, which we override checkHighlighting(editor, checkWarnings, checkInfos) } } finally { myProject = null } } // We have to override doCheckResult because one from DaemonAnalyzerTestCase has few flaws: // - overlapping line markers lead to crash in 193 (fixed in later versions) // - it checks line markers and rest of highlighting *separately*, which means that we can't put both in // expected test data // - no API to sanitize error descriptions (in particular, we have to remove endlines in diagnostic messages, // otherwise parser in testdata goes completely insane) override fun doCheckResult(data: ExpectedHighlightingData, infos: MutableCollection<HighlightInfo>, text: String) { performGenericHighlightingAndLineMarkersChecks(infos, text) performAdditionalChecksAfterHighlighting(editor) } private fun performGenericHighlightingAndLineMarkersChecks(infos: Collection<HighlightInfo>, text: String) { val lineMarkersTags: List<TagInfo<*>> = if (testLineMarkers) { TagsTestDataUtil.toLineMarkerTagPoints( DaemonCodeAnalyzerImpl.getLineMarkers(getDocument(file), project), /* withDescription = */ true ) } else { emptyList() } val filteredHighlights = infos.filterNot { it.severity == HighlightSeverity.INFORMATION && !checkInfos || it.severity == HighlightSeverity.WARNING && !checkWarnings } val highlightsTags: List<TagInfo<*>> = TagsTestDataUtil.toHighlightTagPoints(filteredHighlights) val allTags = lineMarkersTags + highlightsTags val actualTextWithTags = TagsTestDataUtil.insertTagsInText(allTags, text) { renderAdditionalAttributeForTag(it) } val physicalFileWithExpectedTestData = file.testDataFileByUserData KotlinTestUtils.assertEqualsToFile(physicalFileWithExpectedTestData, actualTextWithTags, sanitizer) } protected open fun performAdditionalChecksAfterHighlighting(editor: Editor) { } protected open fun renderAdditionalAttributeForTag(tag: TagInfo<*>): String? = null override fun getTestRootDisposable() = rootDisposable } fun checkFiles( files: List<VirtualFile>, project: Project, analyzer: GradleDaemonAnalyzerTestCase ) { var atLeastOneFile = false // We have to first load all files into the project and only then start // highlighting, otherwise cross-file references might not work val editors = files.map { file -> atLeastOneFile = true val originalText= VfsUtil.loadText(file) val textWithoutTags = textWithoutTags(originalText) configureEditorByExistingFile(file, project, textWithoutTags) } editors.forEach { analyzer.checkHighlighting(project, it) } Assert.assertTrue(atLeastOneFile) } internal fun textWithoutTags(text: String): String { val regex = "</?(error|warning|lineMarker).*?>".toRegex() return regex.replace(text, "") } private fun createEditor(file: VirtualFile, project: Project): Editor { val instance = FileEditorManager.getInstance(project) PsiDocumentManager.getInstance(project).commitAllDocuments() val editor = instance.openTextEditor(OpenFileDescriptor(project, file, 0), false) (editor as EditorImpl).setCaretActive() PsiDocumentManager.getInstance(project).commitAllDocuments() DaemonCodeAnalyzer.getInstance(project).restart() return editor } internal fun configureEditorByExistingFile( virtualFile: VirtualFile, project: Project, contentToSet: String ): Editor { var result: Editor? = null runInEdtAndWait { val editor = createEditor(virtualFile, project) val document = editor.document val editorInfo = EditorInfo(document.text) ApplicationManager.getApplication().runWriteAction { if (document.text != contentToSet) { document.setText(contentToSet) } editorInfo.applyToEditor(editor) } PsiDocumentManager.getInstance(project).commitAllDocuments() result = editor } return result!! } /** * Returns original physical file with expected test data, i.e. something like 'kotlin/idea/testData/gradle/runConfigurations/myTest/Foo.kt' * * Note that it's different from physical file used in project during test run (which is usually a copy in temporary folder) * * All inheritors of GradleImportingTestCase should normally have PsiFiles with properly attached UserData to them * (see [org.jetbrains.kotlin.idea.codeInsight.gradle.KotlinGradleImportingTestCase.configureByFiles]) */ internal val VirtualFile.testDataFileByUserData: File get() { val physicalFileWithExpectedTestData = File(this.getUserData(VfsTestUtil.TEST_DATA_FILE_PATH)!!) TestCase.assertTrue( "Can't find file with expected test data by absolute path ${physicalFileWithExpectedTestData.absolutePath}", physicalFileWithExpectedTestData.exists() ) return physicalFileWithExpectedTestData } internal val PsiFile.testDataFileByUserData: File get() = virtualFile.testDataFileByUserData
apache-2.0
6943c3feb031bce692cda72aee8b3050
38.471698
158
0.728131
5.028846
false
true
false
false
siosio/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/open/GradleProjectImportUtil.kt
2
5092
// 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. @file:JvmName("GradleProjectImportUtil") package org.jetbrains.plugins.gradle.service.project.open import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.io.systemIndependentPath import com.intellij.util.text.nullize import org.jetbrains.annotations.ApiStatus import org.jetbrains.plugins.gradle.service.GradleInstallationManager import org.jetbrains.plugins.gradle.settings.DistributionType import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.gradle.util.GradleEnvironment import org.jetbrains.plugins.gradle.util.GradleUtil import org.jetbrains.plugins.gradle.util.setupGradleJvm import java.nio.file.Path fun canOpenGradleProject(file: VirtualFile): Boolean = GradleOpenProjectProvider().canOpenProject(file) fun openGradleProject(projectFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? = GradleOpenProjectProvider().openProject(projectFile, projectToClose, forceOpenInNewFrame) @ApiStatus.Experimental @JvmOverloads fun canLinkAndRefreshGradleProject(projectFilePath: String, project: Project, showValidationDialog: Boolean = true): Boolean { val validationInfo = validateGradleProject(projectFilePath, project) ?: return true if (showValidationDialog) { val title = ExternalSystemBundle.message("error.project.import.error.title") when (validationInfo.warning) { true -> Messages.showWarningDialog(project, validationInfo.message, title) else -> Messages.showErrorDialog(project, validationInfo.message, title) } } return false } fun linkAndRefreshGradleProject(projectFilePath: String, project: Project) { GradleOpenProjectProvider().linkToExistingProject(projectFilePath, project) } @ApiStatus.Internal fun createLinkSettings(projectDirectory: Path, project: Project): GradleProjectSettings { val gradleSettings = GradleSettings.getInstance(project) gradleSettings.setupGradleSettings() val gradleProjectSettings = GradleProjectSettings() gradleProjectSettings.setupGradleProjectSettings(project, projectDirectory) val gradleVersion = gradleProjectSettings.resolveGradleVersion() setupGradleJvm(project, gradleProjectSettings, gradleVersion) return gradleProjectSettings } @ApiStatus.Internal fun GradleSettings.setupGradleSettings() { gradleVmOptions = GradleEnvironment.Headless.GRADLE_VM_OPTIONS ?: gradleVmOptions isOfflineWork = GradleEnvironment.Headless.GRADLE_OFFLINE?.toBoolean() ?: isOfflineWork serviceDirectoryPath = GradleEnvironment.Headless.GRADLE_SERVICE_DIRECTORY ?: serviceDirectoryPath storeProjectFilesExternally = true } @ApiStatus.Internal fun GradleProjectSettings.setupGradleProjectSettings(project: Project, projectDirectory: Path) { externalProjectPath = projectDirectory.systemIndependentPath isUseQualifiedModuleNames = true distributionType = GradleEnvironment.Headless.GRADLE_DISTRIBUTION_TYPE?.let(DistributionType::valueOf) ?: DistributionType.DEFAULT_WRAPPED gradleHome = GradleEnvironment.Headless.GRADLE_HOME ?: suggestGradleHome(project) } private fun suggestGradleHome(project: Project): String? { val installationManager = ApplicationManager.getApplication().getService(GradleInstallationManager::class.java) val lastUsedGradleHome = GradleUtil.getLastUsedGradleHome().nullize() if (lastUsedGradleHome != null) return lastUsedGradleHome val gradleHome = installationManager.getAutodetectedGradleHome(project) ?: return null return FileUtil.toCanonicalPath(gradleHome.path) } private fun validateGradleProject(projectFilePath: String, project: Project): ValidationInfo? { val systemSettings = ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID) val localFileSystem = LocalFileSystem.getInstance() val projectFile = localFileSystem.refreshAndFindFileByPath(projectFilePath) if (projectFile == null) { val shortPath = FileUtil.getLocationRelativeToUserHome(FileUtil.toSystemDependentName(projectFilePath), false) return ValidationInfo(ExternalSystemBundle.message("error.project.does.not.exist", "Gradle", shortPath)) } val projectDirectory = if (projectFile.isDirectory) projectFile else projectFile.parent val projectSettings = systemSettings.getLinkedProjectSettings(projectDirectory.path) if (projectSettings != null) return ValidationInfo(ExternalSystemBundle.message("error.project.already.registered")) return null }
apache-2.0
96470dfbd542510ce1f3109a7fc52d27
49.93
140
0.830126
4.992157
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/java/findJavaClassUsages/JKNestedClassAllUsages.1.kt
5
596
public class X(bar: String? = Outer.A.BAR): Outer.A() { var next: Outer.A? = Outer.A() val myBar: String? = Outer.A.BAR init { Outer.A.BAR = "" Outer.A.foos() } fun foo(a: Outer.A) { val aa: Outer.A = a aa.bar = "" } fun getNext(): Outer.A? { return next } public override fun foo() { super<Outer.A>.foo() } companion object: Outer.A() { } } object O: Outer.A() { } fun X.bar(a: Outer.A = Outer.A()) { } fun Any.toA(): Outer.A? { return if (this is Outer.A) this as Outer.A else null }
apache-2.0
125dd83453be1a14f776ac2b644292fa
14.710526
57
0.503356
2.893204
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/ChangeTypeQuickFixFactories.kt
3
10259
// 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.fixes import com.intellij.psi.PsiElement import com.intellij.psi.util.parentOfType import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnosticWithPsi import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtPropertySymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithMembers import org.jetbrains.kotlin.analysis.api.symbols.psiSafe import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.api.applicator.HLApplicatorInput import org.jetbrains.kotlin.idea.api.applicator.applicator import org.jetbrains.kotlin.idea.fir.api.fixes.HLApplicatorTargetWithInput import org.jetbrains.kotlin.idea.fir.api.fixes.diagnosticFixFactory import org.jetbrains.kotlin.idea.fir.api.fixes.withInput import org.jetbrains.kotlin.idea.fir.applicators.CallableReturnTypeUpdaterApplicator import org.jetbrains.kotlin.idea.quickfix.ChangeTypeFixUtils import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType object ChangeTypeQuickFixFactories { val applicator = applicator<KtCallableDeclaration, Input> { familyName(CallableReturnTypeUpdaterApplicator.applicator.getFamilyName()) actionName { declaration, (targetType, type) -> val presentation = getPresentation(targetType, declaration) getActionName(declaration, presentation, type) } applyTo { declaration, (_, type), project, editor -> CallableReturnTypeUpdaterApplicator.applicator.applyTo(declaration, type, project, editor) } } private fun getActionName( declaration: KtCallableDeclaration, presentation: String?, typeInfo: CallableReturnTypeUpdaterApplicator.TypeInfo ) = ChangeTypeFixUtils.getTextForQuickFix( declaration, presentation, typeInfo.defaultType.isUnit, typeInfo.defaultType.shortTypeRepresentation ) private fun getPresentation( targetType: TargetType, declaration: KtCallableDeclaration ): String? { return when (targetType) { TargetType.CURRENT_DECLARATION -> null TargetType.BASE_DECLARATION -> KotlinBundle.message( "fix.change.return.type.presentation.base", declaration.presentationForQuickfix ?: return null ) TargetType.ENCLOSING_DECLARATION -> KotlinBundle.message( "fix.change.return.type.presentation.enclosing", declaration.presentationForQuickfix ?: return KotlinBundle.message("fix.change.return.type.presentation.enclosing.function") ) TargetType.CALLED_FUNCTION -> { val presentation = declaration.presentationForQuickfix ?: return KotlinBundle.message("fix.change.return.type.presentation.called.function") when (declaration) { is KtParameter -> KotlinBundle.message("fix.change.return.type.presentation.accessed", presentation) else -> KotlinBundle.message("fix.change.return.type.presentation.called", presentation) } } TargetType.VARIABLE -> return "'${declaration.name}'" } } private val KtCallableDeclaration.presentationForQuickfix: String? get() { val containerName = parentOfType<KtNamedDeclaration>()?.nameAsName?.takeUnless { it.isSpecial } return ChangeTypeFixUtils.functionOrConstructorParameterPresentation(this, containerName?.asString()) } enum class TargetType { CURRENT_DECLARATION, BASE_DECLARATION, ENCLOSING_DECLARATION, CALLED_FUNCTION, VARIABLE, } data class Input( val targetType: TargetType, val typeInfo: CallableReturnTypeUpdaterApplicator.TypeInfo ) : HLApplicatorInput { override fun isValidFor(psi: PsiElement): Boolean = typeInfo.isValidFor(psi) } val changeFunctionReturnTypeOnOverride = changeReturnTypeOnOverride<KtFirDiagnostic.ReturnTypeMismatchOnOverride> { it.function as? KtFunctionSymbol } val changePropertyReturnTypeOnOverride = changeReturnTypeOnOverride<KtFirDiagnostic.PropertyTypeMismatchOnOverride> { it.property as? KtPropertySymbol } val changeVariableReturnTypeOnOverride = changeReturnTypeOnOverride<KtFirDiagnostic.VarTypeMismatchOnOverride> { it.variable as? KtPropertySymbol } val returnTypeMismatch = diagnosticFixFactory(KtFirDiagnostic.ReturnTypeMismatch::class, applicator) { diagnostic -> val function = diagnostic.targetFunction.psi as? KtCallableDeclaration ?: return@diagnosticFixFactory emptyList() listOf(function withInput Input(TargetType.ENCLOSING_DECLARATION, createTypeInfo(diagnostic.actualType))) } @OptIn(ExperimentalStdlibApi::class) val componentFunctionReturnTypeMismatch = diagnosticFixFactory(KtFirDiagnostic.ComponentFunctionReturnTypeMismatch::class, applicator) { diagnostic -> val entryWithWrongType = getDestructuringDeclarationEntryThatTypeMismatchComponentFunction( diagnostic.componentFunctionName, diagnostic.psi ) ?: return@diagnosticFixFactory emptyList() buildList<HLApplicatorTargetWithInput<KtCallableDeclaration, Input>> { add(entryWithWrongType withInput Input(TargetType.VARIABLE, createTypeInfo(diagnostic.destructingType))) val classSymbol = (diagnostic.psi.getKtType() as? KtNonErrorClassType)?.classSymbol as? KtSymbolWithMembers ?: return@buildList val componentFunction = classSymbol.getMemberScope() .getCallableSymbols { it == diagnostic.componentFunctionName } .firstOrNull()?.psi as? KtCallableDeclaration ?: return@buildList add(componentFunction withInput Input(TargetType.CALLED_FUNCTION, createTypeInfo(diagnostic.expectedType))) } } private inline fun <reified DIAGNOSTIC : KtDiagnosticWithPsi<KtNamedDeclaration>> changeReturnTypeOnOverride( crossinline getCallableSymbol: (DIAGNOSTIC) -> KtCallableSymbol? ) = diagnosticFixFactory(DIAGNOSTIC::class, applicator) { diagnostic -> val declaration = diagnostic.psi as? KtCallableDeclaration ?: return@diagnosticFixFactory emptyList() val callable = getCallableSymbol(diagnostic) ?: return@diagnosticFixFactory emptyList() listOfNotNull( createChangeCurrentDeclarationQuickFix(callable, declaration), createChangeOverriddenFunctionQuickFix(callable), ) } private fun <PSI : KtCallableDeclaration> KtAnalysisSession.createChangeCurrentDeclarationQuickFix( callable: KtCallableSymbol, declaration: PSI ): HLApplicatorTargetWithInput<PSI, Input>? { val lowerSuperType = findLowerBoundOfOverriddenCallablesReturnTypes(callable) ?: return null val changeToTypeInfo = createTypeInfo(lowerSuperType) return declaration withInput Input(TargetType.CURRENT_DECLARATION, changeToTypeInfo) } private fun KtAnalysisSession.createChangeOverriddenFunctionQuickFix( callable: KtCallableSymbol ): HLApplicatorTargetWithInput<KtCallableDeclaration, Input>? { val type = callable.returnType val singleNonMatchingOverriddenFunction = findSingleNonMatchingOverriddenFunction(callable, type) ?: return null val singleMatchingOverriddenFunctionPsi = singleNonMatchingOverriddenFunction.psiSafe<KtCallableDeclaration>() ?: return null val changeToTypeInfo = createTypeInfo(type) if (!singleMatchingOverriddenFunctionPsi.isWritable) return null return singleMatchingOverriddenFunctionPsi withInput Input(TargetType.BASE_DECLARATION, changeToTypeInfo) } private fun KtAnalysisSession.findSingleNonMatchingOverriddenFunction( callable: KtCallableSymbol, type: KtType ): KtCallableSymbol? { val overriddenSymbols = callable.getDirectlyOverriddenSymbols() return overriddenSymbols .singleOrNull { overridden -> !type.isSubTypeOf(overridden.returnType) } } private fun KtAnalysisSession.createTypeInfo(ktType: KtType) = with(CallableReturnTypeUpdaterApplicator.TypeInfo) { createByKtTypes(ktType) } private fun KtAnalysisSession.findLowerBoundOfOverriddenCallablesReturnTypes(symbol: KtCallableSymbol): KtType? { var lowestType: KtType? = null for (overridden in symbol.getDirectlyOverriddenSymbols()) { val overriddenType = overridden.returnType when { lowestType == null || overriddenType isSubTypeOf lowestType -> { lowestType = overriddenType } lowestType isNotSubTypeOf overriddenType -> { return null } } } return lowestType } private fun getDestructuringDeclarationEntryThatTypeMismatchComponentFunction( componentName: Name, rhsExpression: KtExpression ): KtDestructuringDeclarationEntry? { val componentIndex = componentName.asString().removePrefix("component").toIntOrNull() ?: return null val destructuringDeclaration = rhsExpression.getParentOfType<KtDestructuringDeclaration>(strict = true) ?: return null return destructuringDeclaration.entries[componentIndex - 1] } }
apache-2.0
593c0135a1e6055edc8bb166ac3f1968
47.164319
158
0.715859
5.667956
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/androidMain/kotlin/androidx/compose/foundation/EdgeEffectCompat.kt
3
5129
/* * 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.compose.foundation import android.content.Context import android.os.Build import android.util.AttributeSet import android.widget.EdgeEffect import androidx.annotation.DoNotInline import androidx.annotation.RequiresApi import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp import kotlin.math.abs internal object EdgeEffectCompat { fun create(context: Context, attrs: AttributeSet?): EdgeEffect { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { Api31Impl.create(context, attrs) } else { GlowEdgeEffectCompat(context) } } fun EdgeEffect.onPullDistanceCompat( deltaDistance: Float, displacement: Float ): Float { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { return Api31Impl.onPullDistance(this, deltaDistance, displacement) } this.onPull(deltaDistance, displacement) return deltaDistance } fun EdgeEffect.onAbsorbCompat(velocity: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { return this.onAbsorb(velocity) } else if (this.isFinished) { // only absorb the glow effect if it is not active (finished) this.onAbsorb(velocity) } } /** * Used for calls to [EdgeEffect.onRelease] that happen because of scroll delta in the opposite * direction to the overscroll. See [GlowEdgeEffectCompat]. */ fun EdgeEffect.onReleaseWithOppositeDelta(delta: Float) { if (this is GlowEdgeEffectCompat) { releaseWithOppositeDelta(delta) } else { onRelease() } } val EdgeEffect.distanceCompat: Float get() { return if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)) { Api31Impl.getDistance(this) } else 0f } } /** * Compat class to work around a framework issue (b/242864658) - small negative deltas that release * an overscroll followed by positive deltas cause the glow overscroll effect to instantly * disappear. This can happen when you pull the overscroll, and keep it there - small fluctuations * in the pointer position can cause these small negative deltas, even though on average it is not * really moving. To workaround this we only release the overscroll if the cumulative negative * deltas are larger than a minimum value - this should catch the majority of cases. */ private class GlowEdgeEffectCompat(context: Context) : EdgeEffect(context) { // Minimum distance in the opposite scroll direction to trigger a release private val oppositeReleaseDeltaThreshold = with(Density(context)) { 1.dp.toPx() } private var oppositeReleaseDelta = 0f override fun onPull(deltaDistance: Float, displacement: Float) { oppositeReleaseDelta = 0f super.onPull(deltaDistance, displacement) } override fun onPull(deltaDistance: Float) { oppositeReleaseDelta = 0f super.onPull(deltaDistance) } override fun onRelease() { oppositeReleaseDelta = 0f super.onRelease() } override fun onAbsorb(velocity: Int) { oppositeReleaseDelta = 0f super.onAbsorb(velocity) } /** * Increments the current cumulative delta, and calls [onRelease] if it is greater than * [oppositeReleaseDeltaThreshold]. */ fun releaseWithOppositeDelta(delta: Float) { oppositeReleaseDelta += delta if (abs(oppositeReleaseDelta) > oppositeReleaseDeltaThreshold) { onRelease() } } } @RequiresApi(Build.VERSION_CODES.S) private object Api31Impl { @DoNotInline fun create(context: Context, attrs: AttributeSet?): EdgeEffect { return try { EdgeEffect(context, attrs) } catch (t: Throwable) { EdgeEffect(context) // Old preview release } } @DoNotInline fun onPullDistance( edgeEffect: EdgeEffect, deltaDistance: Float, displacement: Float ): Float { return try { edgeEffect.onPullDistance(deltaDistance, displacement) } catch (t: Throwable) { edgeEffect.onPull(deltaDistance, displacement) // Old preview release 0f } } @DoNotInline fun getDistance(edgeEffect: EdgeEffect): Float { return try { edgeEffect.getDistance() } catch (t: Throwable) { 0f // Old preview release } } }
apache-2.0
4bd7e849d18ff52437399c379da564a4
31.884615
99
0.668356
4.421552
false
false
false
false
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/DistanceRecord.kt
3
3888
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.health.connect.client.aggregate.AggregateMetric import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.units.Length import androidx.health.connect.client.units.meters import java.time.Instant import java.time.ZoneOffset /** * Captures distance travelled by the user since the last reading. The total distance over an * interval can be calculated by adding together all the values during the interval. The start time * of each record should represent the start of the interval in which the distance was covered. * * If break downs are preferred in scenario of a long workout, consider writing multiple distance * records. The start time of each record should be equal to or greater than the end time of the * previous record. */ public class DistanceRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, /** Distance in [Length] unit. Required field. Valid range: 0-1000000 meters. */ public val distance: Length, override val metadata: Metadata = Metadata.EMPTY, ) : IntervalRecord { init { distance.requireNotLess(other = distance.zero(), name = "distance") distance.requireNotMore(other = MAX_DISTANCE, name = "distance") require(startTime.isBefore(endTime)) { "startTime must be before endTime." } } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is DistanceRecord) return false if (distance != other.distance) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (metadata != other.metadata) return false if (distance.inMeters != other.distance.inMeters) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = distance.hashCode() result = 31 * result + startTime.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() result = 31 * result + distance.inMeters.hashCode() return result } companion object { private val MAX_DISTANCE = 1000_000.meters /** * Metric identifier to retrieve the total distance from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val DISTANCE_TOTAL: AggregateMetric<Length> = AggregateMetric.doubleMetric( dataTypeName = "Distance", aggregationType = AggregateMetric.AggregationType.TOTAL, fieldName = "distance", mapper = Length::meters, ) } }
apache-2.0
f07d13d104426ffe88e7a34830585ac3
38.673469
99
0.679012
4.673077
false
false
false
false
GunoH/intellij-community
platform/core-impl/src/com/intellij/openapi/application/impl/ZenDeskForm.kt
8
1162
// 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.openapi.application.impl import com.intellij.util.xml.dom.XmlElement data class ZenDeskField(val id: Long, val type: String?, val value: String?) { companion object { fun parse(element: XmlElement): ZenDeskField { val id = element.getAttributeValue("id")!!.toLong() val type = element.getAttributeValue("type") val value = element.getAttributeValue("value") return ZenDeskField(id, type, value) } } } class ZenDeskForm(val id: Long, val url: String, val fields: List<ZenDeskField>) { companion object { @JvmStatic fun parse(element: XmlElement): ZenDeskForm { val id = element.getAttributeValue("zendesk-form-id")!!.toLong() val url = element.getAttributeValue("zendesk-url")!! val fields = mutableListOf<ZenDeskField>() for (child in element.children) { if (child.name == "field") { fields.add(ZenDeskField.parse(child)) } } return ZenDeskForm(id, url, fields) } } }
apache-2.0
840717d7fc6388ed23b7b615de79b746
35.3125
158
0.680723
4.04878
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/commit/CommonCheckinFilesAction.kt
2
3012
// 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.openapi.vcs.actions.commit import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.actions.VcsContextUtil import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.vcsUtil.VcsUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls class CommonCheckinFilesAction : DumbAwareAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { CheckinActionUtil.updateCommonCommitAction(e) val project = e.project val presentation = e.presentation if (project != null) { val pathsToCommit = VcsContextUtil.selectedFilePaths(e.dataContext) presentation.text = getActionName(project, pathsToCommit) + StringUtil.ELLIPSIS presentation.isEnabled = presentation.isEnabled && pathsToCommit.any { isActionEnabled(project, it) } } } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val pathsToCommit = VcsContextUtil.selectedFilePaths(e.dataContext) val initialChangeList = CheckinActionUtil.getInitiallySelectedChangeListFor(project, pathsToCommit) val actionName = getActionName(project, pathsToCommit) CheckinActionUtil.performCommonCommitAction(e, project, initialChangeList, pathsToCommit, actionName, null, true) } companion object { @ApiStatus.Internal fun getActionName(project: Project, pathsToCommit: List<FilePath>): @NlsActions.ActionText String { val commonVcs = pathsToCommit.mapNotNull { VcsUtil.getVcsFor(project, it) }.distinct().singleOrNull() val operationName = commonVcs?.checkinEnvironment?.checkinOperationName return appendSubject(pathsToCommit, operationName ?: VcsBundle.message("vcs.command.name.checkin")) } private fun appendSubject(roots: List<FilePath>, checkinActionName: @Nls String): @NlsActions.ActionText String { if (roots.isEmpty()) return checkinActionName if (roots[0].isDirectory) { return VcsBundle.message("action.name.checkin.directory", checkinActionName, roots.size) } else { return VcsBundle.message("action.name.checkin.file", checkinActionName, roots.size) } } @ApiStatus.Internal fun isActionEnabled(project: Project, path: FilePath): Boolean { val status = ChangeListManager.getInstance(project).getStatus(path) return (path.isDirectory || status != FileStatus.NOT_CHANGED) && status != FileStatus.IGNORED } } }
apache-2.0
f9f3f2686d2bb245c855c162e9f7548a
42.028571
120
0.771912
4.591463
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/eval4j/src/org/jetbrains/eval4j/members.kt
4
2267
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.eval4j import org.jetbrains.org.objectweb.asm.Opcodes.* import org.jetbrains.org.objectweb.asm.Type import org.jetbrains.org.objectweb.asm.tree.FieldInsnNode import org.jetbrains.org.objectweb.asm.tree.MethodInsnNode open class MemberDescription protected constructor( val ownerInternalName: String, val name: String, val desc: String, val isStatic: Boolean ) { override fun equals(other: Any?): Boolean { if (this === other) return true return (other is MemberDescription && ownerInternalName == other.ownerInternalName && name == other.name && desc == other.desc && isStatic == other.isStatic ) } override fun hashCode(): Int { var result = 13 result = result * 23 + ownerInternalName.hashCode() result = result * 23 + name.hashCode() result = result * 23 + desc.hashCode() result = result * 23 + isStatic.hashCode() return result } override fun toString() = "MemberDescription(ownerInternalName = $ownerInternalName, name = $name, desc = $desc, isStatic = $isStatic)" } val MemberDescription.ownerType: Type get() = Type.getObjectType(ownerInternalName) class MethodDescription( ownerInternalName: String, name: String, desc: String, isStatic: Boolean ) : MemberDescription(ownerInternalName, name, desc, isStatic) { constructor(insn: MethodInsnNode) : this(insn.owner, insn.name, insn.desc, insn.opcode == INVOKESTATIC) } val MethodDescription.returnType: Type get() = Type.getReturnType(desc) val MethodDescription.parameterTypes: List<Type> get() = Type.getArgumentTypes(desc).toList() class FieldDescription( ownerInternalName: String, name: String, desc: String, isStatic: Boolean ) : MemberDescription(ownerInternalName, name, desc, isStatic) { constructor(insn: FieldInsnNode) : this(insn.owner, insn.name, insn.desc, insn.opcode in setOf(GETSTATIC, PUTSTATIC)) } val FieldDescription.fieldType: Type get() = Type.getType(desc)
apache-2.0
7bc495d3bbaaf2645e525718e9d97344
32.835821
158
0.689457
4.285444
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinReferencesSearcher.kt
2
22988
// 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.search.ideaExtensions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.QueryExecutorBase import com.intellij.openapi.application.ReadAction import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.impl.cache.CacheManager import com.intellij.psi.search.* import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.Processor import com.intellij.util.concurrency.annotations.RequiresReadLock import com.intellij.util.containers.nullize import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.LightClassUtil.getLightClassMethods import org.jetbrains.kotlin.asJava.LightClassUtil.getLightClassPropertyMethods import org.jetbrains.kotlin.asJava.LightClassUtil.getLightFieldForCompanionObject import org.jetbrains.kotlin.asJava.elements.KtLightField import org.jetbrains.kotlin.asJava.elements.KtLightMember import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.elements.KtLightParameter import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.sourcesAndLibraries import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.dataClassComponentMethodName import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.expectedDeclarationIfAny import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.filterDataClassComponentsIfDisabled import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isExpectDeclaration import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.* import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions.Companion.Empty import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions.Companion.calculateEffectiveScope import org.jetbrains.kotlin.idea.search.usagesSearch.operators.OperatorReferenceSearcher import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.ifTrue import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.concurrent.Callable data class KotlinReferencesSearchOptions( val acceptCallableOverrides: Boolean = false, val acceptOverloads: Boolean = false, val acceptExtensionsOfDeclarationClass: Boolean = false, val acceptCompanionObjectMembers: Boolean = false, val acceptImportAlias: Boolean = true, val searchForComponentConventions: Boolean = true, val searchForOperatorConventions: Boolean = true, val searchNamedArguments: Boolean = true, val searchForExpectedUsages: Boolean = true ) { fun anyEnabled(): Boolean = acceptCallableOverrides || acceptOverloads || acceptExtensionsOfDeclarationClass companion object { val Empty = KotlinReferencesSearchOptions() internal fun calculateEffectiveScope( elementToSearch: PsiNamedElement, parameters: ReferencesSearch.SearchParameters ): SearchScope { val kotlinOptions = (parameters as? KotlinAwareReferencesSearchParameters)?.kotlinOptions ?: Empty val elements = if (elementToSearch is KtDeclaration && !isOnlyKotlinSearch(parameters.scopeDeterminedByUser)) { elementToSearch.toLightElements().filterDataClassComponentsIfDisabled(kotlinOptions).nullize() } else { null } ?: listOf(elementToSearch) return elements.fold(parameters.effectiveSearchScope) { scope, e -> scope.unionSafe(parameters.effectiveSearchScope(e)) } } } } interface KotlinAwareReferencesSearchParameters { val kotlinOptions: KotlinReferencesSearchOptions } class KotlinReferencesSearchParameters( elementToSearch: PsiElement, scope: SearchScope = runReadAction { elementToSearch.project.allScope() }, ignoreAccessScope: Boolean = false, optimizer: SearchRequestCollector? = null, override val kotlinOptions: KotlinReferencesSearchOptions = Empty ) : ReferencesSearch.SearchParameters(elementToSearch, scope, ignoreAccessScope, optimizer), KotlinAwareReferencesSearchParameters class KotlinMethodReferencesSearchParameters( elementToSearch: PsiMethod, scope: SearchScope = runReadAction { elementToSearch.project.allScope() }, strictSignatureSearch: Boolean = true, override val kotlinOptions: KotlinReferencesSearchOptions = Empty ) : MethodReferencesSearch.SearchParameters(elementToSearch, scope, strictSignatureSearch), KotlinAwareReferencesSearchParameters class KotlinAliasedImportedElementSearcher : QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters>() { override fun processQuery(parameters: ReferencesSearch.SearchParameters, consumer: Processor<in PsiReference?>) { val kotlinOptions = (parameters as? KotlinAwareReferencesSearchParameters)?.kotlinOptions ?: Empty if (!kotlinOptions.acceptImportAlias) return val queryFunction = ReadAction.nonBlocking(Callable { val element = parameters.elementToSearch if (!element.isValid) return@Callable null val unwrappedElement = element.namedUnwrappedElement ?: return@Callable null val name = unwrappedElement.name if (name == null || StringUtil.isEmptyOrSpaces(name)) return@Callable null val effectiveSearchScope = calculateEffectiveScope(unwrappedElement, parameters) val collector = parameters.optimizer val session = collector.searchSession val function = { collector.searchWord( name, effectiveSearchScope, UsageSearchContext.IN_CODE, true, element, AliasProcessor(element, session) ) } function }).inSmartMode(parameters.project) .executeSynchronously() queryFunction?.invoke() } private class AliasProcessor( private val myTarget: PsiElement, private val mySession: SearchSession ) : RequestResultProcessor(myTarget) { override fun processTextOccurrence(element: PsiElement, offsetInElement: Int, consumer: Processor<in PsiReference>): Boolean { val importStatement = element.parent as? KtImportDirective ?: return true val importAlias = importStatement.alias?.name ?: return true val reference = importStatement.importedReference?.getQualifiedElementSelector()?.mainReference ?: return true if (!reference.isReferenceTo(myTarget)) { return true } val collector = SearchRequestCollector(mySession) val fileScope: SearchScope = LocalSearchScope(element.containingFile) collector.searchWord(importAlias, fileScope, UsageSearchContext.IN_CODE, true, myTarget) return PsiSearchHelper.getInstance(element.project).processRequests(collector, consumer) } } } class KotlinReferencesSearcher : QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters>() { override fun processQuery(queryParameters: ReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) { val processor = QueryProcessor(queryParameters, consumer) processor.process() processor.executeLongRunningTasks() } private class QueryProcessor(val queryParameters: ReferencesSearch.SearchParameters, val consumer: Processor<in PsiReference>) { private val kotlinOptions = queryParameters.safeAs<KotlinAwareReferencesSearchParameters>()?.kotlinOptions ?: Empty private val longTasks = mutableListOf<() -> Unit>() fun executeLongRunningTasks() { longTasks.forEach { ProgressManager.checkCanceled() it() } } fun process() { var element: SmartPsiElementPointer<PsiElement>? = null var classNameForCompanionObject: String? = null val (elementToSearchPointer: SmartPsiElementPointer<PsiNamedElement>, effectiveSearchScope) = ReadAction.nonBlocking(Callable { val psiElement = queryParameters.elementToSearch if (!psiElement.isValid) return@Callable null val unwrappedElement = psiElement.namedUnwrappedElement ?: return@Callable null val elementToSearch = if (kotlinOptions.searchForExpectedUsages && unwrappedElement is KtDeclaration && unwrappedElement.hasActualModifier()) { unwrappedElement.expectedDeclarationIfAny() as? PsiNamedElement } else { null } ?: unwrappedElement val effectiveSearchScope = calculateEffectiveScope(elementToSearch, queryParameters) element = SmartPointerManager.createPointer(psiElement) classNameForCompanionObject = elementToSearch.getClassNameForCompanionObject() SmartPointerManager.createPointer(elementToSearch) to effectiveSearchScope }).inSmartMode(queryParameters.project) .executeSynchronously() ?: return runReadAction { element?.element } ?: return runReadAction { elementToSearchPointer.element?.let { elementToSearch -> val refFilter: (PsiReference) -> Boolean = when (elementToSearch) { is KtParameter -> ({ ref: PsiReference -> !ref.isNamedArgumentReference()/* they are processed later*/ }) else -> ({ true }) } val resultProcessor = KotlinRequestResultProcessor(elementToSearch, filter = refFilter, options = kotlinOptions) if (kotlinOptions.anyEnabled() || elementToSearch is KtNamedDeclaration && elementToSearch.isExpectDeclaration()) { elementToSearch.name?.let { name -> longTasks.add { // Check difference with default scope runReadAction { elementToSearchPointer.element }?.let { elementToSearch -> queryParameters.optimizer.searchWord( name, effectiveSearchScope, UsageSearchContext.IN_CODE, true, elementToSearch, resultProcessor ) } } } } classNameForCompanionObject?.let { name -> longTasks.add { runReadAction { elementToSearchPointer.element }?.let { elementToSearch -> queryParameters.optimizer.searchWord( name, effectiveSearchScope, UsageSearchContext.ANY, true, elementToSearch, resultProcessor ) } } } } if (elementToSearchPointer.element is KtParameter && kotlinOptions.searchNamedArguments) { longTasks.add { ReadAction.nonBlocking(Callable { elementToSearchPointer.element.safeAs<KtParameter>()?.let(::searchNamedArguments) }).executeSynchronously() } } if (!(elementToSearchPointer.element is KtElement && runReadAction { isOnlyKotlinSearch(effectiveSearchScope) })) { longTasks.add { ReadAction.nonBlocking(Callable { element?.element?.let(::searchLightElements) }).executeSynchronously() } } element?.element?.takeIf { it is KtFunction || it is PsiMethod }?.let { _ -> element?.element?.let { OperatorReferenceSearcher.create( it, effectiveSearchScope, consumer, queryParameters.optimizer, kotlinOptions ) } ?.let { searcher -> longTasks.add { searcher.run() } } } } if (kotlinOptions.searchForComponentConventions) { element?.let(::searchForComponentConventions) } } private fun PsiNamedElement.getClassNameForCompanionObject(): String? = (this is KtObjectDeclaration && this.isCompanion()) .ifTrue { getNonStrictParentOfType<KtClass>()?.name } private fun searchNamedArguments(parameter: KtParameter) { val parameterName = parameter.name ?: return val function = parameter.ownerFunction as? KtFunction ?: return if (function.nameAsName?.isSpecial != false) return val project = function.project var namedArgsScope = function.useScope.intersectWith(queryParameters.scopeDeterminedByUser) if (namedArgsScope is GlobalSearchScope) { namedArgsScope = sourcesAndLibraries(namedArgsScope, project) val filesWithFunctionName = CacheManager.getInstance(project).getVirtualFilesWithWord( function.name!!, UsageSearchContext.IN_CODE, namedArgsScope, true ) namedArgsScope = GlobalSearchScope.filesScope(project, filesWithFunctionName.asList()) } val processor = KotlinRequestResultProcessor(parameter, filter = { it.isNamedArgumentReference() }) queryParameters.optimizer.searchWord( parameterName, namedArgsScope, KOTLIN_NAMED_ARGUMENT_SEARCH_CONTEXT, true, parameter, processor ) } @RequiresReadLock private fun searchLightElements(element: PsiElement) { when (element) { is KtClassOrObject -> { processKtClassOrObject(element) } is KtNamedFunction, is KtSecondaryConstructor -> { (element as KtFunction).name?.let { getLightClassMethods(element).forEach(::searchNamedElement) } processStaticsFromCompanionObject(element) } is KtProperty -> { val propertyDeclarations = getLightClassPropertyMethods(element).allDeclarations propertyDeclarations.forEach(::searchNamedElement) processStaticsFromCompanionObject(element) } is KtParameter -> { searchPropertyAccessorMethods(element) if (element.getStrictParentOfType<KtPrimaryConstructor>() != null) { // Simple parameters without val and var shouldn't be processed here because of local search scope val parameterDeclarations = getLightClassPropertyMethods(element).allDeclarations parameterDeclarations.filterDataClassComponentsIfDisabled(kotlinOptions).forEach(::searchNamedElement) } } is KtLightMethod -> { val declaration = element.kotlinOrigin if (declaration is KtProperty || (declaration is KtParameter && declaration.hasValOrVar())) { searchNamedElement(declaration as PsiNamedElement) processStaticsFromCompanionObject(declaration) } else if (declaration is KtPropertyAccessor) { val property = declaration.getStrictParentOfType<KtProperty>() searchNamedElement(property) } else if (declaration is KtFunction) { processStaticsFromCompanionObject(declaration) if (element.isMangled) { searchNamedElement(declaration) { it.restrictToKotlinSources() } } } } is KtLightParameter -> { val origin = element.kotlinOrigin ?: return searchPropertyAccessorMethods(origin) } } } @RequiresReadLock private fun searchPropertyAccessorMethods(origin: KtParameter) { origin.toLightElements().filterDataClassComponentsIfDisabled(kotlinOptions).forEach(::searchNamedElement) } @RequiresReadLock private fun processKtClassOrObject(element: KtClassOrObject) { val className = element.name ?: return val lightClass = element.toLightClass() ?: return searchNamedElement(lightClass, className) if (element is KtObjectDeclaration && element.isCompanion()) { getLightFieldForCompanionObject(element)?.let(::searchNamedElement) if (kotlinOptions.acceptCompanionObjectMembers) { val originLightClass = element.getStrictParentOfType<KtClass>()?.toLightClass() if (originLightClass != null) { val lightDeclarations: List<KtLightMember<*>?> = originLightClass.methods.map { it as? KtLightMethod } + originLightClass.fields.map { it as? KtLightField } for (declaration in element.declarations) { lightDeclarations .firstOrNull { it?.kotlinOrigin == declaration } ?.let(::searchNamedElement) } } } } } private fun searchForComponentConventions(elementPointer: SmartPsiElementPointer<PsiElement>) { ReadAction.nonBlocking(Callable { when (val element = elementPointer.element) { is KtParameter -> { val componentMethodName = element.dataClassComponentMethodName ?: return@Callable val containingClass = element.getStrictParentOfType<KtClassOrObject>()?.toLightClass() ?: return@Callable searchDataClassComponentUsages( containingClass = containingClass, componentMethodName = componentMethodName, kotlinOptions = kotlinOptions ) } is KtLightParameter -> { val componentMethodName = element.kotlinOrigin?.dataClassComponentMethodName ?: return@Callable val containingClass = element.method.containingClass ?: return@Callable searchDataClassComponentUsages( containingClass = containingClass, componentMethodName = componentMethodName, kotlinOptions = kotlinOptions ) } else -> return@Callable } }).executeSynchronously() } @RequiresReadLock private fun searchDataClassComponentUsages( containingClass: KtLightClass, componentMethodName: String, kotlinOptions: KotlinReferencesSearchOptions ) { assertReadAccessAllowed() containingClass.methods.firstOrNull { it.name == componentMethodName && it.parameterList.parametersCount == 0 }?.let { searchNamedElement(it) OperatorReferenceSearcher.create( it, queryParameters.effectiveSearchScope, consumer, queryParameters.optimizer, kotlinOptions )?.let { searcher -> longTasks.add { searcher.run() } } } } @RequiresReadLock private fun processStaticsFromCompanionObject(element: KtDeclaration) { findStaticMethodsFromCompanionObject(element).forEach(::searchNamedElement) } private fun findStaticMethodsFromCompanionObject(declaration: KtDeclaration): List<PsiMethod> { val originObject = declaration.parents .dropWhile { it is KtClassBody } .firstOrNull() as? KtObjectDeclaration ?: return emptyList() if (!originObject.isCompanion()) return emptyList() val originClass = originObject.getStrictParentOfType<KtClass>() val originLightClass = originClass?.toLightClass() ?: return emptyList() val allMethods = originLightClass.allMethods return allMethods.filter { it is KtLightMethod && it.kotlinOrigin == declaration } } @RequiresReadLock private fun searchNamedElement( element: PsiNamedElement?, name: String? = null, modifyScope: ((SearchScope) -> SearchScope)? = null ) { assertReadAccessAllowed() element ?: return val nameToUse = name ?: element.name ?: return val baseScope = queryParameters.effectiveSearchScope(element) val scope = if (modifyScope != null) modifyScope(baseScope) else baseScope val context = UsageSearchContext.IN_CODE + UsageSearchContext.IN_FOREIGN_LANGUAGES + UsageSearchContext.IN_COMMENTS val resultProcessor = KotlinRequestResultProcessor( element, queryParameters.elementToSearch.namedUnwrappedElement ?: element, options = kotlinOptions ) queryParameters.optimizer.searchWord(nameToUse, scope, context.toShort(), true, element, resultProcessor) } private fun assertReadAccessAllowed() { ApplicationManager.getApplication().assertReadAccessAllowed() } private fun PsiReference.isNamedArgumentReference(): Boolean { return this is KtSimpleNameReference && expression.parent is KtValueArgumentName } } }
apache-2.0
041c5dcc55c3b5dc3e7121348ccdca0b
47.910638
158
0.636985
6.448247
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/HashUtils.kt
2
1742
/* * Copyright 2010-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.kotlin.backend.konan.llvm import kotlinx.cinterop.* import org.jetbrains.kotlin.backend.konan.hash.* internal fun localHash(data: ByteArray): Long { memScoped { val res = alloc<LocalHashVar>() val bytes = allocArrayOf(data) MakeLocalHash(bytes, data.size, res.ptr) return res.value } } internal fun globalHash(data: ByteArray, retValPlacement: NativePlacement): GlobalHash { val res = retValPlacement.alloc<GlobalHash>() memScoped { val bytes = allocArrayOf(data) MakeGlobalHash(bytes, data.size, res.ptr) } return res } public fun base64Encode(data: ByteArray): String { memScoped { val resultSize = 4 * data.size / 3 + 3 + 1 val result = allocArray<ByteVar>(resultSize) val bytes = allocArrayOf(data) EncodeBase64(bytes, data.size, result, resultSize) // TODO: any better way to do that without two copies? return result.toKString() } } public fun base64Decode(encoded: String): ByteArray { memScoped { val bufferSize: Int = 3 * encoded.length / 4 val result = allocArray<ByteVar>(bufferSize) val resultSize = allocArray<uint32_tVar>(1) resultSize[0] = bufferSize val errorCode = DecodeBase64(encoded, encoded.length, result, resultSize) if (errorCode != 0) throw Error("Non-zero exit code of DecodeBase64: ${errorCode}") val realSize = resultSize[0] return result.readBytes(realSize) } } internal class LocalHash(val value: Long) : ConstValue by Int64(value)
apache-2.0
d02ee2172d5218bcdaaaa79688085d86
31.867925
101
0.672216
3.923423
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/typealiasExpansionIndex/functionalTypes.kt
13
454
typealias TA = () -> Unit // CONTAINS (key="Function0", value="TA") typealias TB = () -> String // CONTAINS (key="Function0", value="TB") typealias TC = (String) -> Unit // CONTAINS (key="Function1", value="TC") typealias TD = String.() -> Unit // CONTAINS (key="Function1", value="TD") typealias TE = (String, String) -> Unit // CONTAINS (key="Function2", value="TE") typealias TF = String.(String) -> Unit // CONTAINS (key="Function2", value="TF")
apache-2.0
1ad097d4cf502ff599d3dd46231aed7d
25.764706
41
0.638767
3.219858
false
false
true
false
smmribeiro/intellij-community
platform/platform-api/src/com/intellij/openapi/ui/MessageUtil.kt
9
1730
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("MessageUtil") package com.intellij.openapi.ui import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts.* import javax.swing.Icon fun showYesNoDialog(@DialogTitle title: String, @DialogMessage message: String, project: Project?, @Button yesText: String = Messages.getYesButton(), @Button noText: String = Messages.getNoButton(), icon: Icon? = null): Boolean { return Messages.showYesNoDialog(project, message, title, yesText, noText, icon) == Messages.YES } fun showOkNoDialog(@DialogTitle title: String, @DialogMessage message: String, project: Project?, @Button okText: String = Messages.getOkButton(), @Button noText: String = Messages.getNoButton(), icon: Icon? = null): Boolean { return Messages.showYesNoDialog(project, message, title, okText, noText, icon) == Messages.YES } @Messages.OkCancelResult fun showOkCancelDialog(@DialogTitle title: String, @DialogMessage message: String, @Button okText: String, @Button cancelText: String = Messages.getCancelButton(), icon: Icon? = null, doNotAskOption: DialogWrapper.DoNotAskOption? = null, project: Project? = null): Int { return Messages.showOkCancelDialog(project, message, title, okText, cancelText, icon, doNotAskOption) }
apache-2.0
95477fb8e3df8add329b4dfb63fb3c27
47.055556
158
0.62659
4.95702
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassNonConstructorUsages.1.kt
9
671
package client import server.Server class Client(name: String = Server.NAME) : Server() { var nextServer: Server? = Server() val name = Server.NAME fun foo(s: Server) { val server: Server = s println("Server: $server") } fun getNextServer2(): Server? { return nextServer } override fun work() { super<Server>.work() println("Client") } } object ClientObject : Server() { } fun Client.bar(s: Server = Server()) { foo(s) } fun Client.hasNextServer(): Boolean { return getNextServer2() != null } fun Any.asServer(): Server? { return if (this is Server) this as Server else null }
apache-2.0
ba31e09fef9f4591912e4c1b3e3e08ab
16.657895
55
0.605067
3.646739
false
false
false
false
smmribeiro/intellij-community
java/java-impl/src/com/intellij/refactoring/migration/MigrationDialogUi.kt
7
2035
// 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.refactoring.migration import com.intellij.application.options.ModulesComboBox import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.ui.components.ActionLink import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.DEFAULT_COMMENT_WIDTH import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.util.ui.JBUI import javax.swing.JComponent import javax.swing.JEditorPane import javax.swing.JLabel class MigrationDialogUi(map: MigrationMap?) { val predefined = if (map == null) false else MigrationMapSet.isPredefined(map.fileName) lateinit var nameLabel: JLabel var removeLink: ActionLink? = null lateinit var editLink: ActionLink lateinit var descriptionLabel: JEditorPane lateinit var modulesCombo: ModulesComboBox val panel = panel { row { nameLabel = label(map?.name ?: "") .resizableColumn() .component if (!predefined) { removeLink = link(JavaRefactoringBundle.message("migration.dialog.link.delete")) {} .component } editLink = link(JavaRefactoringBundle.message(if (predefined) "migration.dialog.link.duplicate" else "migration.dialog.link.edit")) {} .component } row(JavaRefactoringBundle.message("migration.dialog.scope.label")) { modulesCombo = cell(ModulesComboBox()) .applyToComponent { setMinimumAndPreferredWidth(JBUI.scale(380)) } .horizontalAlign(HorizontalAlign.FILL) .component bottomGap(BottomGap.SMALL) } row { descriptionLabel = text(map?.description ?: "", DEFAULT_COMMENT_WIDTH) .component } } fun preferredFocusedComponent(): JComponent = editLink fun update(map: MigrationMap) { nameLabel.text = map.name descriptionLabel.text = map.description } }
apache-2.0
28ebca1178e6295d0a43fa4c44a9d14d
33.508475
158
0.736118
4.385776
false
false
false
false
smmribeiro/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/completion/PythonBasicCompletionLesson.kt
12
1491
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift.lesson.completion import training.dsl.parseLessonSample import training.learn.lesson.general.completion.BasicCompletionLessonBase private const val keyToComplete1 = "director" private const val keyToComplete2 = "distributor" class PythonBasicCompletionLesson : BasicCompletionLessonBase() { override val sample1 = parseLessonSample(""" movies_dict = { 'title': 'Aviator', 'year': '2005', 'demo': False, 'director': 'Martin Scorsese', 'distributor': 'Miramax Films' } def $keyToComplete1(): return movies_dict[<caret>] """.trimIndent()) override val sample2 = parseLessonSample(""" movies_dict = { 'title': 'Aviator', 'year': '2005', 'demo': False, 'director': 'Martin Scorsese', 'distributor': 'Miramax Films' } def $keyToComplete1(): return movies_dict['$keyToComplete1'] def $keyToComplete2(): return movies_dict['<caret>'] """.trimIndent()) override val item1StartToType = "'dir" override val item1CompletionPrefix = "'$keyToComplete1" override val item1CompletionSuffix = "'" override val item2Completion = "'$keyToComplete2'" override val item2Inserted = keyToComplete2 //override val existedFile = PythonLangSupport.sandboxFile }
apache-2.0
fbab79ea955c52c93758901ba586be1f
28.235294
140
0.673374
4.235795
false
false
false
false
80998062/Fank
domain/src/main/java/com/sinyuk/fanfou/domain/DO/Photos.kt
1
2671
/* * * * 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.domain.DO import android.arch.persistence.room.Ignore import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.SerializedName /** * Created by sinyuk on 2017/11/30. */ data class Photos constructor( @SerializedName("url") var url: String? = null, @SerializedName("imageurl") var imageurl: String? = null, @SerializedName("thumburl") var thumburl: String? = null, @SerializedName("largeurl") var largeurl: String? = null, @Ignore var hasFadedIn: Boolean = false ) : Parcelable { private fun validUrl() = when { largeurl != null -> largeurl thumburl != null -> thumburl else -> imageurl } fun size(size: Int? = null) = when { validUrl() == null -> null isAnimated(validUrl()) == true -> validUrl() else -> { val origin = validUrl()!!.split("@")[0] size?.let { origin + "@" + it + "w_1l.jpg" } origin } } constructor(source: Parcel) : this( source.readString(), source.readString(), source.readString(), source.readString(), 1 == source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(url) writeString(imageurl) writeString(thumburl) writeString(largeurl) writeInt((if (hasFadedIn) 1 else 0)) } companion object { @JvmField val CREATOR: Parcelable.Creator<Photos> = object : Parcelable.Creator<Photos> { override fun createFromParcel(source: Parcel): Photos = Photos(source) override fun newArray(size: Int): Array<Photos?> = arrayOfNulls(size) } fun isAnimated(url: String?) = url?.contains("gif", false) const val LARGE_SIZE = 200f const val SMALL_SIZE = 100f } }
mit
c14b23665c4a722cd10161c0a6049608
26.833333
87
0.604268
4.096626
false
false
false
false
android/sunflower
app/src/main/java/com/google/samples/apps/sunflower/compose/Dimens.kt
1
1577
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower.compose import androidx.compose.runtime.Composable import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.google.samples.apps.sunflower.R /** * Class that captures dimens used in Compose code. The dimens that need to be consistent with the * View system use [dimensionResource] and are marked as composable. * * Disclaimer: * This approach doesn't consider multiple configurations. For that, an Ambient should be created. */ object Dimens { val PaddingSmall: Dp @Composable get() = dimensionResource(R.dimen.margin_small) val PaddingNormal: Dp @Composable get() = dimensionResource(R.dimen.margin_normal) val PaddingLarge: Dp = 24.dp val PlantDetailAppBarHeight: Dp @Composable get() = dimensionResource(R.dimen.plant_detail_app_bar_height) val ToolbarIconPadding = 12.dp val ToolbarIconSize = 32.dp }
apache-2.0
4b365ba52b963dfa121a2a4ef4a7ca08
31.854167
98
0.745086
4.117493
false
false
false
false
spring-gradle-plugins/rewrite-gradle
src/main/kotlin/io/spring/rewrite/gradle/RewriteScanner.kt
1
2920
/** * Copyright 2017 Pivotal Software, 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 io.spring.rewrite.gradle; import com.netflix.rewrite.auto.AutoRewrite import com.netflix.rewrite.refactor.Refactor import eu.infomas.annotation.AnnotationDetector import org.slf4j.LoggerFactory import java.io.File import java.lang.reflect.Modifier import java.net.URLClassLoader class RewriteScanner(classpath: Iterable<File>) { private val logger = LoggerFactory.getLogger(RewriteScanner::class.java) val filteredClasspath = classpath.filter { val fn = it.name.toString() if(it.isDirectory) true else if(fn.endsWith(".class")) true else fn.endsWith(".jar") && !fn.endsWith("-javadoc.jar") && !fn.endsWith("-sources.jar") } fun rewriteRunnersOnClasspath(): Collection<AutoRewriteRunner> { val scanners = mutableListOf<AutoRewriteRunner>() val classLoader = URLClassLoader(filteredClasspath.map { it.toURI().toURL() }.toTypedArray(), this::class.java.classLoader) val reporter = object: AnnotationDetector.MethodReporter { override fun annotations() = arrayOf(AutoRewrite::class.java) override fun reportMethodAnnotation(annotation: Class<out Annotation>?, className: String?, methodName: String?) { val clazz = Class.forName(className, true, classLoader) scanners.addAll(clazz.methods.filter { it.name == methodName && it.isAnnotationPresent(AutoRewrite::class.java) } .filter { method -> if(method == null || !Modifier.isStatic(method.modifiers) || method.parameterTypes.run { size != 1 || this[0] != Refactor::class.java }) { logger.warn("$className.$methodName will be ignored. To be useable, an @AutoRewrite method must be static and take a single Refactor argument.") false } else true } .map { method -> AutoRewriteRunner(method.getAnnotation(AutoRewrite::class.java)) { r: Refactor -> method.invoke(clazz, r) } }) } } AnnotationDetector(reporter).detect(*filteredClasspath.map { it }.toTypedArray()) return scanners } }
apache-2.0
5fb217b4c3ad0325970a21fff78d4473
45.365079
176
0.640068
4.709677
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/overlay/transparency/win10/AccentPolicy.kt
1
1208
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.overlay.transparency.win10 import com.sun.jna.Structure class AccentPolicy : Structure(), Structure.ByReference { @JvmField var AccentState: Int = 0 @JvmField var AccentFlags: Int = 0 @JvmField var GradientColor: Int = 0 @JvmField var AnimationId: Int = 0 override fun getFieldOrder() = listOf("AccentState", "AccentFlags", "GradientColor", "AnimationId") }
agpl-3.0
e6ec70e0311fecf4f3711536f5e5bee8
30
100
0.736755
3.859425
false
false
false
false
myunusov/maxur-mserv
maxur-mserv-core/src/test/kotlin/org/maxur/mserv/frame/service/properties/PropertiesHoconImplSpec.kt
1
3336
package org.maxur.mserv.frame.service.properties import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.junit.platform.runner.JUnitPlatform import org.junit.runner.RunWith import org.maxur.mserv.frame.LocatorImpl import org.maxur.mserv.frame.TestLocatorHolder import java.net.URI import java.net.URL import java.time.Duration import java.time.temporal.ChronoUnit import kotlin.test.assertFailsWith @RunWith(JUnitPlatform::class) class PropertiesHoconImplSpec : Spek({ describe("a Properties Source as Hocon File") { beforeEachTest { LocatorImpl.holder = TestLocatorHolder } context("Load properties source by url") { it("should return opened source with url by default") { val sut = PropertiesSourceHoconImpl() assertThat(sut).isNotNull() assertThat(sut.format).isEqualTo("Hocon") assertThat(sut.uri.toString()).endsWith("application.conf") } it("should return opened source with classpath url") { val sut = PropertiesSourceHoconImpl(URI("classpath://application.conf")) assertThat(sut).isNotNull() assertThat(sut.format).isEqualTo("Hocon") assertThat(sut.uri.toString()).endsWith("application.conf") } it("should return opened source with url by default") { val path = PropertiesHoconImplSpec::class.java.getResource("/application.conf").path val sut = PropertiesSourceHoconImpl(URL(path).toURI()) assertThat(sut).isNotNull() assertThat(sut.format).isEqualTo("Hocon") assertThat(sut.uri.toString()).endsWith("application.conf") } } context("Load properties source from file") { val sut = PropertiesSourceHoconImpl() it("should return value of properties by it's key") { assertThat(sut.asString("name")).isEqualTo("μService") assertThat(sut.read("name", String::class)).isEqualTo("μService") assertThat(sut.asInteger("id")).isEqualTo(1) assertThat(sut.read("id", Integer::class)).isEqualTo(1) assertThat(sut.asLong("id")).isEqualTo(1L) assertThat(sut.read("id", Long::class)).isEqualTo(1L) assertThat(sut.asURI("url")).isEqualTo(URI("file:///file.txt")) assertThat(sut.read("url", URI::class)).isEqualTo(URI("file:///file.txt")) assertThat(sut.read("id", Double::class)).isEqualTo(1.0) assertThat(sut.read("time", Duration::class)).isEqualTo(Duration.of(1, ChronoUnit.SECONDS)) } it("should throw exception when properties is not found") { assertFailsWith<IllegalStateException> { sut.asInteger("error") } } it("should throw exception when properties is not parsed") { assertFailsWith<IllegalStateException> { sut.read("id", PropertiesSourceHoconImpl::class) } } } } })
apache-2.0
715b53a86583d24fbe80b8a254d004b9
43.466667
107
0.615477
4.72238
false
true
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/ctrl/PspController.kt
1
2894
package com.soywiz.kpspemu.ctrl import com.soywiz.kmem.* import com.soywiz.kpspemu.* import com.soywiz.kpspemu.util.* class PspController(override val emulator: Emulator) : WithEmulator { var samplingCycle: Int = 0 var samplingMode: Int = 0 val frames = (0 until 0x10).map { Frame() } var frameIndex = 0 fun getFrame(offset: Int): Frame = frames[(frameIndex + offset) umod frames.size] val lastLatchData = Frame() data class Frame(var timestamp: Int = 0, var buttons: Int = 0, var lx: Int = 128, var ly: Int = 128) { fun setTo(other: Frame) { this.buttons = other.buttons this.lx = other.lx this.ly = other.ly } //fun press(button: PspCtrlButtons) { // buttons = buttons or button.bits //} // //fun release(button: PspCtrlButtons) { // buttons = buttons and button.bits.inv() //} // //fun update(button: PspCtrlButtons, pressed: Boolean) { // if (pressed) press(button) else release(button) //} fun reset() { timestamp = 0 buttons = 0 lx = 128 ly = 128 } } val currentFrame get() = frames[frameIndex] fun startFrame(timestamp: Int) = run { currentFrame.timestamp = timestamp } fun endFrame() { val lastFrame = currentFrame frameIndex = (frameIndex + 1) % frames.size currentFrame.setTo(lastFrame) } fun updateButton(button: PspCtrlButtons, pressed: Boolean) { currentFrame.buttons = currentFrame.buttons.setBits(button.bits, pressed) //if (button == PspCtrlButtons.home && pressed) { // emulator.onHomePress(Unit) //} //if (button == PspCtrlButtons.hold && pressed) { // emulator.onLoadPress(Unit) //} } private fun fixFloat(v: Float): Int = ((v.clamp(-1f, 1f) * 127) + 128).toInt() fun updateAnalog(x: Float, y: Float) { currentFrame.lx = fixFloat(x) currentFrame.ly = fixFloat(y) //println("Update analog: ($x, $y) - ($lx, $ly)") } fun reset() { samplingCycle = 0 samplingMode = 0 for (f in frames) f.reset() lastLatchData.reset() frameIndex = 0 } } enum class PspCtrlButtons(val bits: Int) { //: uint none(0x0000000), select(0x0000001), start(0x0000008), up(0x0000010), right(0x0000020), down(0x0000040), left(0x0000080), leftTrigger(0x0000100), rightTrigger(0x0000200), triangle(0x0001000), circle(0x0002000), cross(0x0004000), square(0x0008000), home(0x0010000), hold(0x0020000), wirelessLanUp(0x0040000), remote(0x0080000), volumeUp(0x0100000), volumeDown(0x0200000), screen(0x0400000), note(0x0800000), discPresent(0x1000000), memoryStickPresent(0x2000000); }
mit
009702b2bbcb6aff5b5dec93b12bc1a6
27.106796
106
0.593296
3.65866
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/util/io/MountableVfsSync.kt
1
2415
package com.soywiz.kpspemu.util.io import com.soywiz.klogger.* import com.soywiz.korio.* import com.soywiz.korio.file.* fun MountableVfsSyncNew(callback: MountableSync.() -> Unit): VfsFile { val logger = Logger("MountableVfsSync") val mount = object : Vfs.Proxy(), MountableSync { private val _mounts = ArrayList<Pair<String, VfsFile>>() override val mounts: Map<String, VfsFile> get() = _mounts.toMap() override fun mount(folder: String, file: VfsFile) = this.apply { _unmount(folder) _mounts += VfsUtil.normalize(folder) to file resort() } override fun unmount(folder: String): MountableSync = this.apply { _unmount(folder) resort() } override fun unmountAll(): MountableSync = this.apply { _mounts.clear() } private fun _unmount(folder: String) { _mounts.removeAll { it.first == VfsUtil.normalize(folder) } } private fun resort() { _mounts.sortBy { -it.first.length } } override suspend fun VfsFile.transform(): VfsFile { //return super.transform(out) return this } override suspend fun access(path: String): VfsFile { val rpath = VfsUtil.normalize(path) for ((base, file) in _mounts) { //println("$base/$file") if (rpath.startsWith(base)) { val nnormalizedPath = rpath.substring(base.length) val subpath = VfsUtil.normalize(nnormalizedPath).trim('/') logger.warn { "Accessing $file : $subpath ($nnormalizedPath)" } val res = file[subpath] logger.warn { " --> $res (${res.exists()})" } return res } } logger.warn { "Can't find $rpath in mounted ${_mounts.map { it.first }}" } throw FileNotFoundException(path) } } callback(mount) return mount.root } //inline fun MountableVfs(callback: Mountable.() -> Unit): VfsFile { // val mount = MountableVfs() // callback(mount) // return mount.root //} interface MountableSync { fun mount(folder: String, file: VfsFile): MountableSync fun unmount(folder: String): MountableSync fun unmountAll(): MountableSync val mounts: Map<String, VfsFile> }
mit
c7aff8e01485b728a841d489af21f34b
30.363636
86
0.570186
4.10017
false
false
false
false
d9n/trypp.support
src/test/code/trypp/support/memory/HeapPoolTest.kt
1
4461
package trypp.support.memory import com.google.common.truth.Truth.assertThat import org.testng.annotations.Test class HeapPoolTest { @Test fun grabNewAndFreeWorksAsExpected() { val pool = HeapPool({ PoolItem() }, { it.reset() }, capacity = 5) assertThat(pool.itemsInUse.size).isEqualTo(0) assertThat(pool.remainingCount).isEqualTo(5) val item1 = pool.grabNew() assertThat(pool.itemsInUse.size).isEqualTo(1) assertThat(pool.remainingCount).isEqualTo(4) val item2 = pool.grabNew() val item3 = pool.grabNew() val item4 = pool.grabNew() val item5 = pool.grabNew() assertThat(pool.itemsInUse.size).isEqualTo(5) assertThat(pool.remainingCount).isEqualTo(0) pool.free(item3) assertThat(pool.itemsInUse.size).isEqualTo(4) assertThat(pool.remainingCount).isEqualTo(1) pool.free(item5) pool.free(item1) pool.free(item2) pool.free(item4) assertThat(pool.itemsInUse.size).isEqualTo(0) assertThat(pool.remainingCount).isEqualTo(5) } @Test fun poolOfPoolableMethodWorksAsExpected() { val pool = HeapPool.of(PoolItem::class) var item = pool.grabNew() assertThat(item.resetCount).isEqualTo(0) pool.free(item) assertThat(item.resetCount).isEqualTo(1) item = pool.grabNew() assertThat(item.resetCount).isEqualTo(1) } @Test fun makeResizableAllowsPoolToGrow() { var allocationCount = 0 val pool = HeapPool({ allocationCount++; PoolItem() }, { it.reset() }, capacity = 2) assertThat(pool.resizable).isFalse() pool.makeResizable(maxCapacity = 3) assertThat(pool.resizable).isTrue() assertThat(pool.capacity).isEqualTo(2) assertThat(pool.maxCapacity).isEqualTo(3) assertThat(allocationCount).isEqualTo(2) pool.grabNew() pool.grabNew() pool.grabNew() assertThat(pool.capacity).isEqualTo(3) assertThat(pool.maxCapacity).isEqualTo(3) assertThat(allocationCount).isEqualTo(3) } @Test fun freeAllWorksAsExpected() { val pool = HeapPool({ PoolItem() }, { it.reset() }) pool.grabNew() pool.grabNew() pool.grabNew() assertThat(pool.itemsInUse.size).isEqualTo(3) pool.freeAll() assertThat(pool.itemsInUse.size).isEqualTo(0) } // // @Test fun makeResizableWithBadCapacityThrowsException() { // val pool = HeapPool({ PoolItem() }, { it.reset() }, capacity = 2) // try { // pool.makeResizable(maxCapacity = 1) // Assert.fail("Can't resize pool below its current capacity") // } // catch (e: IllegalArgumentException) { // } // // assertThat(pool.resizable).isFalse() // } // // // @Test fun freeUnownedObjectThrowsException() { // val pool = HeapPool({ PoolItem() }, { it.reset() }) // try { // pool.free(PoolItem()) // Assert.fail("Pool can't free what it doesn't own") // } // catch (e: IllegalArgumentException) { // } // } // // @Test fun freeObjectTwiceThrowsException() { // val pool = HeapPool({ PoolItem() }, { it.reset() }) // val item = pool.grabNew() // pool.free(item) // try { // pool.free(item) // Assert.fail("Pool can't free same item twice") // } // catch (e: IllegalArgumentException) { // } // } // // @Test fun goingOverCapacityThrowsException() { // val pool = HeapPool({ PoolItem() }, { it.reset() }, capacity = 3) // pool.grabNew() // pool.grabNew() // pool.grabNew() // try { // pool.grabNew() // Assert.fail("Can't grab new if a pool is out of capacity") // } // catch (e: IllegalStateException) { // } // } // // @Test fun invalidCapacityThrowsException() { // try { // Pool({ PoolItem() }, { it.reset() }, capacity = 0) // Assert.fail("Pool can't be instantiated with no capacity") // } // catch (e: IllegalArgumentException) { // } // // try { // Pool({ PoolItem() }, { it.reset() }, capacity = -5) // Assert.fail("Pool can't be instantiated with negative capacity") // } // catch (e: IllegalArgumentException) { // } // } }
mit
af353a41a3d906da0e2bd300dd303da7
29.979167
92
0.576552
3.780508
false
true
false
false
tarsjoris/Sudoku
src/com/tjoris/sudoku/Main.kt
1
2060
package com.tjoris.sudoku import java.io.BufferedReader import java.io.File import java.io.FileInputStream import java.io.InputStreamReader fun main(args: Array<String>) { try { if (args.isEmpty()) { println("Usage: configuration-file") return } val file = File(args[0]) println("Reading file: ${file.absolutePath}") val field = BufferedReader(InputStreamReader(FileInputStream(file))).use(::readField) val solutions = field.solve() if (solutions.isEmpty()) { println("No solutions") } else { solutions.forEach { it.print() } } } catch (e: Exception) { e.printStackTrace(System.out) } } fun readField(reader: BufferedReader): FieldWithZones { val size = Integer.parseInt(reader.readLine()) val length = size * size val startValue = Integer.parseInt(reader.readLine()) val conversion = Conversion(startValue.toShort(), length) val field = FieldWithZones(length, conversion) var line = reader.readLine() if (line == "normal") { // normal 2-d sudoku's for (i in 0 until length) { for (j in 0 until length) { field.addCellToZone(i * length + j, i) field.addCellToZone(i + j * length, length + i) field.addCellToZone(i / size * length * size + i % size * size + j / size * length + j % size, 2 * length + i) } } } else { // special dimension sudoku's (e.g. 3d) for (zoneIndex in 0 until 3 * length) { line = reader.readLine() for (index in 0 until length) { field.addCellToZone(conversion.parse(line[index]).toInt(), zoneIndex) } } } for (i in 0 until length) { line = reader.readLine() for (j in 0 until length) { val ch = line[j] if (ch != '.') { field.setValue(i * length + j, conversion.parse(ch)) } } } return field }
gpl-3.0
9c8cb9cdad881fd3a55468b261cfe467
30.212121
126
0.55534
4.103586
false
false
false
false
AlekseyZhelo/LBM
lbmlib/src/main/kotlin/com/alekseyzhelo/lbm/boundary/InletBoundary.kt
1
2473
package com.alekseyzhelo.lbm.boundary import com.alekseyzhelo.lbm.core.lattice.DescriptorD2Q9 import com.alekseyzhelo.lbm.core.lattice.LatticeD2 import com.alekseyzhelo.lbm.util.computeEquilibrium import com.alekseyzhelo.lbm.util.normSquare import com.alekseyzhelo.lbm.util.opposite class InletBoundary( position: BoundaryPosition, lattice: LatticeD2<*>, x0: Int, x1: Int, y0: Int, y1: Int, val inletRho: Double, val inletVelocity: DoubleArray ) : BoundaryCondition(position, lattice, x0, x1, y0, y1) { override fun getType(): BoundaryType { return BoundaryType.INLET } override fun streamOutgoing(i: Int, j: Int) { val uSqr = normSquare(inletVelocity) for (f in position.outgoing) { lattice.cells[i][j].fBuf[opposite[f]] = computeEquilibrium(opposite[f], inletRho, inletVelocity, uSqr) } } override fun boundaryStream() { for (i in x0..x1) { for (j in y0..y1) { for (f in position.inside) { lattice.cells[i + DescriptorD2Q9.c[f][0]][j + DescriptorD2Q9.c[f][1]].fBuf[f] = lattice.cells[i][j].f[f] } val uSqr = normSquare(inletVelocity) for (f in position.outgoing) { lattice.cells[i][j].fBuf[opposite[f]] = computeEquilibrium(opposite[f], inletRho, inletVelocity, uSqr) } } } } override fun defineBoundaryRhoU(rho: Double, U: DoubleArray) { for (i in x0..x1) { for (j in y0..y1) { lattice.cells[i][j].defineRhoU(inletRho, inletVelocity) } } } override fun defineBoundaryRhoU(rho: Double, U: (i: Int, j: Int) -> DoubleArray) { for (i in x0..x1) { for (j in y0..y1) { lattice.cells[i][j].defineRhoU(inletRho, inletVelocity) } } } override fun defineBoundaryRhoU(rho: (i: Int, j: Int) -> Double, U: DoubleArray) { for (i in x0..x1) { for (j in y0..y1) { lattice.cells[i][j].defineRhoU(inletRho, inletVelocity) } } } override fun defineBoundaryRhoU(rho: (i: Int, j: Int) -> Double, U: (i: Int, j: Int) -> DoubleArray) { for (i in x0..x1) { for (j in y0..y1) { lattice.cells[i][j].defineRhoU(inletRho, inletVelocity) } } } }
apache-2.0
d64dc2937a6f0edf7bb902f9305ed0aa
32.432432
114
0.558835
3.319463
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/base/usecase/GetPointsFromCoordinatesUseCase.kt
1
3644
package com.arcao.geocaching4locus.base.usecase import com.arcao.geocaching4locus.authentication.util.restrictions import com.arcao.geocaching4locus.base.constants.AppConstants import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider import com.arcao.geocaching4locus.base.util.DownloadingUtil import com.arcao.geocaching4locus.data.account.AccountManager import com.arcao.geocaching4locus.data.api.GeocachingApiRepository import com.arcao.geocaching4locus.data.api.model.Coordinates import com.arcao.geocaching4locus.error.exception.NoResultFoundException import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext import kotlinx.coroutines.yield import locus.api.mapper.DataMapper import timber.log.Timber import kotlin.math.min class GetPointsFromCoordinatesUseCase( private val repository: GeocachingApiRepository, private val geocachingApiLogin: GeocachingApiLoginUseCase, private val accountManager: AccountManager, private val geocachingApiFilterProvider: GeocachingApiFilterProvider, private val mapper: DataMapper, private val dispatcherProvider: CoroutinesDispatcherProvider ) { @Suppress("BlockingMethodInNonBlockingContext") suspend operator fun invoke( coordinates: Coordinates, distanceMeters: Int, liteData: Boolean = true, geocacheLogsCount: Int = 0, downloadDisabled: Boolean = false, downloadFound: Boolean = false, downloadOwn: Boolean = false, geocacheTypes: IntArray = intArrayOf(), containerTypes: IntArray = intArrayOf(), difficultyMin: Float = 1F, difficultyMax: Float = 5F, terrainMin: Float = 1F, terrainMax: Float = 5F, maxCount: Int = 50, countHandler: (Int) -> Unit = {} ) = flow { geocachingApiLogin() var count = maxCount var current = 0 var itemsPerRequest = AppConstants.INITIAL_REQUEST_SIZE while (current < count) { val startTimeMillis = System.currentTimeMillis() val geocaches = repository.search( filters = geocachingApiFilterProvider( coordinates, distanceMeters, downloadDisabled, downloadFound, downloadOwn, geocacheTypes, containerTypes, difficultyMin, difficultyMax, terrainMin, terrainMax ), logsCount = geocacheLogsCount, lite = liteData, skip = current, take = min(itemsPerRequest, count - current) ).also { count = min(it.totalCount, maxCount.toLong()).toInt() withContext(dispatcherProvider.io) { countHandler(count) } } accountManager.restrictions().updateLimits(repository.userLimits()) yield() if (geocaches.isEmpty()) break emit(mapper.createLocusPoints(geocaches)) current += geocaches.size itemsPerRequest = DownloadingUtil.computeRequestSize( itemsPerRequest, AppConstants.SEARCH_MAX_REQUEST_SIZE, startTimeMillis ) } Timber.v("found geocaches: %d", current) if (current == 0) { throw NoResultFoundException() } }.flowOn(dispatcherProvider.io) }
gpl-3.0
73a419f4b0ff1c97f749e0b4d1b02081
34.038462
79
0.62843
5.139633
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/entity/Entity2D.kt
1
4497
package xyz.jmullin.drifter.entity import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.math.Vector2 import xyz.jmullin.drifter.animation.Trigger import xyz.jmullin.drifter.extensions.V2 import xyz.jmullin.drifter.rendering.RenderStage import xyz.jmullin.drifter.rendering.shader.ShaderSet import xyz.jmullin.drifter.rendering.shader.Shaders /** * 2-dimensional entity, contains scaffolding on top of Entity for tracking 2d position and orientation. * An Entity2D can be added/removed from a Layer2D, which will take care of calling update/render periodically. */ @Suppress("UNUSED_PARAMETER") open class Entity2D : EntityContainer2D, Entity() { override var paused: Boolean = false override var hidden: Boolean = false // Implicits for local context fun self() = this override fun layer() = parent?.layer() override var children = emptyList<Entity2D>() /** * This entity's parent container, or None if it's not attached. */ var parent: EntityContainer2D? = null /** * World position of the entity. */ val position = V2(0, 0) /** * World size of the entity. */ val size = V2(0, 0) /** * Priority of the entity, used for determining update order (entities with higher priority will be processed * before entities with lower priority). */ var priority = 0 /** * Depth of the entity, used for Z sorting (entities with lower depth will appear on top * of entities with higher depth) */ var depth = 0f // Convenience methods for referring to position and size components directly val x: Float get() = position.x val y: Float get() = position.y val width: Float get() = size.x val height: Float get() = size.y val _bounds = Rectangle() open val bounds: Rectangle get() = _bounds.set(x, y, width, height) /** * Called by the parent container when this entity is added to it. Override to perform some * action after the parent container has been assigned. * * @param container The new parent container. */ open fun create(container: EntityContainer2D) {} /** * Called by the parent container on each frame to render this entity. * * @param stage Active render stage to draw to. */ open fun render(stage: RenderStage) { renderChildren(stage) } /** * Called by the parent container at each tick to update this entity. * * @param delta Time in seconds elapsed since the last update tick. */ override fun update(delta: Float) { updateChildren(delta) super.update(delta) } /** * Remove this entity from its parent container, if any. */ open fun remove() { layer()?.remove(this) parent = null } /** * Replace this entity with another, substituting its parent, position and size. * * @param e Entity to replace this with. */ fun replaceWith(e: Entity2D) { layer()?.let { it.add(e) e.position.set(position) e.size.set(size) remove() } } /** * Returns true if the given point (in world coordinates) intersects with this entity. * By default this is determined using the entity's bounds (position and size) and checks * for collisions with children as well, returning true if any children intersect. * * @param v The point to check. * @return True if the point is contained in this entity */ open fun containsPoint(v: Vector2): Boolean = bounds.contains(v) || children.find { it.containsPoint(v) } != null /** * Unprojects a screen coordinate into the world space of the parent layer. * * @param v Point to unproject. * @return The corresponding world space coordinate. */ fun unproject(v: Vector2) = layer()?.viewport?.unproject(v.cpy()) ?: V2(0, 0) /** * Executes a rendering block with the specified shader applied. * * // TODO Figure out a better way to handle shader switches efficiently, perhaps in tandem * // TODO with sorting to order entities at a single depth by shader. */ fun withShader(shader: ShaderSet, batch: SpriteBatch, block: () -> Unit) { Shaders.switch(shader, batch) block() Shaders.switch(Shaders.default, batch) } fun Trigger.go() = this.go(this@Entity2D) }
mit
cb64f3bb3d7cd05b255b9950a291e8d9
30.669014
117
0.650211
4.187151
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/views/SponsorsView.kt
1
3300
package net.perfectdreams.loritta.morenitta.website.views import net.perfectdreams.loritta.common.locale.BaseLocale import kotlinx.html.DIV import kotlinx.html.div import kotlinx.html.h1 import kotlinx.html.h2 import kotlinx.html.h3 import kotlinx.html.img import kotlinx.html.li import kotlinx.html.p import kotlinx.html.style import kotlinx.html.ul import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.sweetmorenitta.utils.generateSponsorNoWrap class SponsorsView(loritta: LorittaBot, locale: BaseLocale, path: String) : NavbarView(loritta, locale, path) { override fun getTitle() = "Patrocinadores" override fun DIV.generateContent() { div(classes = "even-wrapper") { div(classes = "media") { div(classes = "media-body") { div { style = "text-align: center;" h1 { + "Patrocinadores" } loritta.sponsors.forEach { generateSponsorNoWrap(it) } } } } } div(classes = "odd-wrapper wobbly-bg") { div(classes = "media") { div(classes = "media-figure") { img(src = "https://loritta.website/assets/img/fanarts/Loritta_-_Heathecliff.png") {} } div(classes = "media-body") { div { style = "text-align: left;" div { style = "text-align: center;" h2 { + "Para que servem os patrocinadores?" } } p { + "Patrocinadores são pessoas incríveis que querem divulgar seus servidores e projetos na Loritta, divulgando para mais de cinco mil pessoas diferentes todos os dias!" } h3 { + "A cada mês, donos de servidores podem colocar os seus servidores..." } ul { li { + "Na \"Quarta Patrocinada\" no Servidor de Suporte da Loritta!" } li { + "Na home page e na página de daily da Loritta" } li { + "No status de \"Jogando\" da Loritta" } li { + "E aqui, na página de patrocinadores da Loritta!" } } h3 { + "Se interessou?" } p { + "Então veja o canal de slots premiums no servidor de suporte da Loritta para saber mais sobre os requisitos, formas de pagamento, como funciona e muito mais!" } } } } } } }
agpl-3.0
9e772aa0c205c1bc175cfa25e7cd3986
35.611111
195
0.431998
4.923767
false
false
false
false
MaibornWolff/codecharta
analysis/filter/MergeFilter/src/main/kotlin/de/maibornwolff/codecharta/filter/mergefilter/ParserDialog.kt
1
1923
package de.maibornwolff.codecharta.filter.mergefilter import com.github.kinquirer.KInquirer import com.github.kinquirer.components.promptConfirm import com.github.kinquirer.components.promptInput import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface class ParserDialog { companion object : ParserDialogInterface { override fun collectParserArgs(): List<String> { val inputFolderName = KInquirer.promptInput(message = "What is the folder of cc.json files that has to be merged?") val outputFileName: String = KInquirer.promptInput( message = "What is the name of the output file?" ) val isCompressed = (outputFileName.isEmpty()) || KInquirer.promptConfirm( message = "Do you want to compress the output file?", default = true ) val addMissing: Boolean = KInquirer.promptConfirm(message = "Do you want to add missing nodes to reference?", default = false) val recursive: Boolean = KInquirer.promptConfirm(message = "Do you want to use recursive merge strategy?", default = true) val leaf: Boolean = KInquirer.promptConfirm(message = "Do you want to use leaf merging strategy?", default = false) val ignoreCase: Boolean = KInquirer.promptConfirm( message = "Do you want to ignore case when checking node names?", default = false ) return listOf( inputFolderName, "--output-file=$outputFileName", "--not-compressed=$isCompressed", "--add-missing=$addMissing", "--recursive=$recursive", "--leaf=$leaf", "--ignore-case=$ignoreCase" ) } } }
bsd-3-clause
2562fc462b1aea2136612f753df7f841
36.705882
116
0.592304
5.606414
false
false
false
false
Lennoard/HEBF
app/src/main/java/com/androidvip/hebf/ui/main/performance/GameBoosterSheetFragment.kt
1
18015
package com.androidvip.hebf.ui.main.performance import android.animation.ValueAnimator import android.app.Activity import android.app.NotificationManager import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.provider.Settings import android.view.View import androidx.appcompat.app.AlertDialog import androidx.core.view.ViewCompat import androidx.core.view.forEach import androidx.core.widget.NestedScrollView import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.androidvip.hebf.* import com.androidvip.hebf.ui.main.tune.LmkActivity import com.androidvip.hebf.adapters.ForceStopAppsAdapter import com.androidvip.hebf.databinding.FragmentGameBoosterSheetBinding import com.androidvip.hebf.models.App import com.androidvip.hebf.ui.base.binding.BaseViewBindingSheetFragment import com.androidvip.hebf.utils.* import com.androidvip.hebf.utils.gb.GameBoosterImpl import com.androidvip.hebf.utils.gb.GameBoosterNutellaImpl import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.* class GameBoosterSheetFragment : BaseViewBindingSheetFragment<FragmentGameBoosterSheetBinding>( FragmentGameBoosterSheetBinding::inflate ) { private val gbPrefs: GbPrefs by lazy { GbPrefs(requireContext().applicationContext) } private var isGameBoosterEnabled: Boolean = false override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setUpShape() lifecycleScope.launch(workerContext) { val isRooted = isRooted() val cpuManager = CpuManager() withContext(Dispatchers.Main) { setUpChecks(isRooted) setUpCpu(cpuManager, isRooted) setUpLmk(isRooted) setUpSliders(isRooted) setUpForceStop() } } if (isTaskerInstalled()) { binding.taskerFab.apply { show() extend() setOnClickListener { try { requireContext().packageManager.getLaunchIntentForPackage( "net.dinglisch.android.taskerm" ).apply { startActivity(this) } } catch (e: Exception) { requireContext().toast("Failed to start Tasker") } } } binding.scrollView.setOnScrollChangeListener( NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, oldScrollY -> if (scrollY > oldScrollY) { binding.taskerFab.shrink() } else { binding.taskerFab.extend() } } ) } binding.gameBoosterLaunchGames.setOnClickListener { Intent(requireContext(), LaunchGamesActivity::class.java).apply { startActivity(this) } } } override fun onResume() { super.onResume() val notificationManager = requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager binding.dnd.apply { isChecked = gbPrefs.getBoolean(K.PREF.GB_DND, false) setOnCheckedChangeListener(null) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { isEnabled = true setOnCheckedChangeListener { _, isChecked -> if (isChecked) { if (!notificationManager.isNotificationPolicyAccessGranted) { try { Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS).apply { startActivity(this) } } catch (e: Exception) { this.isChecked = false gbPrefs.putBoolean(K.PREF.GB_DND, false) requireContext().toast("Failed to get DND permission") Logger.logError(e, requireContext()) } } else { gbPrefs.putBoolean(K.PREF.GB_DND, true) if (isGameBoosterEnabled) { notificationManager.setInterruptionFilter( NotificationManager.INTERRUPTION_FILTER_ALARMS ) } } } else { gbPrefs.putBoolean(K.PREF.GB_DND, false) } } } else { isEnabled = false } } lifecycleScope.launch(workerContext) { val isRooted = isRooted() val isEnabled = Utils.runCommand("getprop hebf.gb_enabled", "0") == "1" withContext(Dispatchers.Main) { binding.gameBoosterSwitch.apply { setOnCheckedChangeListener(null) val gameBooster = if (isRooted) { GameBoosterImpl(requireContext()) } else { GameBoosterNutellaImpl(requireContext()) } isChecked = isEnabled if (isEnabled) { setText(R.string.on) } else { setText(R.string.off) } setOnCheckedChangeListener { _, isChecked -> lifecycleScope.launch { if (isChecked) { isGameBoosterEnabled = true gameBooster.enable() setText(R.string.on) } else { isGameBoosterEnabled = false gameBooster.disable() setText(R.string.off) } } } } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_SELECT_LMK_PARAMS) { if (resultCode == Activity.RESULT_OK) { requireContext().toast(R.string.done) } else { requireContext().toast(R.string.failed) } } } private fun setUpChecks(isRooted: Boolean) { binding.lmk.apply { isEnabled = isRooted isChecked = gbPrefs.getBoolean(K.PREF.GB_CHANGE_LMK, false) setOnCheckedChangeListener { _, isChecked -> gbPrefs.putBoolean(K.PREF.GB_CHANGE_LMK, isChecked) if (isChecked) { gbPrefs.putInt("PerfisLMK", 4) } else { gbPrefs.putInt("PerfisLMK", 0) } } } binding.governor.apply { isEnabled = isRooted isChecked = gbPrefs.getBoolean(K.PREF.GB_CHANGE_GOV, false) setOnCheckedChangeListener { _, isChecked -> gbPrefs.putBoolean(K.PREF.GB_CHANGE_GOV, isChecked) } } binding.caches.apply { isChecked = gbPrefs.getBoolean(K.PREF.GB_CLEAR_CACHES, true) setOnCheckedChangeListener { _, isChecked -> gbPrefs.putBoolean(K.PREF.GB_CLEAR_CACHES, isChecked) if (isChecked && isGameBoosterEnabled) { if (isRooted) { runCommand("sync && sysctl -w vm.drop_caches=3") } } } } binding.brightness.apply { val canWriteSettings = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(requireContext()) isEnabled = isRooted || canWriteSettings isChecked = gbPrefs.getBoolean(K.PREF.GB_CHANGE_BRIGHTNESS, false) setOnCheckedChangeListener { _, isChecked -> gbPrefs.putBoolean(K.PREF.GB_CHANGE_BRIGHTNESS, isChecked) } } } private fun setUpCpu(manager: CpuManager, isRooted: Boolean) { val policy = manager.policies?.firstOrNull() val currentGov = policy?.currentGov ?: "performance" val availableGovs = policy?.availableGovs ?: CpuManager.DEFAULT_GOVERNORS.split(" ").toTypedArray() val easHint = availableGovs.firstOrNull { it in CpuManager.EAS_GOVS.split(" ") } != null if (easHint) { // EAS stuff? binding.cpuEasWarning.show() binding.cpuGovText.text = gbPrefs.getString(K.PREF.GB_GOV, currentGov) } else { binding.cpuGovText.text = gbPrefs.getString(K.PREF.GB_GOV, "interactive") } binding.cpuGovLayout.apply { isEnabled = isRooted if (!isRooted) { forEach { it.isEnabled = false } } else setOnClickListener { MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.cpu_governor) .setSingleChoiceItems(availableGovs, -1) { dialog, which -> dialog.dismiss() gbPrefs.putString(K.PREF.GB_GOV, availableGovs[which]) binding.cpuGovText.text = availableGovs[which] }.applyAnim().also { if (isActivityAlive) { it.show() } } } } } private fun setUpLmk(isRooted: Boolean) { binding.lmkProfileLayout.apply { isEnabled = isRooted if (!isRooted) { forEach { it.isEnabled = false } } else setOnClickListener { val array = resources.getStringArray(R.array.game_booster_lmk_profiles) MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.cpu_governor) .setSingleChoiceItems(array, -1) { dialog, which -> dialog.dismiss() gbPrefs.putInt(K.PREF.GB_LMK_PROFILE_SELECTION, which) binding.lmkText.text = array[which] if (which == 1) { Intent(requireContext(), LmkActivity::class.java).apply { putExtra("gb_select_lmk_params", true) startActivityForResult(this, REQUEST_SELECT_LMK_PARAMS) } } }.applyAnim().also { if (isActivityAlive) { it.show() } } } } } private fun setUpSliders(isRooted: Boolean) { val canWriteSettings = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(requireContext()) binding.brightnessSliderEnabled.apply { isEnabled = canWriteSettings || isRooted runCatching { value = gbPrefs.getInt(K.PREF.GB_BRIGHTNESS_LEVEL_ENABLED, 240).toFloat() }.onFailure { value = 240F } addOnChangeListener { _, value, _ -> gbPrefs.putInt(K.PREF.VIP_BRIGHTNESS_LEVEL_ENABLED, value.toInt()) } } binding.brightnessSliderDisabled.apply { isEnabled = canWriteSettings || isRooted runCatching { value = gbPrefs.getInt(K.PREF.GB_BRIGHTNESS_LEVEL_DISABLED, 140).toFloat() }.onFailure { value = 140F } addOnChangeListener { _, value, _ -> gbPrefs.putInt(K.PREF.VIP_BRIGHTNESS_LEVEL_DISABLED, value.toInt()) } } } private fun setUpForceStop() { binding.forceStop.apply { isChecked = gbPrefs.getBoolean(K.PREF.GB_FORCE_STOP, false) setOnCheckedChangeListener { _, isChecked -> gbPrefs.putBoolean(K.PREF.GB_FORCE_STOP, isChecked) } } val appsSet = gbPrefs.getStringSet(K.PREF.FORCE_STOP_APPS_SET, HashSet()) binding.forceStopText.text = appsSet.toString() binding.forceStopLayout.setOnClickListener { showPickAppsDialog() } } private fun showPickAppsDialog() { val loadingSnackBar = Snackbar.make( binding.gameBoosterSwitch, R.string.loading, Snackbar.LENGTH_INDEFINITE ) loadingSnackBar.show() val builder = AlertDialog.Builder(requireContext()) val dialogView = layoutInflater.inflate(R.layout.dialog_list_force_stop_apps, null) builder.setTitle(R.string.hibernate_apps) builder.setView(dialogView) lifecycleScope.launch(workerContext) { val packagesManager = PackagesManager(requireContext()) val packages = if (userPrefs.getInt(K.PREF.USER_TYPE, K.USER_TYPE_NORMAL) == K.USER_TYPE_NORMAL) { packagesManager.installedPackages } else { (packagesManager.getSystemApps() + packagesManager.getThirdPartyApps()).map { it.packageName } } val savedAppSet = userPrefs.getStringSet(K.PREF.FORCE_STOP_APPS_SET, HashSet()) val allApps = ArrayList<App>() for (packageName in packages) { // Remove HEBF from the list if (packageName.contains("com.androidvip")) continue App().apply { this.packageName = packageName label = packagesManager.getAppLabel(packageName) icon = packagesManager.getAppIcon(packageName) isChecked = savedAppSet.contains(packageName) if (!allApps.contains(this)) { allApps.add(this) } } } allApps.sortWith { one: App, other: App -> one.label.compareTo(other.label) } activity.runSafeOnUiThread { loadingSnackBar.dismiss() val rv = dialogView.findViewById<RecyclerView>(R.id.force_stop_apps_rv) val layoutManager = LinearLayoutManager( requireContext(), RecyclerView.VERTICAL, false ) rv.layoutManager = layoutManager val adapter = ForceStopAppsAdapter(requireActivity(), allApps) rv.adapter = adapter builder.setPositiveButton(android.R.string.ok) { _, _ -> val appSet = adapter.selectedApps val packageNamesSet = HashSet<String>() appSet.forEach { if (it.packageName.isNotEmpty()) { packageNamesSet.add(it.packageName) } } gbPrefs.putStringSet(K.PREF.FORCE_STOP_APPS_SET, packageNamesSet) binding.forceStopText.text = packageNamesSet.toString() } builder.setNegativeButton(android.R.string.cancel) { _, _ -> } builder.show() } } } private fun isTaskerInstalled(): Boolean { return try { requireContext().packageManager.getPackageInfo("net.dinglisch.android.taskerm", 0) true } catch (e: Exception) { false } } private fun setUpShape() { val behavior = (dialog as? BottomSheetDialog)?.behavior behavior?.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { if (newState == BottomSheetBehavior.STATE_EXPANDED) { ValueAnimator.ofFloat(0F, 3.dp).apply { addUpdateListener { if (isResumedState) { ViewCompat.setElevation(binding.title, it.animatedValue as Float) } } }.start() binding.title.background = createExpandedShape() } else { val currElevation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { binding.title.elevation } else 0F ValueAnimator.ofFloat(currElevation, 0F).apply { addUpdateListener { if (isResumedState) { ViewCompat.setElevation(binding.title, it.animatedValue as Float) } } }.start() binding.title.background = createBackgroundShape() } } override fun onSlide(bottomSheet: View, slideOffset: Float) {} }) } companion object { const val REQUEST_SELECT_LMK_PARAMS = 31 } }
apache-2.0
3133296d4915d73961310a4ef921395b
37.995671
100
0.525507
5.455784
false
false
false
false
shyiko/ktlint
ktlint-reporter-json/src/main/kotlin/com/pinterest/ktlint/reporter/json/JsonReporter.kt
1
1858
package com.pinterest.ktlint.reporter.json import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.core.Reporter import java.io.PrintStream import java.util.ArrayList import java.util.concurrent.ConcurrentHashMap class JsonReporter(val out: PrintStream) : Reporter { private val acc = ConcurrentHashMap<String, MutableList<LintError>>() override fun onLintError(file: String, err: LintError, corrected: Boolean) { if (!corrected) { acc.getOrPut(file) { ArrayList() }.add(err) } } override fun afterAll() { out.println("[") val indexLast = acc.size - 1 for ((index, entry) in acc.entries.sortedBy { it.key }.withIndex()) { val (file, errList) = entry out.println(""" {""") out.println(""" "file": "${file.escapeJsonValue()}",""") out.println(""" "errors": [""") val errIndexLast = errList.size - 1 for ((errIndex, err) in errList.withIndex()) { val (line, col, ruleId, detail) = err out.println(""" {""") out.println(""" "line": $line,""") out.println(""" "column": $col,""") out.println(""" "message": "${detail.escapeJsonValue()}",""") out.println(""" "rule": "$ruleId"""") out.println(""" }${if (errIndex != errIndexLast) "," else ""}""") } out.println(""" ]""") out.println(""" }${if (index != indexLast) "," else ""}""") } out.println("]") } private fun String.escapeJsonValue() = this .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\b", "\\b") .replace("\n", "\\n") .replace("\r", "\\r") .replace("\t", "\\t") }
mit
4d29923ab0a1f14a909d3b3b62fc5943
35.431373
83
0.500538
4.213152
false
false
false
false
FurhatRobotics/example-skills
Quiz/src/main/kotlin/furhatos/app/quiz/setting/personas.kt
1
827
package furhatos.app.quiz.setting import furhatos.flow.kotlin.FlowControlRunner import furhatos.flow.kotlin.furhat import furhatos.flow.kotlin.voice.PollyNeuralVoice import furhatos.flow.kotlin.voice.Voice class Persona(val name: String, val mask: String = "adult", val face: List<String>, val voice: List<Voice>) { } fun FlowControlRunner.activate(persona: Persona) { for (voice in persona.voice) { if (voice.isAvailable) { furhat.voice = voice break } } for (face in persona.face) { if (furhat.faces.get(persona.mask)?.contains(face)!!){ furhat.setCharacter(face) break } } } val quizPersona = Persona( name = "Quizmaster", face = listOf("Alex", "default"), voice = listOf(PollyNeuralVoice.Joanna()) )
mit
ddc3227adbd7fac448be14c107590e55
26.6
109
0.645707
3.691964
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/preferences/color/ColorPreferenceDialog.kt
1
3019
package mil.nga.giat.mage.preferences.color import android.content.Context import android.graphics.Color import androidx.preference.PreferenceDialogFragmentCompat import android.view.LayoutInflater import mil.nga.giat.mage.R import android.text.TextWatcher import android.text.Editable import android.os.Bundle import android.view.View import android.widget.EditText import java.lang.Exception class ColorPreferenceDialog( private val preference: ColorPickerPreference ) : PreferenceDialogFragmentCompat(), View.OnClickListener { private lateinit var editText: EditText override fun onCreateDialogView(context: Context): View? { val inflater = LayoutInflater.from(context) return inflater.inflate(R.layout.dialog_color_picker, null) } override fun onBindDialogView(view: View) { super.onBindDialogView(view) editText = view.findViewById(R.id.hexText) editText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) { setColor(s.toString()) } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} }) editText.setText(preference.color) addClickListener(view, R.id.orange_tile) addClickListener(view, R.id.red_tile) addClickListener(view, R.id.blue_tile) addClickListener(view, R.id.green_tile) addClickListener(view, R.id.indigo_tile) addClickListener(view, R.id.orange_tile) addClickListener(view, R.id.pink_tile) addClickListener(view, R.id.purple_tile) addClickListener(view, R.id.red_tile) addClickListener(view, R.id.light_blue_tile) addClickListener(view, R.id.yellow_tile) addClickListener(view, R.id.light_gray_tile) addClickListener(view, R.id.dark_gray_tile) addClickListener(view, R.id.black_tile) } override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) { val color = editText.text.toString() try { Color.parseColor(color) if (preference.callChangeListener(color)) { preference.color = color } } catch (ignore: Exception) {} } } override fun onClick(v: View) { val color = v.backgroundTintList!!.defaultColor val hexColor = String.format("#%06X", 0xFFFFFF and color) editText.setText(hexColor) editText.compoundDrawables[0]?.setTint(color) } private fun addClickListener(parent: View, viewId: Int) { val view = parent.findViewById<View>(viewId) view.setOnClickListener(this) } private fun setColor(hexColor: String) { try { val color = Color.parseColor(hexColor) editText.compoundDrawablesRelative[0]?.setTint(color) } catch (ignore: Exception) { } } init { val b = Bundle() b.putString(ARG_KEY, preference.key) arguments = b } }
apache-2.0
13dcda3d60e784d7520a94db0a4381dd
31.826087
95
0.687645
4.175657
false
false
false
false
springboot-angular2-tutorial/boot-app
src/main/kotlin/com/myapp/service/MicropostServiceImpl.kt
1
1566
package com.myapp.service import com.myapp.auth.SecurityContextService import com.myapp.domain.Micropost import com.myapp.dto.request.PageParams import com.myapp.repository.MicropostRepository import com.myapp.service.exception.NotAuthorizedException import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class MicropostServiceImpl( private val micropostRepository: MicropostRepository, override val securityContextService: SecurityContextService ) : MicropostService, WithCurrentUser { override fun findAllByUser(userId: Long, pageParams: PageParams): List<Micropost> { val currentUser = currentUser() val isMyPost = currentUser?.let { it.id == userId } return micropostRepository.findAllByUser(userId, pageParams) .map { it.copy(isMyPost = isMyPost) } } override fun findMyPosts(pageParams: PageParams): List<Micropost> { val currentUser = currentUserOrThrow() return findAllByUser(currentUser.id, pageParams) } override fun create(content: String) = micropostRepository.create(Micropost( content = content, user = currentUserOrThrow() )) override fun delete(id: Long) { val currentUser = currentUserOrThrow() val post = micropostRepository.findOne(id) if (post.user.id == currentUser.id) micropostRepository.delete(id) else throw NotAuthorizedException("You can not delete this post.") } }
mit
fca02804738811239a2cb15e272afa8b
31.645833
87
0.720945
4.619469
false
false
false
false
JLLeitschuh/ktlint-gradle
samples/android-app/src/main/java/org/jlleitschuh/gradle/ktlint/android/ItemDetailFragment.kt
1
2042
package org.jlleitschuh.gradle.ktlint.android import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import org.jlleitschuh.gradle.ktlint.android.databinding.ItemDetailBinding import org.jlleitschuh.gradle.ktlint.android.dummy.DummyContent /** * A fragment representing a single Item detail screen. * This fragment is either contained in a [ItemListActivity] * in two-pane mode (on tablets) or a [ItemDetailActivity] * on handsets. */ class ItemDetailFragment : Fragment() { /** * The dummy content this fragment is presenting. */ private var mItem: DummyContent.DummyItem? = null private var viewBinding: ItemDetailBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments?.containsKey(ARG_ITEM_ID) == true) { // Load the dummy content specified by the fragment // arguments. In a real-world scenario, use a Loader // to load content from a content provider. mItem = DummyContent.ITEM_MAP[arguments?.getString(ARG_ITEM_ID)] mItem?.let { (activity as? ItemDetailActivity)?.viewBinding?.detailToolbar?.title = it.content } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewBinding = ItemDetailBinding.inflate(inflater, container, false) // Show the dummy content as text in a TextView. mItem?.let { viewBinding?.itemDetail?.text = it.details } return viewBinding?.root } override fun onDestroyView() { viewBinding = null super.onDestroyView() } companion object { /** * The fragment argument representing the item ID that this fragment * represents. */ const val ARG_ITEM_ID = "item_id" } }
mit
d0cdef2f2be0f4a256fb57314d3d5adb
29.477612
97
0.659647
4.640909
false
false
false
false
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepEnsureEthernetHasIpAddress.kt
1
2611
package io.particle.mesh.setup.flow.setupsteps import io.particle.firmwareprotos.ctrl.Network import io.particle.firmwareprotos.ctrl.Network.InterfaceType import io.particle.mesh.R import io.particle.mesh.common.android.livedata.nonNull import io.particle.mesh.common.android.livedata.runBlockOnUiThreadAndAwaitUpdate import io.particle.mesh.common.truthy import io.particle.mesh.setup.flow.* import io.particle.mesh.setup.flow.DialogSpec.ResDialogSpec import io.particle.mesh.setup.flow.context.SetupContexts import io.particle.mesh.setup.flow.FlowUiDelegate import kotlinx.coroutines.delay import mu.KotlinLogging class StepEnsureEthernetHasIpAddress(private val flowUi: FlowUiDelegate) : MeshSetupStep() { private val log = KotlinLogging.logger {} override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { // delay for a moment here because otherwise this always ends up failing the first time delay(2000) val targetXceiver = ctxs.requireTargetXceiver() suspend fun findEthernetInterface(): Network.InterfaceEntry? { val ifaceListReply = targetXceiver.sendGetInterfaceList().throwOnErrorOrAbsent() return ifaceListReply.interfacesList.firstOrNull { it.type == InterfaceType.ETHERNET } } val ethernet = findEthernetInterface() requireNotNull(ethernet) val reply = targetXceiver.sendGetInterface(ethernet.index).throwOnErrorOrAbsent() val iface = reply.`interface` for (addyList in listOf(iface.ipv4Config.addressesList, iface.ipv6Config.addressesList)) { val address = addyList.firstOrNull { it.hasAddressValue() } if (address != null) { log.debug { "IP address on ethernet (interface ${ethernet.index}) found: $address" } return } } val result = flowUi.dialogTool.dialogResultLD .nonNull(scopes) .runBlockOnUiThreadAndAwaitUpdate(scopes) { flowUi.dialogTool.newDialogRequest( ResDialogSpec( R.string.p_connecttocloud_xenon_gateway_needs_ethernet, android.R.string.ok ) ) } log.info { "result from awaiting on 'ethernet must be plugged in dialog: $result" } flowUi.dialogTool.clearDialogResult() throw ExpectedFlowException("Ethernet connection not plugged in; user prompted.") } } private fun Network.InterfaceAddress.hasAddressValue(): Boolean { return this.address.v4.address.truthy() || this.address.v6.address.truthy() }
apache-2.0
55ff6048f4d9cb1bb87d863a1cf5067e
37.411765
100
0.701264
4.486254
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/browser/page_search/PageSearcherModule.kt
1
5760
package jp.toastkid.yobidashi.browser.page_search import android.app.Activity import android.text.Editable import android.text.TextWatcher import android.view.View import androidx.core.view.isVisible import androidx.databinding.ViewStubProxy import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import jp.toastkid.lib.color.IconColorFinder import jp.toastkid.lib.input.Inputs import jp.toastkid.lib.viewmodel.PageSearcherViewModel import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.ModuleSearcherBinding import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Module for find in page. * TODO Clean up code. * @author toastkidjp */ class PageSearcherModule(private val viewStubProxy: ViewStubProxy) { private lateinit var binding: ModuleSearcherBinding /** * This value is used by show/hide animation. */ private var height = 0f private val channel = Channel<String>() fun isVisible() = viewStubProxy.isInflated && viewStubProxy.root?.isVisible == true fun switch() { if (isVisible()) { hide() } else { show() } } /** * Show module with opening software keyboard. */ fun show() { if (!viewStubProxy.isInflated) { initialize() } viewStubProxy.root?.animate()?.let { it.cancel() it.translationY(0f) .setDuration(ANIMATION_DURATION) .withStartAction { switchVisibility(View.GONE, View.VISIBLE) } .withEndAction { val editText = binding.inputLayout.editText ?: return@withEndAction editText.requestFocus() (binding.root.context as? Activity)?.also { activity -> Inputs.showKeyboard(activity, editText) } } .start() } } /** * Hide module. */ fun hide() { viewStubProxy.root?.animate()?.let { it.cancel() it.translationY(-height) .setDuration(ANIMATION_DURATION) .withStartAction { clearInput() Inputs.hideKeyboard(binding.inputLayout.editText) } .withEndAction { switchVisibility(View.VISIBLE, View.GONE) } .start() } } private fun switchVisibility(from: Int, to: Int) { CoroutineScope(Dispatchers.Main).launch { if (viewStubProxy.root?.visibility == from) { viewStubProxy.root?.visibility = to } } } fun initialize() { val context = viewStubProxy.viewStub?.context ?: return viewStubProxy.viewStub?.inflate() binding = viewStubProxy.binding as? ModuleSearcherBinding ?: return val viewModel = (context as? FragmentActivity)?.let { ViewModelProvider(it).get(PageSearcherViewModel::class.java) } binding.viewModel = viewModel binding.inputLayout.editText?.also { it.setOnEditorActionListener { input, _, _ -> viewModel?.findDown(input.text.toString()) Inputs.hideKeyboard(it) true } it.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) = Unit override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { CoroutineScope(Dispatchers.Default).launch { channel.send(p0.toString()) } } }) CoroutineScope(Dispatchers.Default).launch { channel.receiveAsFlow() .debounce(1000) .collect { withContext(Dispatchers.Main) { viewModel?.find(it) } } } } (context as? FragmentActivity)?.let { activity -> viewModel?.clear?.observe(activity, { it?.getContentIfNotHandled() ?: return@observe clearInput() }) viewModel?.close?.observe(activity, { it?.getContentIfNotHandled() ?: return@observe hide() }) } if (height == 0f) { height = binding.root.context.resources.getDimension(R.dimen.toolbar_height) } setBackgroundColor(binding) } private fun clearInput() { binding.inputLayout.editText?.setText("") } /** * Set background color to views. */ private fun setBackgroundColor(binding: ModuleSearcherBinding) { val color = IconColorFinder.from(binding.root).invoke() binding.close.setColorFilter(color) binding.sipClear.setColorFilter(color) binding.sipUpward.setColorFilter(color) binding.sipDownward.setColorFilter(color) } /** * Close subscriptions. */ fun dispose() { channel.cancel() } companion object { /** * Animation duration (ms). */ private const val ANIMATION_DURATION = 250L } }
epl-1.0
7f4454fceb5d57b541549d65ba94b02e
29.315789
99
0.572569
5.165919
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/tab/model/CalendarTab.kt
1
962
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.tab.model import androidx.annotation.Keep import java.util.UUID /** * @author toastkidjp */ class CalendarTab : Tab { @Keep private val calendarTab = true private var id = UUID.randomUUID().toString() private var titleStr = "" private var scrollY = 0 override fun id() = id override fun setScrolled(scrollY: Int) { this.scrollY = scrollY } override fun getScrolled(): Int = scrollY override fun title() = titleStr companion object { fun withTitle(title: String): Tab { return CalendarTab().also { it.titleStr = title } } } }
epl-1.0
698a61664c869a6170608779d0f63f6e
20.886364
88
0.671518
4.200873
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/onboarding/PostStyledKComponent.kt
1
2142
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.litho.onboarding import android.graphics.Typeface import android.widget.ImageView import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Row import com.facebook.litho.Style import com.facebook.litho.core.height import com.facebook.litho.core.margin import com.facebook.litho.core.padding import com.facebook.litho.core.width import com.facebook.litho.dp import com.facebook.litho.drawableRes import com.facebook.litho.flexbox.aspectRatio import com.facebook.litho.kotlin.widget.Image import com.facebook.litho.kotlin.widget.Text import com.facebook.samples.litho.onboarding.model.Post import com.facebook.yoga.YogaAlign // start_example class PostStyledKComponent(val post: Post) : KComponent() { override fun ComponentScope.render(): Component { return Column { child( Row(alignItems = YogaAlign.CENTER, style = Style.padding(all = 8.dp)) { child( Image( drawable = drawableRes(post.user.avatarRes), style = Style.width(36.dp).height(36.dp).margin(start = 4.dp, end = 8.dp))) child(Text(text = post.user.username, textStyle = Typeface.BOLD)) }) child( Image( drawable = drawableRes(post.imageRes), scaleType = ImageView.ScaleType.CENTER_CROP, style = Style.aspectRatio(1f))) } } } // end_example
apache-2.0
5935f78c989fcc2c2e49aa9fcdf66aad
35.305085
95
0.715686
4.041509
false
false
false
false
IntershopCommunicationsAG/jiraconnector-gradle-plugin
src/main/kotlin/com/intershop/gradle/jiraconnector/task/CorrectVersionListRunner.kt
1
2194
/* * Copyright 2020 Intershop Communications AG. * * 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.intershop.gradle.jiraconnector.task import com.intershop.gradle.jiraconnector.task.jira.JiraConnector import org.gradle.api.GradleException import org.gradle.workers.WorkAction /** * Work action implementation for the CorrectVersionList task. */ abstract class CorrectVersionListRunner: WorkAction<CorrectVersionListParameters> { override fun execute() { val connector = getPreparedConnector() if (connector != null) { connector.sortVersions(parameters.projectKey.get()) if(parameters.replacements.orNull != null) { connector.fixVersionNames(parameters.projectKey.get(), parameters.replacements.get()) } } else { throw GradleException("It was not possible to initialize the process. Please check the configuration.") } } private fun getPreparedConnector(): JiraConnector? { if(parameters.baseUrl.isPresent && parameters.userName.isPresent && parameters.userPassword.isPresent ) { val connector = JiraConnector( parameters.baseUrl.get(), parameters.userName.get(), parameters.userPassword.get()) if(parameters.socketTimeout.isPresent) { connector.socketTimeout = parameters.socketTimeout.get() } if(parameters.requestTimeout.isPresent) { connector.requestTimeout = parameters.requestTimeout.get() } return connector } return null } }
apache-2.0
3792794c90637a02e0755a042bf0949e
35.566667
115
0.666363
4.843267
false
false
false
false
egenvall/TravelPlanner
app/src/main/java/com/egenvall/travelplanner/favourite/FavouritePresenter.kt
1
2886
package com.egenvall.travelplanner.favourite import com.egenvall.travelplanner.base.presentation.BasePresenter import com.egenvall.travelplanner.base.presentation.BaseView import com.egenvall.travelplanner.common.injection.scope.PerScreen import com.egenvall.travelplanner.model.Favourite import com.egenvall.travelplanner.model.RealmStopLocation import com.egenvall.travelplanner.model.StopLocation import com.egenvall.travelplanner.model.TripResponseModel import com.egenvall.travelplanner.persistance.IRealmInteractor import com.egenvall.travelplanner.search.SearchTripByStopsUsecase import rx.Observer import javax.inject.Inject @PerScreen class FavouritePresenter @Inject constructor(val searchTripUc : SearchTripByStopsUsecase, private val realmInteractor : IRealmInteractor) : BasePresenter<FavouritePresenter.View>() { //=================================================================================== // Favourites related methods //=================================================================================== fun searchFavouriteTrip(fav : Favourite){ searchTripUc.searchTripsByStops( mapToStopLocation(fav.pair.origin),mapToStopLocation(fav.pair.destination), object : Observer<TripResponseModel>{ override fun onNext(t: TripResponseModel) { } override fun onError(e: Throwable?) { } override fun onCompleted() { } }) } private fun mapToStopLocation(stop: RealmStopLocation): StopLocation { with(stop) { return StopLocation(stopid, type, lat, lon, idx, name) } } //=================================================================================== // Persistance related methods //=================================================================================== fun addFavourite(origin : StopLocation, dest : StopLocation, nick: String, bg : String){ realmInteractor.addFavourite(origin,dest,nick,bg) } fun getFavourites() = performViewAction {setFavourites(realmInteractor.getFavourites())} //=================================================================================== // Lifecycle Methods //=================================================================================== override fun onViewAttached() {} override fun onViewDetached() {} //Called from BasePresenter when view is detached override fun unsubscribe() { searchTripUc.unsubscribe() } //=================================================================================== // View Interface //=================================================================================== interface View : BaseView { fun showMessage(str : String) fun setFavourites(list : List<Favourite>) } }
apache-2.0
03749befa0c2e56bad285fc3ea941d3e
38.013514
182
0.539155
5.625731
false
false
false
false
yshrsmz/monotweety
app2/src/main/java/net/yslibrary/monotweety/ui/loginform/LoginFormViewModel.kt
1
9778
package net.yslibrary.monotweety.ui.loginform import com.codingfeline.twitter4kt.core.model.oauth1a.AccessToken import com.codingfeline.twitter4kt.core.model.oauth1a.RequestToken import com.codingfeline.twitter4kt.core.oauth1a.authorizationUrl import kotlinx.coroutines.launch import net.yslibrary.monotweety.base.CoroutineDispatchers import net.yslibrary.monotweety.data.auth.AuthFlow import net.yslibrary.monotweety.ui.arch.Action import net.yslibrary.monotweety.ui.arch.Effect import net.yslibrary.monotweety.ui.arch.GlobalAction import net.yslibrary.monotweety.ui.arch.Intent import net.yslibrary.monotweety.ui.arch.MviViewModel import net.yslibrary.monotweety.ui.arch.Processor import net.yslibrary.monotweety.ui.arch.State import net.yslibrary.monotweety.ui.arch.ULIEState import timber.log.Timber import javax.inject.Inject sealed class LoginFormIntent : Intent { object Initialize : LoginFormIntent() object OpenBrowser : LoginFormIntent() data class PinCodeUpdated(val value: String) : LoginFormIntent() object Authorize : LoginFormIntent() } sealed class LoginFormAction : Action { object Initialize : LoginFormAction() object LoadRequestToken : LoginFormAction() data class RequestTokenError(val error: Throwable) : LoginFormAction() data class RequestTokenLoaded(val token: RequestToken) : LoginFormAction() data class Authorize( val requestToken: RequestToken, val pinCode: String, ) : LoginFormAction() data class AccessTokenError(val error: Throwable) : LoginFormAction() data class AccessTokenLoaded(val token: AccessToken) : LoginFormAction() data class PinCodeUpdated(val value: String) : LoginFormAction() } sealed class LoginFormEffect : Effect { data class OpenBrowser(val url: String) : LoginFormEffect() object ToMain : LoginFormEffect() data class ShowError(val message: String?) : LoginFormEffect() } /** * +------+ * | Idle | * +------+ * | * | tap Open Browser * V * +---------------------+ +-----------------------+ * | LoadingRequestToken | ------------> | LoadRequestTokenError | * +---------------------+ <------------ +-----------------------+ * | A A * | go to Twitter | | * V | +-------------------+ * +----------------+ | re-request | * | WaitForPinCode | --+ | * +----------------+ | re-request * | | * | pincode entered | * V | * +-------------+ +----------------------+ * | Authorizing | ----------------------> | LoadAccessTokenError | * +-------------+ <---------------------- +----------------------+ * | * | AccessToken received * V * +----------+ * | Finished | * +----------+ */ enum class LoginFlowState { Idle, LoadingRequestToken, LoadRequestTokenError, WaitForPinCode, Authorizing, LoadAccessTokenError, Finished; fun isAtLeast(state: LoginFlowState): Boolean = compareTo(state) >= 0 fun isAtMost(state: LoginFlowState): Boolean = compareTo(state) <= 0 } data class LoginFormState( val state: ULIEState, val loginFlowState: LoginFlowState, val requestToken: RequestToken?, val accessToken: AccessToken?, val pinCode: String, ) : State { val pinCodeIsValid: Boolean by lazy { isValidPinCode(pinCode) } companion object { fun initialState(): LoginFormState { return LoginFormState( state = ULIEState.UNINITIALIZED, loginFlowState = LoginFlowState.Idle, requestToken = null, accessToken = null, pinCode = "", ) } } } class LoginFormProcessor @Inject constructor( private val authFlow: AuthFlow, dispatchers: CoroutineDispatchers, ) : Processor<LoginFormAction>( dispatchers = dispatchers, ) { override fun processAction(action: LoginFormAction) { when (action) { LoginFormAction.LoadRequestToken -> { loadRequestToken() } is LoginFormAction.Authorize -> { loadAccessToken(action.requestToken, action.pinCode) } LoginFormAction.Initialize, is LoginFormAction.RequestTokenLoaded, is LoginFormAction.AccessTokenLoaded, is LoginFormAction.RequestTokenError, is LoginFormAction.AccessTokenError, is LoginFormAction.PinCodeUpdated, -> { // no-op } } } private fun loadRequestToken() { launch { try { val token = authFlow.getRequestToken() put(LoginFormAction.RequestTokenLoaded(token)) } catch (e: Throwable) { Timber.e(e, "load request token error: $e.") put(LoginFormAction.RequestTokenError(e)) } } } private fun loadAccessToken(requestToken: RequestToken, pinCode: String) { launch { try { val token = authFlow.getAccessToken(requestToken, pinCode) put(LoginFormAction.AccessTokenLoaded(token)) } catch (e: Throwable) { Timber.e(e, "load access token error: $e.") put(LoginFormAction.AccessTokenError(e)) } } } } class LoginFormViewModel @Inject constructor( processor: LoginFormProcessor, dispatchers: CoroutineDispatchers, ) : MviViewModel<LoginFormIntent, LoginFormAction, LoginFormState, LoginFormEffect>( initialState = LoginFormState.initialState(), processor = processor, dispatchers = dispatchers, ) { override fun intentToAction(intent: LoginFormIntent, state: LoginFormState): Action { return when (intent) { LoginFormIntent.Initialize -> LoginFormAction.Initialize LoginFormIntent.OpenBrowser -> { when (state.loginFlowState) { LoginFlowState.Idle -> LoginFormAction.LoadRequestToken LoginFlowState.LoadingRequestToken -> GlobalAction.NoOp LoginFlowState.WaitForPinCode -> LoginFormAction.LoadRequestToken LoginFlowState.Authorizing -> GlobalAction.NoOp LoginFlowState.LoadRequestTokenError -> LoginFormAction.LoadRequestToken LoginFlowState.LoadAccessTokenError -> LoginFormAction.LoadRequestToken LoginFlowState.Finished -> GlobalAction.NoOp } } is LoginFormIntent.Authorize -> { if (state.pinCodeIsValid && state.loginFlowState == LoginFlowState.WaitForPinCode) { LoginFormAction.Authorize(state.requestToken!!, state.pinCode) } else GlobalAction.NoOp } is LoginFormIntent.PinCodeUpdated -> LoginFormAction.PinCodeUpdated(intent.value) } } override fun reduce(previousState: LoginFormState, action: LoginFormAction): LoginFormState { return when (action) { LoginFormAction.Initialize -> { previousState.copy( state = ULIEState.IDLE, loginFlowState = LoginFlowState.Idle, requestToken = null, accessToken = null, ) } LoginFormAction.LoadRequestToken -> { previousState.copy( state = ULIEState.IDLE, loginFlowState = LoginFlowState.LoadingRequestToken, requestToken = null, accessToken = null, ) } is LoginFormAction.RequestTokenLoaded -> { sendEffect(LoginFormEffect.OpenBrowser(url = action.token.authorizationUrl())) previousState.copy( state = ULIEState.IDLE, loginFlowState = LoginFlowState.WaitForPinCode, requestToken = action.token, ) } is LoginFormAction.RequestTokenError -> { sendEffect(LoginFormEffect.ShowError(action.error.message)) previousState.copy( state = ULIEState.ERROR(action.error), loginFlowState = LoginFlowState.LoadRequestTokenError ) } is LoginFormAction.PinCodeUpdated -> { previousState.copy( state = ULIEState.IDLE, pinCode = action.value ) } is LoginFormAction.Authorize -> { previousState.copy( state = ULIEState.IDLE, loginFlowState = LoginFlowState.Authorizing, accessToken = null, ) } is LoginFormAction.AccessTokenLoaded -> { sendEffect(LoginFormEffect.ToMain) previousState.copy( state = ULIEState.IDLE, loginFlowState = LoginFlowState.Finished, accessToken = action.token, ) } is LoginFormAction.AccessTokenError -> { sendEffect(LoginFormEffect.ShowError(action.error.message)) previousState.copy( state = ULIEState.ERROR(action.error), loginFlowState = LoginFlowState.LoadAccessTokenError ) } } } } private fun isValidPinCode(value: String): Boolean { return value.toIntOrNull(10) != null }
apache-2.0
7f2a6c7a2e6aa69ab88d66335fb2edeb
35.898113
100
0.573532
4.923464
false
false
false
false
xfournet/intellij-community
python/src/com/jetbrains/python/sdk/add/PyAddExistingCondaEnvPanel.kt
1
2308
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.sdk.add import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.ui.components.JBCheckBox import com.intellij.util.ui.FormBuilder import com.jetbrains.python.sdk.* import icons.PythonIcons import java.awt.BorderLayout import javax.swing.Icon /** * @author vlan */ class PyAddExistingCondaEnvPanel(private val project: Project?, private val existingSdks: List<Sdk>, override var newProjectPath: String?) : PyAddSdkPanel() { override val panelName = "Existing environment" override val icon: Icon = PythonIcons.Python.Condaenv private val sdkComboBox = PySdkPathChoosingComboBox(detectCondaEnvs(project, existingSdks) .filterNot { it.isAssociatedWithAnotherProject(project) }, null) private val makeSharedField = JBCheckBox("Make available to all projects") init { layout = BorderLayout() val formPanel = FormBuilder.createFormBuilder() .addLabeledComponent("Interpreter:", sdkComboBox) .addComponent(makeSharedField) .panel add(formPanel, BorderLayout.NORTH) } override fun validateAll() = listOfNotNull(validateSdkComboBox(sdkComboBox)) override fun getOrCreateSdk(): Sdk? { val sdk = sdkComboBox.selectedSdk return when (sdk) { is PyDetectedSdk -> sdk.setupAssociated(existingSdks, newProjectPath ?: project?.basePath)?.apply { if (!makeSharedField.isSelected) { associateWithProject(project, newProjectPath != null) } } else -> sdk } } }
apache-2.0
b13e5f7a888f024c7e14033f2dd775af
36.241935
114
0.688908
4.818372
false
false
false
false
Kotlin/dokka
plugins/javadoc/src/main/kotlin/org/jetbrains/dokka/javadoc/JavadocPageCreator.kt
1
10311
package org.jetbrains.dokka.javadoc import org.jetbrains.dokka.DokkaConfiguration.DokkaSourceSet import org.jetbrains.dokka.base.DokkaBase import org.jetbrains.dokka.base.signatures.SignatureProvider import org.jetbrains.dokka.base.transformers.pages.comments.DocTagToContentConverter import org.jetbrains.dokka.base.translators.documentables.firstSentenceBriefFromContentNodes import org.jetbrains.dokka.javadoc.pages.* import org.jetbrains.dokka.model.* import org.jetbrains.dokka.model.doc.Description import org.jetbrains.dokka.model.doc.Index import org.jetbrains.dokka.model.doc.Param import org.jetbrains.dokka.model.doc.TagWrapper import org.jetbrains.dokka.model.properties.PropertyContainer import org.jetbrains.dokka.model.properties.WithExtraProperties import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.plugability.plugin import org.jetbrains.dokka.plugability.querySingle import kotlin.reflect.KClass open class JavadocPageCreator(context: DokkaContext) { private val signatureProvider: SignatureProvider = context.plugin<DokkaBase>().querySingle { signatureProvider } private val documentationVersion = context.configuration.moduleVersion fun pageForModule(m: DModule): JavadocModulePageNode = JavadocModulePageNode( name = m.name.ifEmpty { "root" }, content = contentForModule(m), children = m.packages.map { pageForPackage(it) }, dri = setOf(m.dri), extra = ((m as? WithExtraProperties<DModule>)?.extra ?: PropertyContainer.empty()) ) fun pageForPackage(p: DPackage) = JavadocPackagePageNode(p.name, contentForPackage(p), setOf(p.dri), listOf(p), p.classlikes.mapNotNull { pageForClasslike(it) } ) fun pageForClasslike(c: DClasslike): JavadocClasslikePageNode? { return c.highestJvmSourceSet?.let { jvm -> @Suppress("UNCHECKED_CAST") val extra = ((c as? WithExtraProperties<Documentable>)?.extra ?: PropertyContainer.empty()) val children = c.classlikes.mapNotNull { pageForClasslike(it) } JavadocClasslikePageNode( name = c.dri.classNames.orEmpty(), content = contentForClasslike(c), dri = setOf(c.dri), brief = c.brief(), signature = signatureForNode(c, jvm), description = c.descriptionToContentNodes(), constructors = (c as? WithConstructors)?.constructors?.mapNotNull { it.toJavadocFunction() }.orEmpty(), methods = c.functions.mapNotNull { it.toJavadocFunction() }, entries = (c as? DEnum)?.entries?.map { JavadocEntryNode( it.dri, it.name, signatureForNode(it, jvm), it.descriptionToContentNodes(jvm), PropertyContainer.withAll(it.indexesInDocumentation()) ) }.orEmpty(), classlikes = children, properties = c.properties.map { JavadocPropertyNode( it.dri, it.name, signatureForNode(it, jvm), it.descriptionToContentNodes(jvm), PropertyContainer.withAll(it.indexesInDocumentation()) ) }, documentables = listOf(c), children = children, extra = extra + c.indexesInDocumentation() ) } } private fun contentForModule(m: DModule): JavadocContentNode = JavadocContentGroup( setOf(m.dri), JavadocContentKind.OverviewSummary, m.sourceSets.toDisplaySourceSets() ) { title(m.name, m.descriptionToContentNodes(), documentationVersion, dri = setOf(m.dri), kind = ContentKind.Main) leafList(setOf(m.dri), ContentKind.Packages, JavadocList( "Packages", "Package", m.packages.sortedBy { it.packageName }.map { p -> RowJavadocListEntry( LinkJavadocListEntry(p.name, setOf(p.dri), JavadocContentKind.PackageSummary, sourceSets), p.brief() ) } )) } private fun contentForPackage(p: DPackage): JavadocContentNode = JavadocContentGroup( setOf(p.dri), JavadocContentKind.PackageSummary, p.sourceSets.toDisplaySourceSets() ) { title("Package ${p.name}", p.descriptionToContentNodes(), dri = setOf(p.dri), kind = ContentKind.Packages) fun allClasslikes(c: DClasslike): List<DClasslike> = c.classlikes.flatMap { allClasslikes(it) } + c val rootList = p.classlikes.map { allClasslikes(it) }.flatten().groupBy { it::class }.map { (key, value) -> JavadocList(key.tabTitle, key.colTitle, value.map { c -> RowJavadocListEntry( LinkJavadocListEntry(c.name ?: "", setOf(c.dri), JavadocContentKind.Class, sourceSets), c.brief() ) }) } rootList(setOf(p.dri), JavadocContentKind.Class, rootList) } private val KClass<out DClasslike>.colTitle: String get() = when (this) { DClass::class -> "Class" DObject::class -> "Object" DAnnotation::class -> "Annotation" DEnum::class -> "Enum" DInterface::class -> "Interface" else -> "" } private val KClass<out DClasslike>.tabTitle: String get() = "$colTitle Summary" private fun contentForClasslike(c: DClasslike): JavadocContentNode = JavadocContentGroup( setOf(c.dri), JavadocContentKind.Class, c.sourceSets.toDisplaySourceSets() ) { title( c.name.orEmpty(), c.brief(), documentationVersion, parent = c.dri.packageName, dri = setOf(c.dri), kind = JavadocContentKind.Class ) } private fun DFunction.toJavadocFunction() = highestJvmSourceSet?.let { jvm -> JavadocFunctionNode( name = name, dri = dri, signature = signatureForNode(this, jvm), brief = brief(jvm), description = descriptionToContentNodes(jvm), parameters = parameters.mapNotNull { val signature = signatureForNode(it, jvm) signature.modifiers?.let { type -> JavadocParameterNode( name = it.name.orEmpty(), type = type, description = it.brief(), typeBound = it.type, dri = it.dri, extra = PropertyContainer.withAll(it.indexesInDocumentation()) ) } }, extra = extra + indexesInDocumentation() ) } private val Documentable.highestJvmSourceSet get() = sourceSets.let { sources -> sources.firstOrNull { it != expectPresentInSet } ?: sources.firstOrNull() } private inline fun <reified T : TagWrapper> Documentable.findNodeInDocumentation(sourceSetData: DokkaSourceSet?): T? = documentation[sourceSetData]?.firstChildOfTypeOrNull<T>() private fun Documentable.descriptionToContentNodes(sourceSet: DokkaSourceSet? = highestJvmSourceSet) = contentNodesFromType<Description>(sourceSet) private fun DParameter.paramsToContentNodes(sourceSet: DokkaSourceSet? = highestJvmSourceSet) = contentNodesFromType<Param>(sourceSet) private inline fun <reified T : TagWrapper> Documentable.contentNodesFromType(sourceSet: DokkaSourceSet?) = findNodeInDocumentation<T>(sourceSet)?.let { DocTagToContentConverter().buildContent( it.root, DCI(setOf(dri), JavadocContentKind.OverviewSummary), sourceSets.toSet() ) }.orEmpty() fun List<ContentNode>.nodeForJvm(jvm: DokkaSourceSet): ContentNode = firstOrNull { jvm.sourceSetID in it.sourceSets.sourceSetIDs } ?: throw IllegalStateException("No source set found for ${jvm.sourceSetID} ") private fun Documentable.brief(sourceSet: DokkaSourceSet? = highestJvmSourceSet): List<ContentNode> = firstSentenceBriefFromContentNodes(descriptionToContentNodes(sourceSet)) private fun DParameter.brief(sourceSet: DokkaSourceSet? = highestJvmSourceSet): List<ContentNode> = firstSentenceBriefFromContentNodes(paramsToContentNodes(sourceSet).dropWhile { it is ContentDRILink }) private fun ContentNode.asJavadocNode(): JavadocSignatureContentNode = (this as ContentGroup).firstChildOfTypeOrNull<JavadocSignatureContentNode>() ?: throw IllegalStateException("No content for javadoc signature found") private fun signatureForNode(documentable: Documentable, sourceSet: DokkaSourceSet): JavadocSignatureContentNode = signatureProvider.signature(documentable).nodeForJvm(sourceSet).asJavadocNode() private fun Documentable.indexesInDocumentation(): JavadocIndexExtra { val indexes = documentation[highestJvmSourceSet]?.withDescendants()?.filterIsInstance<Index>()?.toList().orEmpty() return JavadocIndexExtra( indexes.map { ContentGroup( children = DocTagToContentConverter().buildContent( it, DCI(setOf(dri), JavadocContentKind.OverviewSummary), sourceSets.toSet() ), dci = DCI(setOf(dri), JavadocContentKind.OverviewSummary), sourceSets = sourceSets.toDisplaySourceSets(), style = emptySet(), extra = PropertyContainer.empty() ) } ) } }
apache-2.0
28bb6e617b419040d88dd8772518ef82
43.443966
123
0.601881
5.061856
false
false
false
false
andycondon/pathfinder-gps
src/test/kotlin/io/frontierrobotics/gps/SpeedSpecs.kt
1
2009
package io.frontierrobotics.gps import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import test.assertBetween import kotlin.test.assertEquals class SpeedSpecs : Spek({ describe("a speed in meters per second") { val speed = Speed.ofMetersPerSecond(98.5) on("calling toKilometersPerHour") { it("should return the correct result") { assertEquals(354.6, speed.toKilometersPerHour()) } } on("calling toMilesPerHour") { it("should return the correct result") { assertBetween(220.3381, 220.3382, speed.toMilesPerHour()) } } on("calling toKnots") { val knots = speed.toKnots() it("should return the correct result") { assertBetween(191.46863, 191.4687, knots) } } } describe("a speed in miles per hour") { val speed = Speed.ofMilesPerHour(65.0) on("calling toMetersPerSecond") { val metersPerSecond = speed.toMetersPerSecond() it("should return the correct result") { assertEquals(29.0576, metersPerSecond) } } on("calling toKilometersPerHour") { val kilometersPerHour = speed.toKilometersPerHour() it("should return the correct result") { assertBetween(104.607, 104.6074, kilometersPerHour) } } } describe("a speed in knots") { val speed = Speed.ofKnots(17.0) on("calling toMetersPerSecond") { val metersPerSecond = speed.toMetersPerSecond() it("should return the correct result") { assertBetween(8.74556, 8.745563, metersPerSecond) } } } })
mit
aa6ef4a8e3617e1dee66b0e5a0e53b69
25.090909
73
0.545545
4.348485
false
false
false
false
javiersantos/PiracyChecker
app/src/main/java/com/github/javiersantos/piracychecker/demo/KotlinActivity.kt
1
4641
package com.github.javiersantos.piracychecker.demo import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.widget.RadioGroup import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.github.javiersantos.piracychecker.allow import com.github.javiersantos.piracychecker.callback import com.github.javiersantos.piracychecker.doNotAllow import com.github.javiersantos.piracychecker.enums.Display import com.github.javiersantos.piracychecker.enums.InstallerID import com.github.javiersantos.piracychecker.onError import com.github.javiersantos.piracychecker.piracyChecker import com.github.javiersantos.piracychecker.utils.apkSignatures @Suppress("unused") class KotlinActivity : AppCompatActivity() { private var piracyCheckerDisplay = Display.DIALOG override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) val radioDisplay = findViewById<RadioGroup>(R.id.radio_display) setSupportActionBar(toolbar) radioDisplay.setOnCheckedChangeListener { _, i -> when (i) { R.id.radio_dialog -> piracyCheckerDisplay = Display.DIALOG R.id.radio_activity -> piracyCheckerDisplay = Display.ACTIVITY } } // Show APK signature apkSignatures.forEach { Log.e("Signature", it) } } fun toGithub() { startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("https://github.com/javiersantos/piracyChecker"))) } fun verifySignature() { piracyChecker { display(piracyCheckerDisplay) enableSigningCertificates("478yYkKAQF+KST8y4ATKvHkYibo=") // Wrong signature //enableSigningCertificates("VHZs2aiTBiap/F+AYhYeppy0aF0=") // Right signature }.start() } fun readSignature() { val dialogMessage = StringBuilder() apkSignatures.forEach { Log.e("Signature", it) dialogMessage.append("* ").append(it).append("\n") } AlertDialog.Builder(this) .setTitle("APK") .setMessage(dialogMessage.toString()) .show() } fun verifyInstallerId() { piracyChecker { display(piracyCheckerDisplay) enableInstallerId(InstallerID.GOOGLE_PLAY) }.start() } fun verifyUnauthorizedApps() { piracyChecker { display(piracyCheckerDisplay) enableUnauthorizedAppsCheck() //blockIfUnauthorizedAppUninstalled("license_checker", "block") }.start() } fun verifyStores() { piracyChecker { display(piracyCheckerDisplay) enableStoresCheck() }.start() } fun verifyDebug() { piracyChecker { display(piracyCheckerDisplay) enableDebugCheck() callback { allow { // Do something when the user is allowed to use the app } doNotAllow { piracyCheckerError, pirateApp -> // You can either do something specific when the user is not allowed to use the app // Or manage the error, using the 'error' parameter, yourself (Check errors at {@link PiracyCheckerError}). // Additionally, if you enabled the check of pirate apps and/or third-party stores, the 'app' param // is the app that has been detected on device. App can be null, and when null, it means no pirate app or store was found, // or you disabled the check for those apps. // This allows you to let users know the possible reasons why license is been invalid. } onError { error -> // This method is not required to be implemented/overriden but... // You can either do something specific when an error occurs while checking the license, // Or manage the error, using the 'error' parameter, yourself (Check errors at {@link PiracyCheckerError}). } } }.start() } fun verifyEmulator() { piracyChecker { display(piracyCheckerDisplay) enableEmulatorCheck(false) }.start() } }
apache-2.0
2079ca79fddefa1ea0ae9c2515694f78
36.136
142
0.618832
4.885263
false
false
false
false
http4k/http4k
http4k-security/oauth/src/main/kotlin/org/http4k/security/oauth/server/AuthRequestWithRequestAuthRequestExtractor.kt
1
5665
package org.http4k.security.oauth.server import dev.forkhandles.result4k.Failure import dev.forkhandles.result4k.Result import dev.forkhandles.result4k.Success import dev.forkhandles.result4k.flatMap import dev.forkhandles.result4k.mapFailure import dev.forkhandles.result4k.onFailure import org.http4k.core.Request import org.http4k.security.ResponseType.Code import org.http4k.security.oauth.server.request.RequestJWTValidator import org.http4k.security.oauth.server.request.RequestObject import org.http4k.security.oauth.server.request.RequestObjectExtractor.extractRequestObjectFromJwt class AuthRequestWithRequestAuthRequestExtractor( private val requestJWTValidator: RequestJWTValidator, private val combineAuthRequestRequestStrategy: CombineAuthRequestRequestStrategy ) : AuthRequestExtractor { override fun extract(request: Request): Result<AuthRequest, InvalidAuthorizationRequest> { return AuthRequestFromQueryParameters.extract(request).flatMap { authRequest -> val requestJwtContainer = authRequest.request if (requestJwtContainer != null) { val requestJwtValidationError = requestJWTValidator.validate(authRequest.client, requestJwtContainer) if (requestJwtValidationError != null) { Failure(requestJwtValidationError) } else { extractRequestObjectFromJwt(requestJwtContainer.value) .mapFailure { InvalidAuthorizationRequest("Query 'request' is invalid") } .flatMap { requestObject -> combineAuthRequestAndRequestObject(authRequest, requestObject) } } } else { Success(authRequest) } } } private fun combineAuthRequestAndRequestObject( authRequest: AuthRequest, requestObject: RequestObject ): Result<AuthRequest, InvalidAuthorizationRequest> { if (requestObject.client != null && authRequest.client != requestObject.client) { return Failure(InvalidAuthorizationRequest("'client_id' is invalid")) } return Success(authRequest.copy( requestObject = requestObject, redirectUri = nonNullValueIfExistsOrErrorIfNotEqual( authRequest.redirectUri, requestObject.redirectUri ).onFailure { return it }, state = nonNullValueIfExistsOrErrorIfNotEqual( authRequest.state, requestObject.state ).onFailure { return it }, nonce = nonNullValueIfExistsOrErrorIfNotEqual( authRequest.nonce, requestObject.nonce ).onFailure { return it }, responseType = nonNullValueIfExistsOrErrorIfNotEqual( authRequest.responseType, requestObject.responseType ).onFailure { return it } ?: Code, responseMode = nonNullValueIfExistsOrErrorIfNotEqual( authRequest.responseMode, requestObject.responseMode ).onFailure { return it }, scopes = nonEmptyScopeIfExistsOrErrorIfNotEqual(authRequest.scopes, requestObject.scope) .onFailure { return it } )) } private fun <T> nonNullValueIfExistsOrErrorIfNotEqual( authRequestValue: T?, requestObjectValue: T? ): Result<T?, InvalidAuthorizationRequest> { if (authRequestValue != null && requestObjectValue != null && authRequestValue != requestObjectValue) { return Failure(InvalidAuthorizationRequest("request object is invalid")) } return Success(combineAuthRequestRequestStrategy.combine(authRequestValue, requestObjectValue)) } private fun nonEmptyScopeIfExistsOrErrorIfNotEqual( authRequestValue: List<String>, requestObjectValue: List<String> ): Result<List<String>, InvalidAuthorizationRequest> { if (authRequestValue.isNotEmpty() && requestObjectValue.isNotEmpty() && authRequestValue.toSet() != requestObjectValue.toSet()) { return Failure(InvalidAuthorizationRequest("request object is invalid")) } return Success(combineAuthRequestRequestStrategy.combine(authRequestValue, requestObjectValue)) } sealed class CombineAuthRequestRequestStrategy { object Combine : CombineAuthRequestRequestStrategy() { override fun <T> combine(authRequestValue: T?, requestObjectValue: T?): T? = authRequestValue ?: requestObjectValue override fun <T> combine(authRequestValue: List<T>, requestObjectValue: List<T>): List<T> = if (authRequestValue.isNotEmpty()) authRequestValue else requestObjectValue } object AuthRequestOnly : CombineAuthRequestRequestStrategy() { override fun <T> combine(authRequestValue: T?, requestObjectValue: T?): T? = authRequestValue override fun <T> combine(authRequestValue: List<T>, requestObjectValue: List<T>): List<T> = authRequestValue } object RequestObjectOnly : CombineAuthRequestRequestStrategy() { override fun <T> combine(authRequestValue: T?, requestObjectValue: T?): T? = requestObjectValue override fun <T> combine(authRequestValue: List<T>, requestObjectValue: List<T>): List<T> = requestObjectValue } abstract fun <T> combine(authRequestValue: T?, requestObjectValue: T?): T? abstract fun <T> combine(authRequestValue: List<T>, requestObjectValue: List<T>): List<T> } }
apache-2.0
cb60397df3792fedf7643f483b9c258c
45.056911
137
0.674492
5.379867
false
false
false
false
alashow/music-android
modules/core-playback/src/main/java/tm/alashow/datmusic/playback/models/QueueState.kt
1
402
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.playback.models import kotlinx.serialization.Serializable @Serializable data class QueueState( val queue: List<String>, val currentIndex: Int = 0, val title: String? = null, val repeatMode: Int = 0, val shuffleMode: Int = 0, val seekPosition: Long = 0, val state: Int = 0 )
apache-2.0
79ead9d0a8546538294a10e9a48d2916
21.333333
43
0.681592
3.688073
false
false
false
false
cemrich/zapp
app/src/main/java/de/christinecoenen/code/zapp/utils/system/IntentHelper.kt
1
2214
package de.christinecoenen.code.zapp.utils.system import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import de.christinecoenen.code.zapp.R object IntentHelper { /** * Open the given url in a new (external) activity. If no app is found * that can handle this intent, a system chooser is shown. * * @param context * @param url */ @JvmStatic fun openUrl(context: Context, url: String?) { val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) try { context.startActivity(browserIntent) } catch (e: ActivityNotFoundException) { context.startActivity(Intent.createChooser(browserIntent, context.getString(R.string.action_open))) } } /** * Opens the default mail app. If no app is found that can handle * this intent, a a system chooser is shown. * * @param context * @param mail receiver mail address * @param subject mail subject line */ fun sendMail(context: Context, mail: String, subject: String?) { val feedbackIntent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$mail")) feedbackIntent.putExtra(Intent.EXTRA_SUBJECT, subject) try { context.startActivity(feedbackIntent) } catch (e: ActivityNotFoundException) { context.startActivity(Intent.createChooser(feedbackIntent, context.getString(R.string.action_send_mail))) } } /** * Shares the given url as plain text (e.g. for messengers, some players, browsers, etc.). */ fun shareLink(context: Context, url: String, title: String) { val playVideoIntent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_SUBJECT, title) putExtra(Intent.EXTRA_TEXT, url) putExtra(Intent.EXTRA_TITLE, title) } context.startActivity( Intent.createChooser(playVideoIntent, context.getString(R.string.action_share)) ) } /** * */ fun playVideo(context: Context, url: String, title: String) { val playVideoIntent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(Uri.parse(url), "video/*") putExtra(Intent.EXTRA_TITLE, title) } context.startActivity( Intent.createChooser(playVideoIntent, context.getString(R.string.action_open)) ) } }
mit
47085540de352128e486b8594b909a39
27.753247
108
0.726287
3.582524
false
false
false
false
Aidanvii7/Toolbox
adapterviews-databinding-recyclerview/src/main/java/com/aidanvii/toolbox/adapterviews/databinding/recyclerview/BindableItemDecoration.kt
1
2500
package com.aidanvii.toolbox.adapterviews.databinding.recyclerview; import android.graphics.Canvas import android.graphics.Rect import androidx.recyclerview.widget.RecyclerView import android.view.View import com.aidanvii.toolbox.actionStub import com.aidanvii.toolbox.adapterviews.databinding.BindableAdapterItem import com.aidanvii.toolbox.children import com.aidanvii.toolbox.unchecked abstract class BindableItemDecoration<AdapterItem : BindableAdapterItem> : RecyclerView.ItemDecoration() { protected abstract fun getItemOffsets(adapterItem: AdapterItem, outRect: Rect, layoutParams: RecyclerView.LayoutParams, state: RecyclerView.State) protected abstract fun onDraw(adapterItem: AdapterItem, canvas: Canvas, state: RecyclerView.State) override fun onDraw(canvas: Canvas, recyclerView: RecyclerView, state: RecyclerView.State) { for (childView in recyclerView.children) { onAdapter(recyclerView) { onDraw( adapterItem = items[recyclerView.getChildAdapterPosition(childView)], canvas = canvas, state = state ) } } } override fun getItemOffsets(outRect: Rect, view: View, recyclerView: RecyclerView, state: RecyclerView.State) { onAdapter(recyclerView) { getItemOffsets( adapterItem = items[recyclerView.getChildAdapterPosition(view)], outRect = outRect, layoutParams = view.layoutParams as RecyclerView.LayoutParams, state = state ) } } @Suppress(unchecked) private inline fun onAdapter( recyclerView: RecyclerView, block: BindingRecyclerViewAdapter<AdapterItem>.() -> Unit ) { recyclerView.adapter.let { adapter -> when (adapter) { null -> actionStub is BindingRecyclerViewAdapter<*> -> (adapter as BindingRecyclerViewAdapter<AdapterItem>).block() else -> throwWrongAdapterType(adapter) } } } private fun throwWrongAdapterType(unsupportedAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>): Nothing { throw UnsupportedOperationException( """ cannot attach ${this::class.java.simpleName} to ${unsupportedAdapter::class.java.simpleName}, ${unsupportedAdapter::class.java.simpleName} must extend BindingRecyclerViewAdapter. """ ) } }
apache-2.0
37a294c7c43bd4c5cad7041e5e3cb9af
38.698413
150
0.6684
5.567929
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/map/tangram/MarkerManager.kt
1
6787
package de.westnordost.streetcomplete.map.tangram import android.graphics.drawable.BitmapDrawable import com.mapzen.tangram.LngLat import com.mapzen.tangram.MapController import com.mapzen.tangram.geometry.Polygon import com.mapzen.tangram.geometry.Polyline import de.westnordost.streetcomplete.data.osm.mapdata.LatLon import kotlinx.coroutines.suspendCancellableCoroutine import java.util.concurrent.ConcurrentLinkedQueue import kotlin.coroutines.Continuation import kotlin.coroutines.resume /** Controls the marker management. Use in place of the Tangram MapController.addMarker, pickMarker * etc. methods to enable markers that survive a scene reload. * * The Tangram Markers are wrapped into own Marker objects with a similar interface that are able * to recreate the Tangram Markers after the scene has successfully loaded. * * See https://github.com/tangrams/tangram-es/issues/1756 * */ class MarkerManager(private val c: MapController) { private var markerIdCounter = 0L private val markers = mutableMapOf<Long, Marker>() private val markerPickContinuations = ConcurrentLinkedQueue<Continuation<MarkerPickResult?>>() init { c.setMarkerPickListener { tangramMarkerPickResult: com.mapzen.tangram.MarkerPickResult? -> val tangramMarkerId = tangramMarkerPickResult?.marker?.markerId var markerPickResult: MarkerPickResult? = null if (tangramMarkerId != null) { val marker = markers.values.find { it.tangramMarker?.markerId == tangramMarkerId } if (marker != null) { markerPickResult = MarkerPickResult(marker, tangramMarkerPickResult.coordinates.toLatLon()) } } markerPickContinuations.poll()?.resume(markerPickResult) } } suspend fun pickMarker(posX: Float, posY: Float): MarkerPickResult? = suspendCancellableCoroutine { cont -> markerPickContinuations.offer(cont) cont.invokeOnCancellation { markerPickContinuations.remove(cont) } c.pickMarker(posX, posY) } fun addMarker(): Marker { val marker = Marker(markerIdCounter++, c.addMarker()) markers[marker.markerId] = marker return marker } fun removeMarker(markerId: Long): Boolean { val marker = markers.remove(markerId) ?: return false val tangramMarkerId = marker.tangramMarker?.markerId if (tangramMarkerId != null) { c.removeMarker(tangramMarkerId) } return true } fun removeAllMarkers() { markers.clear() c.removeAllMarkers() } fun recreateMarkers() { for (marker in markers.values) { marker.tangramMarker = c.addMarker() } } fun invalidateMarkers() { for (marker in markers.values) { marker.tangramMarker = null } } } /** Wrapper around com.mapzen.tangram.Marker * * Tangram Markers are invalidated and can't be used anymore on each scene update. This class keeps * the necessary data to automatically reinstantiate them after the scene update is done. * */ class Marker(val markerId: Long, tangramMarker: com.mapzen.tangram.Marker) { internal var tangramMarker: com.mapzen.tangram.Marker? = null set(value) { field = value if (value != null) { value.isVisible = isVisible drawOrder?.let { value.setDrawOrder(it) } stylingFromPath?.let { value.setStylingFromPath(it) } stylingFromString?.let { value.setStylingFromString(it) } point?.let { val duration = pointEaseDuration val ease = pointEaseType if (duration != null && ease != null) { value.setPointEased(it, duration, ease) } else { value.setPoint(it) } } value.setPolyline(polyline) value.setPolygon(polygon) drawableId?.let { value.setDrawable(it) } drawable?.let { value.setDrawable(it) } } drawOrder } init { this.tangramMarker = tangramMarker } var isVisible: Boolean set(value) { _isVisible = value } get() = _isVisible != false // this construct is necessary because isVisible is not initialized to its initial value yet // when tangramMarker is set in the constructor. But in the constructor, tangramMarker.isVisible // is set to isVisible. private var _isVisible: Boolean? = null set(value) { field = value tangramMarker?.isVisible = value != false } var userData: Any? = null private var stylingFromPath: String? = null private var stylingFromString: String? = null private var drawOrder: Int? = null private var pointEaseDuration: Int? = null private var pointEaseType: MapController.EaseType? = null private var point: LngLat? = null private var polyline: Polyline? = null private var polygon: Polygon? = null private var drawable: BitmapDrawable? = null private var drawableId: Int? = null fun setStylingFromPath(stylingFromPath: String) { this.stylingFromPath = stylingFromPath tangramMarker?.setStylingFromPath(stylingFromPath) } fun setStylingFromString(stylingFromString: String) { this.stylingFromString = stylingFromString tangramMarker?.setStylingFromString(stylingFromString) } fun setDrawOrder(drawOrder: Int) { this.drawOrder = drawOrder tangramMarker?.setDrawOrder(drawOrder) } fun setPointEased(point: LatLon?, duration: Int, ease: MapController.EaseType) { val lngLat = point?.toLngLat() this.point = lngLat this.pointEaseDuration = duration this.pointEaseType = ease tangramMarker?.setPointEased(lngLat, duration, ease) } fun setPoint(point: LatLon) { val lngLat = point.toLngLat() this.point = lngLat tangramMarker?.setPoint(lngLat) } fun setPolyline(polyline: Polyline?) { this.polyline = polyline tangramMarker?.setPolyline(polyline) } fun setPolygon(polygon: Polygon?) { this.polygon = polygon tangramMarker?.setPolygon(polygon) } fun setDrawable(drawableId: Int) { this.drawableId = drawableId tangramMarker?.setDrawable(drawableId) } fun setDrawable(drawable: BitmapDrawable) { this.drawable = drawable tangramMarker?.setDrawable(drawable) } } class MarkerPickResult internal constructor( val marker: Marker, val coordinates: LatLon )
gpl-3.0
5cc57abca543353a871f6371403d5358
32.766169
111
0.651245
4.592016
false
false
false
false
BrianLusina/MovieReel
app/src/main/kotlin/com/moviereel/ui/base/BaseFragment.kt
1
4225
package com.moviereel.ui.base import android.content.Context import android.os.Bundle import android.support.annotation.StringRes import android.support.v4.app.Fragment import android.view.View import com.moviereel.di.components.ActivityComponent import org.jetbrains.anko.AnkoLogger /** * @author lusinabrian on 01/04/17 */ abstract class BaseFragment : Fragment(), BaseView, AnkoLogger{ /** * Gets the base activity this fragment is attached to * @return [BaseActivity] */ var baseActivity: BaseActivity? = null private set override fun onAttach(context: Context?) { super.onAttach(context) if (context is BaseActivity) { val mBaseActivity = context this.baseActivity = mBaseActivity mBaseActivity.onFragmentAttached() } } /** * Called to do initial creation of a fragment. This is called after * [Fragment.onAttach] and before * [Fragment.onCreateView]. * * * * Note that this can be called while the fragment's activity is * still in the process of being created. As such, you can not rely * on things like the activity's content view hierarchy being initialized * at this point. If you want to do work once the activity itself is * created, see [.onActivityCreated]. * * * * Any restored child fragments will be created before the base * `Fragment.onCreate` method returns. * @param savedInstanceState If the fragment is being re-created from * * a previous saved state, this is the state. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } /** * Checks if there is network connected * Returns True if the device is connected to a network, false otherwise * @return [Boolean] */ override val isNetworkConnected: Boolean get() = baseActivity != null && baseActivity!!.isNetworkConnected /** * Hides keyboard */ override fun hideKeyboard() { if (baseActivity != null) { baseActivity!!.hideKeyboard() } } /** * Shows a snackbar if an error has been encountered * @param message the message to display in the snackbar * * * @param length how long the snack bar should be displayed */ override fun onErrorSnackBar(message: String, length: Int) { if (baseActivity != null) { baseActivity!!.onErrorSnackBar(message, length) } } override fun showNetworkErrorSnackbar(message: String, length: Int) { if (baseActivity != null) { baseActivity!!.showNetworkErrorSnackbar(message, length) } } override fun showNetworkErrorSnackbar(@StringRes message: Int, length: Int) { showNetworkErrorSnackbar(getString(message), length) } /** * Override of [.onErrorSnackBar] * @param resId * * * @param length */ override fun onErrorSnackBar(@StringRes resId: Int, length: Int) { if (baseActivity != null) { baseActivity!!.onErrorSnackBar(resId, length) } } override fun onDetach() { baseActivity = null super.onDetach() } /** * Gets the activity component of the activity this fragment is attached to * @return [ActivityComponent] */ val activityComponent: ActivityComponent get() = baseActivity!!.activityComponent!! /** * Used to setup views in this fragment */ protected abstract fun setUp(view: View) /** * before destroying the fragment, check if the attached view in the hierarchy are still bound and * unbind them */ override fun onDestroy() { super.onDestroy() } /** * Callback interface for this fragment */ interface Callback { /** * Callback for when a fragment is attached to an activity */ fun onFragmentAttached() /** * Callback for when a fragment is detached from an activity * @param tag the fragment tag to detach */ fun onFragmentDetached(tag: String) } }
mit
47a399f961846e8904e69dd90d5fc0a7
27.547297
102
0.629586
4.95892
false
false
false
false
binaryfoo/emv-bertlv
src/test/java/io/github/binaryfoo/decoders/apdu/GenerateACAPDUDecoderTest.kt
1
2612
package io.github.binaryfoo.decoders.apdu import io.github.binaryfoo.DecodedData import io.github.binaryfoo.EmvTags import io.github.binaryfoo.decoders.DecodeSession import io.github.binaryfoo.decoders.annotator.backgroundOf import org.hamcrest.core.Is.`is` import org.junit.Assert.assertThat import org.junit.Test class GenerateACAPDUDecoderTest { @Test fun testDecode() { val input = "80AE50002B00000001000100000000000000020000000000003612031500000EEC8522000000000000000000005E030000" val session = DecodeSession() session.tagMetaData = EmvTags.METADATA session.put(EmvTags.CDOL_1, "9F02069F03069F090295055F2A029A039C019F37049F35019F45029F4C089F3403") val startIndex = 6 val decoded = GenerateACAPDUDecoder().decode(input, startIndex, session) assertThat(decoded.rawData, `is`("C-APDU: Generate AC (TC+CDA)")) assertThat(decoded.children.first(), `is`(DecodedData(EmvTags.AMOUNT_AUTHORIZED, "9F02 (amount authorized)", "000000010001", startIndex + 5, startIndex + 11))) val expectedDecodedCVMResults = EmvTags.METADATA.get(EmvTags.CVM_RESULTS).decoder.decode("5E0300", startIndex + 45, DecodeSession()) assertThat(decoded.children.last(), `is`(DecodedData(EmvTags.CVM_RESULTS, "9F34 (CVM Results - Cardholder Verification Results)", "5E0300", startIndex + 45, startIndex + 48, expectedDecodedCVMResults, backgroundOf("How was the card holder verified? Did this check succeed?")))) } @Test fun testDecodeSecondGenerateAC() { val first = "80AE80002B000000001000000000000000000280000080000036120316008221F60122000000000000000000005E030000" val second = "80AE40001D11223344556677880000303080000080008221F601000000000000000000" val session = DecodeSession() session.tagMetaData = EmvTags.METADATA session.put(EmvTags.CDOL_1, "9F02069F03069F090295055F2A029A039C019F37049F35019F45029F4C089F3403") session.put(EmvTags.CDOL_2, "910A8A0295059F37049F4C08") val firstDecoded = GenerateACAPDUDecoder().decode(first, 0, session) assertThat(firstDecoded.rawData, `is`("C-APDU: Generate AC (ARQC)")) val secondDecoded = GenerateACAPDUDecoder().decode(second, 0, session) assertThat(secondDecoded.rawData, `is`("C-APDU: Generate AC (TC)")) assertThat(secondDecoded.children.first(), `is`(DecodedData(EmvTags.ISSUER_AUTHENTICATION_DATA, "91 (issuer authentication data)", "11223344556677880000", 5, 15))) assertThat(secondDecoded.children.last(), `is`(DecodedData(EmvTags.ICC_DYNAMIC_NUMBER, "9F4C (ICC dynamic number)", "0000000000000000", 26, 34, backgroundReading = backgroundOf("Nonce generated by the chip")))) } }
mit
03d16d9b53bdedefa48cc54420bdcc62
55.782609
281
0.780628
3.544098
false
true
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/asyncs/CompletableFuturex.kt
1
1619
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ @file:JvmName("CompletableFuturex") package debop4k.core.asyncs import java.util.concurrent.* import java.util.function.* @JvmField val DefaultExecutor: ForkJoinPool = ForkJoinPool.commonPool() @JvmOverloads inline fun runAsync(crossinline body: () -> Unit, executor: Executor = DefaultExecutor): CompletableFuture<Void> = CompletableFuture.runAsync(Runnable { body() }, executor) @JvmOverloads inline fun <T> supplyAsync(crossinline supplier: () -> T, executor: Executor = DefaultExecutor): CompletableFuture<T> = CompletableFuture.supplyAsync(Supplier { supplier() }, executor) fun <T> completedFuture(result: T): CompletableFuture<T> = CompletableFuture.completedFuture(result) fun allOfFutures(vararg futures: CompletableFuture<*>): CompletableFuture<Void> = CompletableFuture.allOf(*futures) fun anyOfFutures(vararg futures: CompletableFuture<*>): CompletableFuture<Any> = CompletableFuture.anyOf(*futures)
apache-2.0
05cffa23a74f29f8d331b2069db591cf
35.795455
86
0.735639
4.497222
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/fragment/ForumFragment.kt
1
4410
package me.ykrank.s1next.view.fragment import android.content.Context import android.net.Uri import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import com.github.ykrank.androidtools.ui.vm.LoadingViewModel import io.reactivex.Single import io.rx_cache2.DynamicKey import io.rx_cache2.EvictDynamicKey import me.ykrank.s1next.App import me.ykrank.s1next.R import me.ykrank.s1next.data.api.Api import me.ykrank.s1next.data.api.model.collection.ForumGroups import me.ykrank.s1next.data.api.model.wrapper.ForumGroupsWrapper import me.ykrank.s1next.util.IntentUtil import me.ykrank.s1next.util.JsonUtil import me.ykrank.s1next.view.activity.SearchActivity import me.ykrank.s1next.view.adapter.ForumRecyclerViewAdapter import me.ykrank.s1next.view.internal.ToolbarDropDownInterface /** * A Fragment represents forum list. */ class ForumFragment : BaseRecyclerViewFragment<ForumGroupsWrapper>(), ToolbarDropDownInterface.OnItemSelectedListener { private lateinit var mRecyclerAdapter: ForumRecyclerViewAdapter private var mForumGroups: ForumGroups? = null private var mToolbarCallback: ToolbarDropDownInterface.Callback? = null private var inForceRefresh = false override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) leavePageMsg("ForumFragment") val recyclerView = recyclerView recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) mRecyclerAdapter = ForumRecyclerViewAdapter(activity) recyclerView.adapter = mRecyclerAdapter } override fun onAttach(context: Context) { App.appComponent.inject(this) super.onAttach(context) mToolbarCallback = context as ToolbarDropDownInterface.Callback? } override fun onDetach() { super.onDetach() mToolbarCallback = null } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.fragment_forum, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item?.itemId) { R.id.menu_browser -> { IntentUtil.startViewIntentExcludeOurApp(context, Uri.parse(Api.BASE_URL)) return true } R.id.app_bar_search -> { val activity = activity!! SearchActivity.start(activity, activity.findViewById(R.id.app_bar_search)) return true } else -> return super.onOptionsItemSelected(item) } } override fun getSourceObservable(@LoadingViewModel.LoadingDef loading: Int): Single<ForumGroupsWrapper> { val source: Single<String> = if (mDownloadPrefManager.netCacheEnable) { apiCacheProvider.getForumGroupsWrapper(mS1Service.forumGroupsWrapper, DynamicKey(mUser.key), EvictDynamicKey(isForceLoading)) } else { mS1Service.forumGroupsWrapper } return source.compose(JsonUtil.jsonSingleTransformer(ForumGroupsWrapper::class.java)) } override fun onNext(data: ForumGroupsWrapper) { super.onNext(data) mForumGroups = data.data // host activity would call #onToolbarDropDownItemSelected(int) after mToolbarCallback?.setupToolbarDropDown(mForumGroups?.forumGroupNameList) } /** * Show all forums when `position == 0` otherwise show * corresponding forum group's forum list. */ override fun onToolbarDropDownItemSelected(position: Int) { mForumGroups?.let { if (position == 0) { mRecyclerAdapter.refreshDataSet(it.forumList, true) } else { // the first position is "全部" // so position - 1 to correspond its group mRecyclerAdapter.refreshDataSet(it.forumGroupList[position - 1], true) } } if (inForceRefresh) { inForceRefresh = false recyclerView.smoothScrollToPosition(0) } } fun forceSwipeRefresh() { inForceRefresh = true startSwipeRefresh() } companion object { val TAG = ForumFragment::class.java.name } }
apache-2.0
6e1a746e4339d6981f083cd04463a1cf
34.248
137
0.697912
4.551653
false
false
false
false
android/animation-samples
Motion/app/src/main/java/com/example/android/motion/demo/sharedelement/CheeseGridAdapter.kt
1
6498
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.motion.demo.sharedelement import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.view.ViewCompat import androidx.navigation.findNavController import androidx.navigation.fragment.FragmentNavigatorExtras import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.Priority import com.example.android.motion.R import com.example.android.motion.demo.doOnEnd import com.example.android.motion.model.Cheese import com.google.android.material.card.MaterialCardView private const val STATE_LAST_SELECTED_ID = "last_selected_id" /** * A [RecyclerView.Adapter] for cheeses. * * This adapter starts the shared element transition. It also handles return transition. */ internal class CheeseGridAdapter( private val onReadyToTransition: () -> Unit ) : ListAdapter<Cheese, CheeseViewHolder>(Cheese.DIFF_CALLBACK) { private var lastSelectedId: Long? = null /** * `true` if we are expecting a reenter transition from the detail fragment. */ val expectsTransition: Boolean get() = lastSelectedId != null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CheeseViewHolder { return CheeseViewHolder(parent).apply { itemView.setOnClickListener { view -> val cheese = getItem(bindingAdapterPosition) // Record the selected item so that we can make the item ready before starting the // reenter transition. lastSelectedId = cheese.id view.findNavController().navigate( R.id.cheeseDetailFragment, CheeseDetailFragmentArgs(cheese.id).toBundle(), null, FragmentNavigatorExtras( // We expand the card into the background. // The fragment will use this first element as the epicenter of all the // fragment transitions, including Explode for non-shared elements. card to CheeseDetailFragment.TRANSITION_NAME_BACKGROUND, // The image is the focal element in this shared element transition. image to CheeseDetailFragment.TRANSITION_NAME_IMAGE, // These elements are only on the grid item, but they need to be shared // elements so they can be animated with the card. See SharedFade.kt. name to CheeseDetailFragment.TRANSITION_NAME_NAME, favorite to CheeseDetailFragment.TRANSITION_NAME_FAVORITE, bookmark to CheeseDetailFragment.TRANSITION_NAME_BOOKMARK, share to CheeseDetailFragment.TRANSITION_NAME_SHARE, // These elements are only on the detail fragment. toolbar to CheeseDetailFragment.TRANSITION_NAME_TOOLBAR, body to CheeseDetailFragment.TRANSITION_NAME_BODY ) ) } } } override fun onBindViewHolder(holder: CheeseViewHolder, position: Int) { val cheese = getItem(position) // Each of the shared elements has to have a unique transition name, not just in this grid // item, but in the entire fragment. ViewCompat.setTransitionName(holder.image, "image-${cheese.id}") ViewCompat.setTransitionName(holder.name, "name-${cheese.id}") ViewCompat.setTransitionName(holder.toolbar, "toolbar-${cheese.id}") ViewCompat.setTransitionName(holder.card, "card-${cheese.id}") ViewCompat.setTransitionName(holder.favorite, "favorite-${cheese.id}") ViewCompat.setTransitionName(holder.bookmark, "bookmark-${cheese.id}") ViewCompat.setTransitionName(holder.share, "share-${cheese.id}") ViewCompat.setTransitionName(holder.body, "body-${cheese.id}") holder.name.text = cheese.name // Load the image asynchronously. See CheeseDetailFragment.kt about "dontTransform()" var requestBuilder = Glide.with(holder.image).load(cheese.image).dontTransform() if (cheese.id == lastSelectedId) { requestBuilder = requestBuilder .priority(Priority.IMMEDIATE) .doOnEnd { // We have loaded the image for the transition destination. It is ready to start // the transition postponed in the fragment. onReadyToTransition() lastSelectedId = null } } requestBuilder.into(holder.image) } fun saveInstanceState(outState: Bundle) { lastSelectedId?.let { id -> outState.putLong(STATE_LAST_SELECTED_ID, id) } } fun restoreInstanceState(state: Bundle) { if (lastSelectedId == null && state.containsKey(STATE_LAST_SELECTED_ID)) { lastSelectedId = state.getLong(STATE_LAST_SELECTED_ID) } } } internal class CheeseViewHolder( parent: ViewGroup ) : RecyclerView.ViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.cheese_grid_item, parent, false) ) { val card: MaterialCardView = itemView.findViewById(R.id.card) val image: ImageView = itemView.findViewById(R.id.image) val name: TextView = itemView.findViewById(R.id.name) val toolbar: MirrorView = itemView.findViewById(R.id.toolbar) val favorite: ImageView = itemView.findViewById(R.id.favorite) val bookmark: ImageView = itemView.findViewById(R.id.bookmark) val share: ImageView = itemView.findViewById(R.id.share) val body: MirrorView = itemView.findViewById(R.id.body) }
apache-2.0
ee92bb6c2472ffe81ff28b8478f3df0c
42.610738
100
0.666974
4.900452
false
false
false
false
tomhenne/Jerusalem
src/main/java/de/esymetric/jerusalem/utils/FileBasedHashMapForLongKeys.kt
1
4143
package de.esymetric.jerusalem.utils import java.io.ByteArrayInputStream import java.io.DataInputStream import java.io.File import java.io.IOException class FileBasedHashMapForLongKeys { // nextIndex var raf: BufferedRandomAccessFile? = null var rafCache = BufferedRandomAccessFileCache() var isEmpty = false var fileLength: Long = 0 var countGets = 0 var countGetReads = 0 val avgGetAccessNumberOfReads: Float get() { val r = countGetReads.toFloat() / countGets.toFloat() countGetReads = 0 countGets = 0 return r } val andClearNumberOfFileChanges: Int get() = rafCache.andClearNumberOfFileChanges fun open(filePath: String?, readOnly: Boolean) { isEmpty = false fileLength = 0L if (readOnly && !File(filePath).exists()) { isEmpty = true return } try { raf = rafCache.getRandomAccessFile(filePath!!, readOnly) if (raf!!.length() < SENTENCE_LENGTH.toLong() * HASH_ARRAY_SIZE.toLong()) { val bufSize = HASH_ARRAY_SIZE // other sizes could be chosen val buf = ByteArray(bufSize) for (i in 0 until HASH_ARRAY_SIZE / bufSize * SENTENCE_LENGTH) raf?.write(buf) print("$") } fileLength = raf!!.length() } catch (e: IOException) { e.printStackTrace() } } fun close() { rafCache.close() } fun put(key: Long, value: Int) { try { val arrayIndex = (key and HASH_ARRAY_MASK).toInt() val strippedKey = (key shr HASH_ARRAY_NUMBER_OF_BITS).toInt() + 1 val pos = arrayIndex.toLong() * SENTENCE_LENGTH.toLong() raf!!.seek(pos) val readKey = raf!!.readInt() raf!!.readInt() val readNextIndex = raf!!.readInt() if (readKey == 0) { raf!!.seek(pos) raf!!.writeInt(strippedKey) raf!!.writeInt(value) } else { val newIndex = (fileLength / SENTENCE_LENGTH.toLong()).toInt() raf!!.seek(fileLength) raf!!.writeInt(strippedKey) raf!!.writeInt(value) raf!!.writeInt(readNextIndex) fileLength += SENTENCE_LENGTH.toLong() raf!!.seek(pos + 8L) raf!!.writeInt(newIndex) } } catch (e: IOException) { e.printStackTrace() } } operator fun get(key: Long): Int { if (isEmpty) return -1 try { val arrayIndex = (key and HASH_ARRAY_MASK).toInt() val strippedKey = (key shr HASH_ARRAY_NUMBER_OF_BITS).toInt() + 1 var pos = arrayIndex.toLong() * SENTENCE_LENGTH.toLong() countGets++ countGetReads++ val buf = ByteArray(SENTENCE_LENGTH) while (true) { raf!!.seek(pos) raf!!.read(buf) val bais = ByteArrayInputStream(buf) val dis = DataInputStream(bais) val foundKey = dis.readInt() val foundValue = dis.readInt() val nextIndex = dis.readInt() dis.close() bais.close() if (foundKey == strippedKey) return foundValue pos = if (nextIndex <= 0L) return -1 else { nextIndex.toLong() * SENTENCE_LENGTH.toLong() } countGetReads++ } } catch (e: IOException) { e.printStackTrace() return -1 } } companion object { const val HASH_ARRAY_NUMBER_OF_BITS = 20 const val HASH_ARRAY_SIZE = 1 shl HASH_ARRAY_NUMBER_OF_BITS // 1048576 = 1M const val HASH_ARRAY_MASK = (HASH_ARRAY_SIZE - 1).toLong() const val SENTENCE_LENGTH = 12 // 12 bytes: int stripped-key, int value, int } }
apache-2.0
d09fe54a498ec920924bb5d10a3d9a17
33.732759
94
0.513396
4.639418
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/util/TabletAwareView.kt
1
2951
/* 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.util import android.content.Context import android.os.Build import android.util.AttributeSet import android.view.View import org.blitzortung.android.app.R import org.blitzortung.android.app.helper.ViewHelper open class TabletAwareView( context: Context, attrs: AttributeSet?, defStyle: Int ) : View(context, attrs, defStyle) { protected val padding: Float protected val textSize: Float protected val sizeFactor: Float init { val a = context.obtainStyledAttributes(attrs, R.styleable.View, defStyle, 0); val scaleForTablet = a.getBoolean(R.styleable.View_tablet_scaleable, false) && isTablet(context) padding = ViewHelper.pxFromDp(this, padding(scaleForTablet)) textSize = ViewHelper.pxFromSp(this, textSize(scaleForTablet)) sizeFactor = sizeFactor(scaleForTablet) a.recycle(); } @SuppressWarnings("unused") constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0) { } @SuppressWarnings("unused") constructor(context: Context) : this(context, null, 0) { } companion object { fun isTablet(context: Context): Boolean { if (isAtLeast(Build.VERSION_CODES.HONEYCOMB_MR2)) { return context.resources.configuration.smallestScreenWidthDp >= 600 } else { return false } } fun padding(context: Context): Float { return padding(isTablet(context)) } fun padding(scaleForTablet: Boolean): Float { return if (scaleForTablet) 8f else 5f } fun textSize(context: Context): Float { return textSize(isTablet(context)) } fun textSize(scaleForTablet: Boolean): Float { return 14f * textSizeFactor(scaleForTablet) } fun sizeFactor(context: Context): Float { return sizeFactor(isTablet(context)) } fun sizeFactor(scaleForTablet: Boolean): Float { return if (scaleForTablet) 1.8f else 1f } fun textSizeFactor(context: Context): Float { return textSizeFactor(isTablet(context)) } fun textSizeFactor(scaleForTablet: Boolean): Float { return if (scaleForTablet) 1.4f else 1f } } }
apache-2.0
1ca73572393763683dedfa67951f6c5f
27.921569
104
0.65661
4.510703
false
false
false
false
umren/Watcher
app/src/main/java/io/github/umren/watcher/Views/Adapters/FavoritesAdapter.kt
1
1820
package io.github.umren.watcher.Views.Adapters import android.widget.ArrayAdapter import io.github.umren.watcher.Entities.Movie import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.TextView import io.github.umren.watcher.R import android.app.Activity class FavoritesAdapter(context: Context, private val movies: ArrayList<Movie>) : ArrayAdapter<Movie>(context, 0, movies) { internal class ViewHolder { var txtItem: TextView? = null var movieNumber: TextView? = null } override fun getItem(position: Int): Movie { return movies[position] } override fun getCount(): Int { return movies.size } override fun getItemId(i: Int): Long { return i.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val retView: View val viewHolder: ViewHolder if (convertView == null) { // inflate the layout val inflater = (context as Activity).layoutInflater retView = inflater.inflate(R.layout.item_favorite, parent, false) // well set up the ViewHolder viewHolder = ViewHolder() viewHolder.txtItem = retView.findViewById(R.id.movie_title) as TextView viewHolder.movieNumber = retView.findViewById(R.id.movie_number) as TextView retView.setTag(R.id.tag_viewholder, viewHolder) } else { retView = convertView viewHolder = retView.getTag(R.id.tag_viewholder) as ViewHolder } viewHolder.txtItem?.text = getItem(position).title viewHolder.movieNumber?.text = (position + 1).toString() retView.setTag(R.id.tag_movie_id, getItem(position).id) return retView } }
gpl-3.0
f6afcb525c0432b94564512afc1574dd
28.852459
122
0.662088
4.343675
false
false
false
false
cout970/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/tilerenderers/TileRenderer.kt
2
3147
package com.cout970.magneticraft.systems.tilerenderers import com.cout970.magneticraft.IVector3 import com.cout970.magneticraft.misc.vector.* import com.cout970.magneticraft.systems.tileentities.TileBase import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer /** * Created by cout970 on 2017/06/16. */ abstract class TileRenderer<T : TileBase> : TileEntitySpecialRenderer<T>() { override fun render(tile: T, x: Double, y: Double, z: Double, tick: Float, destroyStage: Int, alpha: Float) { renderTileEntityAt(tile, x, y, z, tick, destroyStage) } abstract fun renderTileEntityAt(te: T, x: Double, y: Double, z: Double, partialTicks: Float, destroyStage: Int) open fun onModelRegistryReload() = Unit inline fun stackMatrix(func: () -> Unit) { pushMatrix() func() popMatrix() } fun pushMatrix() = GlStateManager.pushMatrix() fun popMatrix() = GlStateManager.popMatrix() inline fun rotationCenter(x: Number, y: Number, z: Number, func: () -> Unit) { GlStateManager.translate(x.toFloat(), y.toFloat(), z.toFloat()) func() GlStateManager.translate(-x.toFloat(), -y.toFloat(), -z.toFloat()) } inline fun rotationCenter(x: Double, y: Double, z: Double, func: () -> Unit) { GlStateManager.translate(x, y, z) func() GlStateManager.translate(-x, -y, -z) } inline fun rotationCenter(x: Float, y: Float, z: Float, func: () -> Unit) { GlStateManager.translate(x, y, z) func() GlStateManager.translate(-x, -y, -z) } inline fun rotationCenter(vec: IVector3, func: () -> Unit) { GlStateManager.translate(vec.xd, vec.yd, vec.zd) func() GlStateManager.translate(-vec.xd, -vec.yd, -vec.zd) } @Suppress("NOTHING_TO_INLINE") inline fun translate(x: Number, y: Number, z: Number) { GlStateManager.translate(x.toFloat(), y.toFloat(), z.toFloat()) } fun translate(x: Double, y: Double, z: Double) = GlStateManager.translate(x, y, z) fun translate(x: Float, y: Float, z: Float) = GlStateManager.translate(x, y, z) fun translate(vec: IVector3) = GlStateManager.translate(vec.xd, vec.yd, vec.zd) fun rotate(angle: Float, x: Float, y: Float, z: Float) = GlStateManager.rotate(angle, x, y, z) fun rotate(angle: Float, axis: IVector3) = GlStateManager.rotate(angle, axis.xf, axis.yf, axis.zf) @Suppress("NOTHING_TO_INLINE") inline fun rotate(angle: Number, x: Number, y: Number, z: Number) { GlStateManager.rotate(angle.toFloat(), x.toFloat(), y.toFloat(), z.toFloat()) } @Suppress("NOTHING_TO_INLINE") inline fun scale(x: Number, y: Number, z: Number) = GlStateManager.scale(x.toFloat(), y.toFloat(), z.toFloat()) fun scale(n: Double) = GlStateManager.scale(n, n, n) fun scale(x: Double, y: Double, z: Double) = GlStateManager.scale(x, y, z) fun scale(x: Float, y: Float, z: Float) = GlStateManager.scale(x, y, z) fun scale(vec: IVector3) = GlStateManager.scale(vec.xd, vec.yd, vec.zd) }
gpl-2.0
482dd7d25baddeeecd4ea2a0edd24aaa
37.864198
115
0.654592
3.600686
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/SimpleDropHelper.kt
1
4768
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.gui import javafx.css.Styleable import javafx.scene.Node import javafx.scene.input.DataFormat import javafx.scene.input.DragEvent import javafx.scene.input.TransferMode open class SimpleDropHelper<T>( val dataFormat: DataFormat, val modes: Array<TransferMode> = TransferMode.ANY, val dropped: ((DragEvent, T) -> Unit)? = null ) : AbstractDropHelper() { open fun accept(event: DragEvent): Pair<Node?, Array<TransferMode>>? { debugPrintln("accept Target ${event.gestureTarget}") if (!event.dragboard.hasContent(dataFormat)) { debugPrintln("Not accepted : No data of the correct type") return null } val source = event.gestureSource if (excludes.contains(source)) { debugPrintln("Not accepted : Excluded node") return null } return acceptTarget(event) } open fun acceptTarget(event: DragEvent): Pair<Node?, Array<TransferMode>>? { debugPrintln("Accepted : $modes") return Pair(event.gestureTarget as Node?, modes) } override fun onDragDropped(event: DragEvent) { val accepted = accept(event) if (accepted != null) { debugPrintln("onDragDropped event.tm= ${event.transferMode} accepted: ${accepted.second}") if (accepted.second.contains(event.transferMode)) { onDropped(event, accepted.first) debugPrintln("Accepted : $modes") } } event.isDropCompleted = true event.consume() } open fun onDropped(event: DragEvent, target: Node?) { dropped?.let { debugPrintln("Dropped. Calling dropped lambda") it(event, content(event)) } } fun content(event: DragEvent): T { @Suppress("UNCHECKED_CAST") return event.dragboard.getContent(dataFormat) as T } private var previousStyledNode: Styleable? = null private fun setDropStyle(node: Styleable?, transferMode: TransferMode?) { previousStyledNode?.styleClass?.remove("drop-copy") previousStyledNode?.styleClass?.remove("drop-move") previousStyledNode?.styleClass?.remove("drop-link") val type = when (transferMode) { TransferMode.COPY -> "copy" TransferMode.MOVE -> "move" TransferMode.LINK -> "link" else -> null } previousStyledNode = node if (type != null) { previousStyledNode?.styleClass?.add("drop-$type") } } /** * When the drag component allows for ANY modes, but the drop component only allows LINK, then * during onDragEventEntered, event.transferMode is COPY, despite the mouse pointer showing a LINK. * I think this is a bug, and this is my best effort work-around. */ private fun eventTransferMode(allowedModes: Array<TransferMode>, event: DragEvent): TransferMode? { if (!allowedModes.contains(event.transferMode)) { return allowedModes.firstOrNull() ?: event.transferMode } return event.transferMode } override fun onDragOver(event: DragEvent): Boolean { val accepted = accept(event) if (accepted != null) { val acceptedNode = accepted.first val acceptedModes = accepted.second event.acceptTransferModes(* acceptedModes) // We set the styles here, because onDragEntered is only called once, even if the transfer mode changes // (by holding down combinations of shift and ctrl) if (acceptedNode is Styleable) { setDropStyle(acceptedNode, eventTransferMode(acceptedModes, event)) } return true } else { // Ensures that the old style is removed when dragging over a table where only some rows accept the drop. setDropStyle(null, null) } return false } override fun onDragExited(event: DragEvent) { setDropStyle(null, null) event.consume() } }
gpl-3.0
c6753b10759e06d266fa0612c7fd41e1
33.550725
117
0.646602
4.553964
false
false
false
false
wiltonlazary/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/ContextUtils.kt
1
24557
/* * Copyright 2010-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.kotlin.backend.konan.llvm import kotlinx.cinterop.allocArray import kotlinx.cinterop.get import kotlinx.cinterop.memScoped import kotlinx.cinterop.toKString import llvm.* import org.jetbrains.kotlin.backend.konan.CachedLibraries import org.jetbrains.kotlin.library.resolver.TopologicalLibraryOrder import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.hash.GlobalHash import org.jetbrains.kotlin.backend.konan.ir.llvmSymbolOrigin import org.jetbrains.kotlin.descriptors.konan.CompiledKlibModuleOrigin import org.jetbrains.kotlin.descriptors.konan.CurrentKlibModuleOrigin import org.jetbrains.kotlin.descriptors.konan.DeserializedKlibModuleOrigin import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.util.file import org.jetbrains.kotlin.ir.util.fqNameForIrSerialization import org.jetbrains.kotlin.ir.util.isReal import org.jetbrains.kotlin.konan.library.KonanLibrary import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.library.KotlinLibrary import org.jetbrains.kotlin.library.resolver.TopologicalLibraryOrder import org.jetbrains.kotlin.library.uniqueName import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.utils.addToStdlib.cast import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty internal sealed class SlotType { // An object is statically allocated on stack. object STACK : SlotType() // Frame local arena slot can be used. object ARENA : SlotType() // Return slot can be used. object RETURN : SlotType() // Return slot, if it is an arena, can be used. object RETURN_IF_ARENA : SlotType() // Param slot, if it is an arena, can be used. class PARAM_IF_ARENA(val parameter: Int) : SlotType() // Params slot, if it is an arena, can be used. class PARAMS_IF_ARENA(val parameters: IntArray, val useReturnSlot: Boolean) : SlotType() // Anonymous slot. object ANONYMOUS : SlotType() // Unknown slot type. object UNKNOWN : SlotType() } // Lifetimes class of reference, computed by escape analysis. internal sealed class Lifetime(val slotType: SlotType) { object STACK : Lifetime(SlotType.STACK) { override fun toString(): String { return "STACK" } } // If reference is frame-local (only obtained from some call and never leaves). object LOCAL : Lifetime(SlotType.ARENA) { override fun toString(): String { return "LOCAL" } } // If reference is only returned. object RETURN_VALUE : Lifetime(SlotType.ANONYMOUS) { override fun toString(): String { return "RETURN_VALUE" } } // If reference is set as field of references of class RETURN_VALUE or INDIRECT_RETURN_VALUE. object INDIRECT_RETURN_VALUE : Lifetime(SlotType.RETURN_IF_ARENA) { override fun toString(): String { return "INDIRECT_RETURN_VALUE" } } // If reference is stored to the field of an incoming parameters. class PARAMETER_FIELD(val parameter: Int) : Lifetime(SlotType.PARAM_IF_ARENA(parameter)) { override fun toString(): String { return "PARAMETER_FIELD($parameter)" } } // If reference is stored to the field of an incoming parameters. class PARAMETERS_FIELD(val parameters: IntArray, val useReturnSlot: Boolean) : Lifetime(SlotType.PARAMS_IF_ARENA(parameters, useReturnSlot)) { override fun toString(): String { return "PARAMETERS_FIELD(${parameters.contentToString()}, useReturnSlot='$useReturnSlot')" } } // If reference refers to the global (either global object or global variable). object GLOBAL : Lifetime(SlotType.ANONYMOUS) { override fun toString(): String { return "GLOBAL" } } // If reference used to throw. object THROW : Lifetime(SlotType.ANONYMOUS) { override fun toString(): String { return "THROW" } } // If reference used as an argument of outgoing function. Class can be improved by escape analysis // of called function. object ARGUMENT : Lifetime(SlotType.ANONYMOUS) { override fun toString(): String { return "ARGUMENT" } } // If reference class is unknown. object UNKNOWN : Lifetime(SlotType.UNKNOWN) { override fun toString(): String { return "UNKNOWN" } } // If reference class is irrelevant. object IRRELEVANT : Lifetime(SlotType.UNKNOWN) { override fun toString(): String { return "IRRELEVANT" } } } /** * Provides utility methods to the implementer. */ internal interface ContextUtils : RuntimeAware { val context: Context override val runtime: Runtime get() = context.llvm.runtime /** * Describes the target platform. * * TODO: using [llvmTargetData] usually results in generating non-portable bitcode. */ val llvmTargetData: LLVMTargetDataRef get() = runtime.targetData val staticData: StaticData get() = context.llvm.staticData /** * TODO: maybe it'd be better to replace with [IrDeclaration::isEffectivelyExternal()], * or just drop all [else] branches of corresponding conditionals. */ fun isExternal(declaration: IrDeclaration): Boolean { return !context.llvmModuleSpecification.containsDeclaration(declaration) } /** * LLVM function generated from the Kotlin function. * It may be declared as external function prototype. */ val IrFunction.llvmFunction: LLVMValueRef get() = llvmFunctionOrNull ?: error("$name in $file/${parent.fqNameForIrSerialization}") val IrFunction.llvmFunctionOrNull: LLVMValueRef? get() { assert(this.isReal) return if (isExternal(this)) { runtime.addedLLVMExternalFunctions.getOrPut(this) { context.llvm.externalFunction(this.symbolName, getLlvmFunctionType(this), origin = this.llvmSymbolOrigin) } } else { context.llvmDeclarations.forFunctionOrNull(this)?.llvmFunction } } /** * Address of entry point of [llvmFunction]. */ val IrFunction.entryPointAddress: ConstPointer get() { val result = LLVMConstBitCast(this.llvmFunction, int8TypePtr)!! return constPointer(result) } val IrClass.typeInfoPtr: ConstPointer get() { return if (isExternal(this)) { constPointer(importGlobal(this.typeInfoSymbolName, runtime.typeInfoType, origin = this.llvmSymbolOrigin)) } else { context.llvmDeclarations.forClass(this).typeInfo } } /** * Pointer to type info for given class. * It may be declared as pointer to external variable. */ val IrClass.llvmTypeInfoPtr: LLVMValueRef get() = typeInfoPtr.llvm /** * Returns contents of this [GlobalHash]. * * It must be declared identically with [Runtime.globalHashType]. */ fun GlobalHash.getBytes(): ByteArray { val size = GlobalHash.size assert(size == LLVMStoreSizeOfType(llvmTargetData, runtime.globalHashType)) return this.bits.getBytes(size) } /** * Returns global hash of this string contents. */ val String.globalHashBytes: ByteArray get() = memScoped { val hash = globalHash(stringAsBytes(this@globalHashBytes), memScope) hash.getBytes() } /** * Return base64 representation for global hash of this string contents. */ val String.globalHashBase64: String get() { return base64Encode(globalHashBytes) } val String.globalHash: ConstValue get() = memScoped { val hashBytes = [email protected] return Struct(runtime.globalHashType, ConstArray(int8Type, hashBytes.map { Int8(it) })) } val FqName.globalHash: ConstValue get() = this.toString().globalHash } /** * Converts this string to the sequence of bytes to be used for hashing/storing to binary/etc. */ internal fun stringAsBytes(str: String) = str.toByteArray(Charsets.UTF_8) internal val String.localHash: LocalHash get() = LocalHash(localHash(stringAsBytes(this))) internal val Name.localHash: LocalHash get() = this.toString().localHash internal val FqName.localHash: LocalHash get() = this.toString().localHash internal class Llvm(val context: Context, val llvmModule: LLVMModuleRef) { private fun importFunction(name: String, otherModule: LLVMModuleRef): LLVMValueRef { if (LLVMGetNamedFunction(llvmModule, name) != null) { throw IllegalArgumentException("function $name already exists") } val externalFunction = LLVMGetNamedFunction(otherModule, name) ?: throw Error("function $name not found") val functionType = getFunctionType(externalFunction) val function = LLVMAddFunction(llvmModule, name, functionType)!! copyFunctionAttributes(externalFunction, function) return function } private fun importGlobal(name: String, otherModule: LLVMModuleRef): LLVMValueRef { if (LLVMGetNamedGlobal(llvmModule, name) != null) { throw IllegalArgumentException("global $name already exists") } val externalGlobal = LLVMGetNamedGlobal(otherModule, name)!! val globalType = getGlobalType(externalGlobal) val global = LLVMAddGlobal(llvmModule, globalType, name)!! return global } private fun copyFunctionAttributes(source: LLVMValueRef, destination: LLVMValueRef) { // TODO: consider parameter attributes val attributeIndex = LLVMAttributeFunctionIndex val count = LLVMGetAttributeCountAtIndex(source, attributeIndex) memScoped { val attributes = allocArray<LLVMAttributeRefVar>(count) LLVMGetAttributesAtIndex(source, attributeIndex, attributes) (0 until count).forEach { LLVMAddAttributeAtIndex(destination, attributeIndex, attributes[it]) } } } private fun importMemset(): LLVMValueRef { val functionType = functionType(voidType, false, int8TypePtr, int8Type, int32Type, int1Type) return LLVMAddFunction(llvmModule, "llvm.memset.p0i8.i32", functionType)!! } private fun importMemcpy(): LLVMValueRef { val functionType = functionType(voidType, false, int8TypePtr, int8TypePtr, int32Type, int1Type) return LLVMAddFunction(llvmModule, "llvm.memcpy.p0i8.p0i8.i32", functionType)!! } private fun llvmIntrinsic(name: String, type: LLVMTypeRef, vararg attributes: String): LLVMValueRef { val result = LLVMAddFunction(llvmModule, name, type)!! attributes.forEach { val kindId = getLlvmAttributeKindId(it) addLlvmFunctionEnumAttribute(result, kindId) } return result } internal fun externalFunction( name: String, type: LLVMTypeRef, origin: CompiledKlibModuleOrigin, independent: Boolean = false ): LLVMValueRef { this.imports.add(origin, onlyBitcode = independent) val found = LLVMGetNamedFunction(llvmModule, name) if (found != null) { assert(getFunctionType(found) == type) { "Expected: ${LLVMPrintTypeToString(type)!!.toKString()} " + "found: ${LLVMPrintTypeToString(getFunctionType(found))!!.toKString()}" } assert(LLVMGetLinkage(found) == LLVMLinkage.LLVMExternalLinkage) return found } else { // As exported functions are written in C++ they assume sign extension for promoted types - // mention that in attributes. val function = LLVMAddFunction(llvmModule, name, type)!! return memScoped { val paramCount = LLVMCountParamTypes(type) val paramTypes = allocArray<LLVMTypeRefVar>(paramCount) LLVMGetParamTypes(type, paramTypes) (0 until paramCount).forEach { index -> val paramType = paramTypes[index] addFunctionSignext(function, index + 1, paramType) } val returnType = LLVMGetReturnType(type) addFunctionSignext(function, 0, returnType) function } } } private fun externalNounwindFunction(name: String, type: LLVMTypeRef, origin: CompiledKlibModuleOrigin): LLVMValueRef { val function = externalFunction(name, type, origin) setFunctionNoUnwind(function) return function } val imports get() = context.llvmImports class ImportsImpl(private val context: Context) : LlvmImports { private val usedBitcode = mutableSetOf<KotlinLibrary>() private val usedNativeDependencies = mutableSetOf<KotlinLibrary>() private val allLibraries by lazy { context.librariesWithDependencies.toSet() } override fun add(origin: CompiledKlibModuleOrigin, onlyBitcode: Boolean) { val library = when (origin) { CurrentKlibModuleOrigin -> return is DeserializedKlibModuleOrigin -> origin.library } if (library !in allLibraries) { error("Library (${library.libraryName}) is used but not requested.\nRequested libraries: ${allLibraries.joinToString { it.libraryName }}") } usedBitcode.add(library) if (!onlyBitcode) { usedNativeDependencies.add(library) } } override fun bitcodeIsUsed(library: KonanLibrary) = library in usedBitcode override fun nativeDependenciesAreUsed(library: KonanLibrary) = library in usedNativeDependencies } val nativeDependenciesToLink: List<KonanLibrary> by lazy { context.config.resolvedLibraries .getFullList(TopologicalLibraryOrder) .filter { require(it is KonanLibrary) (!it.isDefault && !context.config.purgeUserLibs) || imports.nativeDependenciesAreUsed(it) }.cast<List<KonanLibrary>>() } private val immediateBitcodeDependencies: List<KonanLibrary> by lazy { context.config.resolvedLibraries.getFullList(TopologicalLibraryOrder).cast<List<KonanLibrary>>() .filter { (!it.isDefault && !context.config.purgeUserLibs) || imports.bitcodeIsUsed(it) } } val allCachedBitcodeDependencies: List<KonanLibrary> by lazy { val allLibraries = context.config.resolvedLibraries.getFullList().associateBy { it.uniqueName } val result = mutableSetOf<KonanLibrary>() fun addDependencies(cachedLibrary: CachedLibraries.Cache) { cachedLibrary.bitcodeDependencies.forEach { val library = allLibraries[it] ?: error("Bitcode dependency to an unknown library: $it") result.add(library as KonanLibrary) addDependencies(context.config.cachedLibraries.getLibraryCache(library) ?: error("Library $it is expected to be cached")) } } for (library in immediateBitcodeDependencies) { val cache = context.config.cachedLibraries.getLibraryCache(library) if (cache != null) { result += library addDependencies(cache) } } result.toList() } val allNativeDependencies: List<KonanLibrary> by lazy { (nativeDependenciesToLink + allCachedBitcodeDependencies).distinct() } val allBitcodeDependencies: List<KonanLibrary> by lazy { val allNonCachedDependencies = context.librariesWithDependencies.filter { context.config.cachedLibraries.getLibraryCache(it) == null } val set = (allNonCachedDependencies + allCachedBitcodeDependencies).toSet() // This list is used in particular to build the libraries' initializers chain. // The initializers must be called in the topological order, so make sure that the // libraries list being returned is also toposorted. context.config.resolvedLibraries .getFullList(TopologicalLibraryOrder) .cast<List<KonanLibrary>>() .filter { it in set } } val bitcodeToLink: List<KonanLibrary> by lazy { (context.config.resolvedLibraries.getFullList(TopologicalLibraryOrder).cast<List<KonanLibrary>>()) .filter { shouldContainBitcode(it) } } private fun shouldContainBitcode(library: KonanLibrary): Boolean { if (!context.llvmModuleSpecification.containsLibrary(library)) { return false } if (!context.llvmModuleSpecification.isFinal) { return true } // Apply some DCE: return (!library.isDefault && !context.config.purgeUserLibs) || imports.bitcodeIsUsed(library) } val additionalProducedBitcodeFiles = mutableListOf<String>() val staticData = StaticData(context) private val target = context.config.target val runtimeFile = context.config.distribution.runtime(target) val runtime = Runtime(runtimeFile) // TODO: dispose val targetTriple = runtime.target init { LLVMSetDataLayout(llvmModule, runtime.dataLayout) LLVMSetTarget(llvmModule, targetTriple) } private fun importRtFunction(name: String) = importFunction(name, runtime.llvmModule) private fun importModelSpecificRtFunction(name: String) = importRtFunction(name + context.memoryModel.suffix) private fun importRtGlobal(name: String) = importGlobal(name, runtime.llvmModule) val allocInstanceFunction = importModelSpecificRtFunction("AllocInstance") val allocArrayFunction = importModelSpecificRtFunction("AllocArrayInstance") val initInstanceFunction = importModelSpecificRtFunction("InitInstance") val initSharedInstanceFunction = importModelSpecificRtFunction("InitSharedInstance") val updateHeapRefFunction = importModelSpecificRtFunction("UpdateHeapRef") val releaseHeapRefFunction = importModelSpecificRtFunction("ReleaseHeapRef") val updateStackRefFunction = importModelSpecificRtFunction("UpdateStackRef") val updateReturnRefFunction = importModelSpecificRtFunction("UpdateReturnRef") val zeroHeapRefFunction = importRtFunction("ZeroHeapRef") val zeroArrayRefsFunction = importRtFunction("ZeroArrayRefs") val enterFrameFunction = importModelSpecificRtFunction("EnterFrame") val leaveFrameFunction = importModelSpecificRtFunction("LeaveFrame") val lookupOpenMethodFunction = importRtFunction("LookupOpenMethod") val lookupInterfaceTableRecord = importRtFunction("LookupInterfaceTableRecord") val isInstanceFunction = importRtFunction("IsInstance") val isInstanceOfClassFastFunction = importRtFunction("IsInstanceOfClassFast") val throwExceptionFunction = importRtFunction("ThrowException") val appendToInitalizersTail = importRtFunction("AppendToInitializersTail") val addTLSRecord = importRtFunction("AddTLSRecord") val clearTLSRecord = importRtFunction("ClearTLSRecord") val lookupTLS = importRtFunction("LookupTLS") val initRuntimeIfNeeded = importRtFunction("Kotlin_initRuntimeIfNeeded") val mutationCheck = importRtFunction("MutationCheck") val checkLifetimesConstraint = importRtFunction("CheckLifetimesConstraint") val freezeSubgraph = importRtFunction("FreezeSubgraph") val checkMainThread = importRtFunction("CheckIsMainThread") val kRefSharedHolderInitLocal = importRtFunction("KRefSharedHolder_initLocal") val kRefSharedHolderInit = importRtFunction("KRefSharedHolder_init") val kRefSharedHolderDispose = importRtFunction("KRefSharedHolder_dispose") val kRefSharedHolderRef = importRtFunction("KRefSharedHolder_ref") val createKotlinObjCClass by lazy { importRtFunction("CreateKotlinObjCClass") } val getObjCKotlinTypeInfo by lazy { importRtFunction("GetObjCKotlinTypeInfo") } val missingInitImp by lazy { importRtFunction("MissingInitImp") } val Kotlin_Interop_DoesObjectConformToProtocol by lazyRtFunction val Kotlin_Interop_IsObjectKindOfClass by lazyRtFunction val Kotlin_ObjCExport_refToObjC by lazyRtFunction val Kotlin_ObjCExport_refFromObjC by lazyRtFunction val Kotlin_ObjCExport_CreateNSStringFromKString by lazyRtFunction val Kotlin_ObjCExport_convertUnit by lazyRtFunction val Kotlin_ObjCExport_GetAssociatedObject by lazyRtFunction val Kotlin_ObjCExport_AbstractMethodCalled by lazyRtFunction val Kotlin_ObjCExport_RethrowExceptionAsNSError by lazyRtFunction val Kotlin_ObjCExport_RethrowNSErrorAsException by lazyRtFunction val Kotlin_ObjCExport_AllocInstanceWithAssociatedObject by lazyRtFunction val Kotlin_ObjCExport_createContinuationArgument by lazyRtFunction val Kotlin_ObjCExport_resumeContinuation by lazyRtFunction val tlsMode by lazy { when (target) { KonanTarget.WASM32, is KonanTarget.ZEPHYR -> LLVMThreadLocalMode.LLVMNotThreadLocal else -> LLVMThreadLocalMode.LLVMGeneralDynamicTLSModel } } var tlsCount = 0 val tlsKey by lazy { val global = LLVMAddGlobal(llvmModule, kInt8Ptr, "__KonanTlsKey")!! LLVMSetLinkage(global, LLVMLinkage.LLVMInternalLinkage) LLVMSetInitializer(global, LLVMConstNull(kInt8Ptr)) global } private val personalityFunctionName = when (target) { KonanTarget.IOS_ARM32 -> "__gxx_personality_sj0" KonanTarget.MINGW_X64 -> "__gxx_personality_seh0" else -> "__gxx_personality_v0" } val cxxStdTerminate = externalNounwindFunction( "_ZSt9terminatev", // mangled C++ 'std::terminate' functionType(voidType, false), origin = context.standardLlvmSymbolsOrigin ) val gxxPersonalityFunction = externalNounwindFunction( personalityFunctionName, functionType(int32Type, true), origin = context.standardLlvmSymbolsOrigin ) val cxaBeginCatchFunction = externalNounwindFunction( "__cxa_begin_catch", functionType(int8TypePtr, false, int8TypePtr), origin = context.standardLlvmSymbolsOrigin ) val cxaEndCatchFunction = externalNounwindFunction( "__cxa_end_catch", functionType(voidType, false), origin = context.standardLlvmSymbolsOrigin ) val memsetFunction = importMemset() //val memcpyFunction = importMemcpy() val llvmTrap = llvmIntrinsic( "llvm.trap", functionType(voidType, false), "cold", "noreturn", "nounwind" ) val llvmEhTypeidFor = llvmIntrinsic( "llvm.eh.typeid.for", functionType(int32Type, false, int8TypePtr), "nounwind", "readnone" ) val usedFunctions = mutableListOf<LLVMValueRef>() val usedGlobals = mutableListOf<LLVMValueRef>() val compilerUsedGlobals = mutableListOf<LLVMValueRef>() val irStaticInitializers = mutableListOf<IrStaticInitializer>() val otherStaticInitializers = mutableListOf<LLVMValueRef>() val fileInitializers = mutableListOf<IrField>() var fileUsesThreadLocalObjects = false val globalSharedObjects = mutableSetOf<LLVMValueRef>() private object lazyRtFunction { operator fun provideDelegate( thisRef: Llvm, property: KProperty<*> ) = object : ReadOnlyProperty<Llvm, LLVMValueRef> { val value by lazy { thisRef.importRtFunction(property.name) } override fun getValue(thisRef: Llvm, property: KProperty<*>): LLVMValueRef = value } } val llvmInt8 = int8Type val llvmInt16 = int16Type val llvmInt32 = int32Type val llvmInt64 = int64Type val llvmFloat = floatType val llvmDouble = doubleType val llvmVector128 = vector128Type } class IrStaticInitializer(val file: IrFile, val initializer: LLVMValueRef)
apache-2.0
4cf165703ae3dc69004296ed615c643e
37.370313
154
0.68343
4.755422
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/actions/OpenExistingNetworkAction.kt
1
1082
package com.thomas.needham.neurophidea.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.thomas.needham.neurophidea.forms.open.OpenNetworkForm /** * Created by thoma on 13/06/2016. * * Action to Open a network that was previously created by this plugin */ class OpenExistingNetworkAction : AnAction() { var form: OpenNetworkForm? = null var itr: Long = 0L companion object ProjectInfo { var project: Project? = null var projectDirectory: String? = "" var isOpen: Boolean? = false } override fun actionPerformed(e: AnActionEvent) { // Setup Project InitialisationAction.project = e.project InitialisationAction.projectDirectory = InitialisationAction.project?.basePath InitialisationAction.isOpen = InitialisationAction.project?.isOpen // TODO Implement // Messages.showErrorDialog(project, "Feature is Not Currently Implemented", "Not Implemented") // return form = OpenNetworkForm() } }
mit
989bcd8815ee88998e4d0265d31c5bde
30.823529
96
0.779113
4.114068
false
false
false
false
liceoArzignano/app_bold
app/src/main/kotlin/it/liceoarzignano/bold/ui/CircularProgressBar.kt
1
3793
package it.liceoarzignano.bold.ui import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.RectF import androidx.core.content.ContextCompat import androidx.interpolator.view.animation.FastOutSlowInInterpolator import android.util.AttributeSet import android.view.View import it.liceoarzignano.bold.R import java.util.* /** * Simple single android view component that can be used to showing a round progress bar. * It can be customized with size, stroke size, colors and text etc. * Progress change will be animated. * Created by Kristoffer, http://kmdev.se * * * Customized for it.liceoarzignano.bold by joey */ class CircularProgressBar : View { private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG) private var mViewWidth: Int = 0 private var mViewHeight: Int = 0 private var mSweepAngle = 0f private var mProgressColor: Int = 0 private val mTextColor = ContextCompat.getColor(context, R.color.black) private var mValue: Double = 0.toDouble() constructor(context: Context): super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, style: Int) : super(context, attrs, style) override fun onDraw(canvas: Canvas) { super.onDraw(canvas) initMeasurements() drawOutlineArc(canvas) drawText(canvas) } private fun initMeasurements() { mViewWidth = width mViewHeight = height } private fun drawOutlineArc(canvas: Canvas) { val diameter = Math.min(mViewWidth, mViewHeight) - 48 val outerOval = RectF(24f, 24f, diameter.toFloat(), diameter.toFloat()) mPaint.color = ContextCompat.getColor(context, R.color.circular_progress_bar_bg) mPaint.strokeWidth = 32f mPaint.isAntiAlias = true mPaint.strokeCap = Paint.Cap.ROUND mPaint.style = Paint.Style.STROKE canvas.drawArc(outerOval, 0f, 360f, false, mPaint) mPaint.color = mProgressColor canvas.drawArc(outerOval, -90f, mSweepAngle, false, mPaint) } private fun drawText(canvas: Canvas) { mPaint.textSize = Math.min(mViewWidth, mViewHeight) / 5f mPaint.textAlign = Paint.Align.CENTER mPaint.strokeWidth = 0f mPaint.color = mTextColor // Center text val posX = canvas.width / 2 val posY = (canvas.height / 2 - (mPaint.descent() + mPaint.ascent()) / 2).toInt() canvas.drawText(String.format(Locale.ENGLISH, "%.2f", mValue), posX.toFloat(), posY.toFloat(), mPaint) } private fun calcSweepAngleFromProgress(progress: Int): Float = (36 * progress / 100).toFloat() fun setProgress(progress: Double) { mValue = progress // Animate only the first time if (mSweepAngle != 0f) { mSweepAngle = calcSweepAngleFromProgress( if (progress < 1) 100 else (progress * 100).toInt()) return } mSweepAngle = 0f val animator = ValueAnimator.ofFloat(mSweepAngle, calcSweepAngleFromProgress( if (progress < 1) 100 else (progress * 100).toInt())) animator.interpolator = FastOutSlowInInterpolator() animator.duration = 1600 animator.startDelay = 300 animator.addUpdateListener { valueAnimator -> mSweepAngle = valueAnimator.animatedValue as Float invalidate() } animator.start() } fun setProgressColor(color: Int) { mProgressColor = color invalidate() } }
lgpl-3.0
51cd257282001910bdbcb11cae24d89d
31.418803
98
0.647245
4.510107
false
false
false
false
hypercube1024/firefly
firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/Http1ServerConnection.kt
1
4716
package com.fireflysource.net.http.server.impl import com.fireflysource.common.`object`.Assert import com.fireflysource.common.sys.SystemLogger import com.fireflysource.net.Connection import com.fireflysource.net.http.common.HttpConfig import com.fireflysource.net.http.common.TcpBasedHttpConnection import com.fireflysource.net.http.common.exception.BadMessageException import com.fireflysource.net.http.common.exception.HttpServerConnectionListenerNotSetException import com.fireflysource.net.http.common.model.HttpVersion import com.fireflysource.net.http.common.v1.decoder.HttpParser import com.fireflysource.net.http.common.v1.decoder.parseAll import com.fireflysource.net.http.server.HttpServerConnection import com.fireflysource.net.tcp.TcpConnection import com.fireflysource.net.tcp.TcpCoroutineDispatcher import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import java.io.IOException import java.util.concurrent.CancellationException import java.util.concurrent.atomic.AtomicBoolean class Http1ServerConnection( val config: HttpConfig, private val tcpConnection: TcpConnection ) : Connection by tcpConnection, TcpCoroutineDispatcher by tcpConnection, TcpBasedHttpConnection, HttpServerConnection { companion object { private val log = SystemLogger.create(Http1ServerConnection::class.java) } private val requestHandler = Http1ServerRequestHandler(this) private val parser = HttpParser(requestHandler) private val responseHandler = Http1ServerResponseHandler(this) private val beginning = AtomicBoolean(false) private val channel: Channel<ParseHttpPacketMessage> = Channel(Channel.UNLIMITED) private var parseRequestJob: Job? = null private var generateResponseJob: Job? = null private fun parseRequestJob() = coroutineScope.launch { parseLoop@ while (true) { when (channel.receive()) { is ParseNextHttpPacket -> parseNextHttpPacket() is ExitHttpParser -> { log.info { "Exit the HTTP server parser. id: $id" } break@parseLoop } } } } private suspend fun parseNextHttpPacket() { try { parser.parseAll(tcpConnection) } catch (e: BadMessageException) { requestHandler.badMessage(e) channel.trySend(ExitHttpParser) } catch (e: IOException) { log.info { "The TCP connection IO exception. message: ${e.message ?: e.javaClass.name}, id: $id" } channel.trySend(ExitHttpParser) } catch (e: CancellationException) { log.info { "Cancel HTTP1 parsing. message: ${e.message} id: $id" } channel.trySend(ExitHttpParser) } catch (e: Exception) { log.error(e) { "Parse HTTP1 request exception. id: $id" } } finally { resetParser() } } fun parseNextRequest() { channel.trySend(ParseNextHttpPacket) } suspend fun endHttpParser() { channel.trySend(ExitHttpParser) parseRequestJob?.join() } fun resetParser() { parser.reset() } private fun generateResponseJob() = responseHandler.generateResponseJob() fun getHeaderBufferSize() = config.headerBufferSize fun sendResponseMessage(message: Http1ResponseMessage) = responseHandler.sendResponseMessage(message) suspend fun endResponseHandler() { responseHandler.endResponseHandler() generateResponseJob?.join() } override fun begin() { if (beginning.compareAndSet(false, true)) { if (requestHandler.connectionListener === HttpServerConnection.EMPTY_LISTENER) { throw HttpServerConnectionListenerNotSetException("Please set connection listener before begin parsing.") } parseRequestJob = parseRequestJob() generateResponseJob = generateResponseJob() parseNextRequest() } } override fun setListener(listener: HttpServerConnection.Listener): HttpServerConnection { Assert.state( !beginning.get(), "The HTTP request parser has started. Please set listener before begin parsing." ) requestHandler.connectionListener = listener return this } override fun getHttpVersion(): HttpVersion = HttpVersion.HTTP_1_1 override fun isSecureConnection(): Boolean = tcpConnection.isSecureConnection override fun getTcpConnection(): TcpConnection = tcpConnection } sealed interface ParseHttpPacketMessage object ParseNextHttpPacket : ParseHttpPacketMessage object ExitHttpParser : ParseHttpPacketMessage
apache-2.0
fbbffb49e69611da1b848d69d8957178
37.040323
121
0.709924
4.744467
false
false
false
false
Karumi/Shot
shot-consumer/app/src/main/java/com/karumi/ui/view/CursorActivity.kt
1
985
package com.karumi.ui.view import androidx.appcompat.widget.Toolbar import android.view.View import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.bind import com.github.salomonbrys.kodein.instance import com.github.salomonbrys.kodein.provider import com.karumi.R import com.karumi.ui.presenter.CursorPresenter import kotlinx.android.synthetic.main.cursor_activity.* import kotlinx.android.synthetic.main.main_activity.toolbar class CursorActivity : BaseActivity(), CursorPresenter.View { override val layoutId: Int = R.layout.cursor_activity override val presenter: CursorPresenter by injector.instance() override val toolbarView: Toolbar get() = toolbar override val activityModules = Kodein.Module(allowSilentOverride = true) { bind<CursorPresenter>() with provider { CursorPresenter(this@CursorActivity) } } override fun showEditText() { et_cursor.visibility = View.VISIBLE } }
apache-2.0
140034453e7e0972fc1343e0488012c0
31.866667
78
0.762437
4.320175
false
false
false
false
apixandru/intellij-community
plugins/settings-repository/src/RepositoryService.kt
6
2694
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.util.io.URLUtil import com.intellij.util.io.exists import com.intellij.util.io.isDirectory import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.transport.URIish import org.jetbrains.settingsRepository.git.createBareRepository import java.io.IOException import java.nio.file.Path import java.nio.file.Paths interface RepositoryService { fun checkUrl(uriString: String, project: Project? = null): Boolean { val uri = URIish(uriString) val isFile: Boolean if (uri.scheme == URLUtil.FILE_PROTOCOL) { isFile = true } else { isFile = uri.scheme == null && uri.host == null } if (isFile && !checkFileRepo(uriString, project)) { return false } return true } private fun checkFileRepo(url: String, project: Project?): Boolean { val suffix = "/${Constants.DOT_GIT}" val file = Paths.get(if (url.endsWith(suffix)) url.substring(0, url.length - suffix.length) else url) if (file.exists()) { if (!file.isDirectory()) { Messages.showErrorDialog(project, "Path is not a directory", "") return false } else if (isValidRepository(file)) { return true } } else if (!file.isAbsolute) { Messages.showErrorDialog(project, icsMessage("specify.absolute.path.dialog.message"), "") return false } if (MessageDialogBuilder .yesNo(icsMessage("init.dialog.title"), icsMessage("init.dialog.message", file)) .yesText("Create") .project(project) .isYes) { return try { createBareRepository(file) true } catch (e: IOException) { Messages.showErrorDialog(project, icsMessage("init.failed.message", e.message), icsMessage("init.failed.title")) false } } else { return false } } // must be protected, kotlin bug fun isValidRepository(file: Path): Boolean }
apache-2.0
fb2cd526343caf8a5ace194d76e44871
30.337209
120
0.686711
4.106707
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/dialog/wheel/WheelView.kt
1
24924
package com.tamsiree.rxui.view.dialog.wheel import android.annotation.SuppressLint import android.content.Context import android.database.DataSetObserver import android.graphics.Canvas import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.animation.Interpolator import android.widget.LinearLayout import com.tamsiree.rxui.R import java.util.* import kotlin.math.abs import kotlin.math.asin import kotlin.math.max /** * @author Tamsiree * * Numeric wheel view. */ class WheelView : View { /** Top and bottom shadows colors */ private var SHADOWS_COLORS = intArrayOf(-0xeeeeef, 0x00AAAAAA, 0x00AAAAAA) // Wheel Values var currentItem = 0 /** * Gets count of visible items * * @return the count of visible items */ /** * Sets the desired count of visible items. * Actual amount of visible items depends on wheel layout parameters. * To apply changes and rebuild view call measure(). * * @param count the desired count for visible items */ // Count of visible items var visibleItems = DEF_VISIBLE_ITEMS // Item height private var itemHeight = 0 // Center Line private var centerDrawable: Drawable? = null // Wheel drawables private var wheelBackground = R.drawable.wheel_bg private var wheelForeground = R.drawable.wheel_val_holo // Shadows drawables private var topShadow: GradientDrawable? = null private var bottomShadow: GradientDrawable? = null // Draw Shadows private var drawShadows = true // Scrolling private var scroller: WheelScroller? = null private var isScrollingPerformed = false private var scrollingOffset = 0 // Cyclic var isCyclic = false // Items layout private var itemsLayout: LinearLayout? = null // The number of first item in layout private var firstItem = 0 // View adapter var viewAdapter: WheelViewAdapter? = null // Recycle private val recycle = WheelRecycle(this) // Listeners private val changingListeners: MutableList<OnWheelChangedListener> = LinkedList() private val scrollingListeners: MutableList<OnWheelScrollListener> = LinkedList() private val clickingListeners: MutableList<OnWheelClickedListener> = LinkedList() /** * Constructor */ constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) { initData(context) } /** * Constructor */ constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { initData(context) } /** * Constructor */ constructor(context: Context) : super(context) { initData(context) } /** * Initializes class data * @param context the context */ private fun initData(context: Context) { scroller = WheelScroller(context, scrollingListener) } // Scrolling listener var scrollingListener: WheelScroller.ScrollingListener = object : WheelScroller.ScrollingListener { override fun onStarted() { isScrollingPerformed = true notifyScrollingListenersAboutStart() } override fun onScroll(distance: Int) { doScroll(distance) val height = height if (scrollingOffset > height) { scrollingOffset = height scroller!!.stopScrolling() } else if (scrollingOffset < -height) { scrollingOffset = -height scroller!!.stopScrolling() } } override fun onFinished() { if (isScrollingPerformed) { notifyScrollingListenersAboutEnd() isScrollingPerformed = false } scrollingOffset = 0 invalidate() } override fun onJustify() { if (Math.abs(scrollingOffset) > WheelScroller.MIN_DELTA_FOR_SCROLLING) { scroller!!.scroll(scrollingOffset, 0) } } } /** * Set the the specified scrolling interpolator * @param interpolator the interpolator */ fun setInterpolator(interpolator: Interpolator?) { scroller!!.setInterpolator(interpolator) } // Adapter listener private val dataObserver: DataSetObserver = object : DataSetObserver() { override fun onChanged() { invalidateWheel(false) } override fun onInvalidated() { invalidateWheel(true) } } /** * Sets view adapter. Usually new adapters contain different views, so * it needs to rebuild view by calling measure(). * * @param wheelViewAdapter the view adapter */ fun setViewAdapter0(wheelViewAdapter: WheelViewAdapter) { if (viewAdapter != null) { viewAdapter?.unregisterDataSetObserver(dataObserver) } viewAdapter = wheelViewAdapter if (viewAdapter != null) { viewAdapter?.registerDataSetObserver(dataObserver) } invalidateWheel(true) } /** * Adds wheel changing listener * @param listener the listener */ fun addChangingListener(listener: OnWheelChangedListener) { changingListeners.add(listener) } /** * Removes wheel changing listener * @param listener the listener */ fun removeChangingListener(listener: OnWheelChangedListener) { changingListeners.remove(listener) } /** * Notifies changing listeners * @param oldValue the old wheel value * @param newValue the new wheel value */ protected fun notifyChangingListeners(oldValue: Int, newValue: Int) { for (listener in changingListeners) { listener.onChanged(this, oldValue, newValue) } } /** * Adds wheel scrolling listener * @param listener the listener */ fun addScrollingListener(listener: OnWheelScrollListener) { scrollingListeners.add(listener) } /** * Removes wheel scrolling listener * @param listener the listener */ fun removeScrollingListener(listener: OnWheelScrollListener) { scrollingListeners.remove(listener) } /** * Notifies listeners about starting scrolling */ protected fun notifyScrollingListenersAboutStart() { for (listener in scrollingListeners) { listener.onScrollingStarted(this) } } /** * Notifies listeners about ending scrolling */ protected fun notifyScrollingListenersAboutEnd() { for (listener in scrollingListeners) { listener.onScrollingFinished(this) } } /** * Adds wheel clicking listener * @param listener the listener */ fun addClickingListener(listener: OnWheelClickedListener) { clickingListeners.add(listener) } /** * Removes wheel clicking listener * @param listener the listener */ fun removeClickingListener(listener: OnWheelClickedListener) { clickingListeners.remove(listener) } /** * Notifies listeners about clicking */ protected fun notifyClickListenersAboutClick(item: Int) { for (listener in clickingListeners) { listener.onItemClicked(this, item) } } /** * Sets the current item. Does nothing when index is wrong. * * @param index the item index * @param animated the animation flag */ fun setCurrentItem(index: Int, animated: Boolean) { var index = index if (viewAdapter == null || viewAdapter!!.itemsCount == 0) { return // throw? } val itemCount = viewAdapter!!.itemsCount if (index < 0 || index >= itemCount) { if (isCyclic) { while (index < 0) { index += itemCount } index %= itemCount } else { return // throw? } } if (index != currentItem) { if (animated) { var itemsToScroll = index - currentItem if (isCyclic) { val scroll = itemCount + Math.min(index, currentItem) - Math.max(index, currentItem) if (scroll < Math.abs(itemsToScroll)) { itemsToScroll = if (itemsToScroll < 0) scroll else -scroll } } scroll(itemsToScroll, 0) } else { scrollingOffset = 0 val old = currentItem currentItem = index notifyChangingListeners(old, currentItem) invalidate() } } } /** * Sets the current item w/o animation. Does nothing when index is wrong. * * @param index the item index */ fun setCurrentItem0(index: Int) { setCurrentItem(index, false) } /** * Tests if wheel is cyclic. That means before the 1st item there is shown the last one * @return true if wheel is cyclic */ fun isCyclic0(): Boolean { return isCyclic } /** * Set wheel cyclic flag * @param isCyclic the flag to set */ fun setCyclic0(isCyclic: Boolean) { this.isCyclic = isCyclic invalidateWheel(false) } /** * Determine whether shadows are drawn * @return true is shadows are drawn */ fun drawShadows(): Boolean { return drawShadows } /** * Set whether shadows should be drawn * @param drawShadows flag as true or false */ fun setDrawShadows(drawShadows: Boolean) { this.drawShadows = drawShadows } /** * Set the shadow gradient color * @param start * @param middle * @param end */ fun setShadowColor(start: Int, middle: Int, end: Int) { SHADOWS_COLORS = intArrayOf(start, middle, end) } /** * Sets the drawable for the wheel background * @param resource */ fun setWheelBackground(resource: Int) { wheelBackground = resource setBackgroundResource(wheelBackground) } /** * Sets the drawable for the wheel foreground * @param resource */ fun setWheelForeground(resource: Int) { wheelForeground = resource centerDrawable = context.resources.getDrawable(wheelForeground) } /** * Invalidates wheel * @param clearCaches if true then cached views will be clear */ fun invalidateWheel(clearCaches: Boolean) { if (clearCaches) { recycle.clearAll() if (itemsLayout != null) { itemsLayout?.removeAllViews() } scrollingOffset = 0 } else if (itemsLayout != null) { // cache all items recycle.recycleItems(itemsLayout!!, firstItem, ItemsRange()) } invalidate() } /** * Initializes resources */ private fun initResourcesIfNecessary() { if (centerDrawable == null) { centerDrawable = context.resources.getDrawable(wheelForeground) } if (topShadow == null) { topShadow = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, SHADOWS_COLORS) } if (bottomShadow == null) { bottomShadow = GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, SHADOWS_COLORS) } setBackgroundResource(wheelBackground) } /** * Calculates desired height for layout * * @param layout * the source layout * @return the desired layout height */ private fun getDesiredHeight(layout: LinearLayout?): Int { if (layout != null && layout.getChildAt(0) != null) { itemHeight = layout.getChildAt(0).measuredHeight } val desired = itemHeight * visibleItems - itemHeight * ITEM_OFFSET_PERCENT / 50 return Math.max(desired, suggestedMinimumHeight) } /** * Returns height of wheel item * @return the item height */ private fun getItemHeight(): Int { if (itemHeight != 0) { return itemHeight } if (itemsLayout != null && itemsLayout?.getChildAt(0) != null) { itemHeight = itemsLayout?.getChildAt(0)!!.height return itemHeight } return height / visibleItems } /** * Calculates control width and creates text layouts * @param widthSize the input layout width * @param mode the layout mode * @return the calculated control width */ private fun calculateLayoutWidth(widthSize: Int, mode: Int): Int { initResourcesIfNecessary() // TODO: make it static itemsLayout?.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) itemsLayout?.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) var width = itemsLayout?.measuredWidth!! if (mode == MeasureSpec.EXACTLY) { width = widthSize } else { width += 2 * PADDING // Check against our minimum width width = max(width, suggestedMinimumWidth) if (mode == MeasureSpec.AT_MOST && widthSize < width) { width = widthSize } } itemsLayout?.measure(MeasureSpec.makeMeasureSpec(width - 2 * PADDING, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) return width } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = MeasureSpec.getMode(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) buildViewForMeasuring() val width = calculateLayoutWidth(widthSize, widthMode) var height: Int if (heightMode == MeasureSpec.EXACTLY) { height = heightSize } else { height = getDesiredHeight(itemsLayout) if (heightMode == MeasureSpec.AT_MOST) { height = Math.min(height, heightSize) } } setMeasuredDimension(width, height) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { layout(r - l, b - t) } /** * Sets layouts width and height * @param width the layout width * @param height the layout height */ private fun layout(width: Int, height: Int) { val itemsWidth = width - 2 * PADDING itemsLayout?.layout(0, 0, itemsWidth, height) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (viewAdapter != null && viewAdapter!!.itemsCount > 0) { updateView() drawItems(canvas) drawCenterRect(canvas) } if (drawShadows) { drawShadows(canvas) } } /** * Draws shadows on top and bottom of control * @param canvas the canvas for drawing */ private fun drawShadows(canvas: Canvas) { val height = (1.5 * getItemHeight()).toInt() topShadow?.setBounds(0, 0, width, height) topShadow?.draw(canvas) bottomShadow?.setBounds(0, getHeight() - height, width, getHeight()) bottomShadow?.draw(canvas) } /** * Draws items * @param canvas the canvas for drawing */ private fun drawItems(canvas: Canvas) { canvas.save() val top = (currentItem - firstItem) * getItemHeight() + (getItemHeight() - height) / 2 canvas.translate(PADDING.toFloat(), -top + scrollingOffset.toFloat()) itemsLayout?.draw(canvas) canvas.restore() } /** * Draws rect for current value * @param canvas the canvas for drawing */ private fun drawCenterRect(canvas: Canvas) { val center = height / 2 val offset = (getItemHeight() / 2 * 1.2).toInt() centerDrawable?.setBounds(0, center - offset, width, center + offset) centerDrawable?.draw(canvas) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { if (!isEnabled || viewAdapter == null) { return true } when (event.action) { MotionEvent.ACTION_MOVE -> if (parent != null) { parent.requestDisallowInterceptTouchEvent(true) } MotionEvent.ACTION_UP -> if (!isScrollingPerformed) { var distance = event.y.toInt() - height / 2 if (distance > 0) { distance += getItemHeight() / 2 } else { distance -= getItemHeight() / 2 } val items = distance / getItemHeight() if (items != 0 && isValidItemIndex(currentItem + items)) { notifyClickListenersAboutClick(currentItem + items) } } } return scroller?.onTouchEvent(event)!! } /** * Scrolls the wheel * @param delta the scrolling value */ private fun doScroll(delta: Int) { scrollingOffset += delta val itemHeight = getItemHeight() var count = scrollingOffset / itemHeight var pos = currentItem - count val itemCount = viewAdapter?.itemsCount!! var fixPos = scrollingOffset % itemHeight if (abs(fixPos) <= itemHeight / 2) { fixPos = 0 } if (isCyclic && itemCount > 0) { if (fixPos > 0) { pos-- count++ } else if (fixPos < 0) { pos++ count-- } // fix position by rotating while (pos < 0) { pos += itemCount } pos %= itemCount } else { // if (pos < 0) { count = currentItem pos = 0 } else if (pos >= itemCount) { count = currentItem - itemCount + 1 pos = itemCount - 1 } else if (pos > 0 && fixPos > 0) { pos-- count++ } else if (pos < itemCount - 1 && fixPos < 0) { pos++ count-- } } val offset = scrollingOffset if (pos != currentItem) { setCurrentItem(pos, false) } else { invalidate() } // update offset scrollingOffset = offset - count * itemHeight if (scrollingOffset > height) { scrollingOffset = if (height <= 0) { 0 } else { scrollingOffset % height + height } } } /** * Scroll the wheel * @param itemsToScroll items to scroll * @param time scrolling duration */ fun scroll(itemsToScroll: Int, time: Int) { val distance = itemsToScroll * getItemHeight() - scrollingOffset scroller?.scroll(distance, time) }// process empty items above the first or below the second// top + bottom items /** * Calculates range for wheel items * @return the items range */ private val itemsRange: ItemsRange? get() { if (getItemHeight() == 0) { return null } var first = currentItem var count = 1 while (count * getItemHeight() < height) { first-- count += 2 // top + bottom items } if (scrollingOffset != 0) { if (scrollingOffset > 0) { first-- } count++ // process empty items above the first or below the second val emptyItems = scrollingOffset / getItemHeight() first -= emptyItems count += asin(emptyItems.toDouble()).toInt() } return ItemsRange(first, count) } /** * Rebuilds wheel items if necessary. Caches all unused items. * * @return true if items are rebuilt */ private fun rebuildItems(): Boolean { var updated = false val range = itemsRange if (itemsLayout != null) { val first = recycle.recycleItems(itemsLayout!!, firstItem, range!!) updated = firstItem != first firstItem = first } else { createItemsLayout() updated = true } if (!updated) { updated = firstItem != range?.first || itemsLayout?.childCount != range.count } if (firstItem > range?.first!! && firstItem <= range.last) { for (i in firstItem - 1 downTo range.first) { if (!addViewItem(i, true)) { break } firstItem = i } } else { firstItem = range.first } var first = firstItem for (i in itemsLayout!!.childCount until range.count) { if (!addViewItem(firstItem + i, false) && itemsLayout?.childCount == 0) { first++ } } firstItem = first return updated } /** * Updates view. Rebuilds items and label if necessary, recalculate items sizes. */ private fun updateView() { if (rebuildItems()) { calculateLayoutWidth(width, MeasureSpec.EXACTLY) layout(width, height) } } /** * Creates item layouts if necessary */ private fun createItemsLayout() { if (itemsLayout == null) { itemsLayout = LinearLayout(context) itemsLayout?.orientation = LinearLayout.VERTICAL } } /** * Builds view for measuring */ private fun buildViewForMeasuring() { // clear all items if (itemsLayout != null) { recycle.recycleItems(itemsLayout!!, firstItem, ItemsRange()) } else { createItemsLayout() } // add views // all items must be included to measure width correctly for (i in viewAdapter?.itemsCount!! - 1 downTo 0) { if (addViewItem(i, true)) { firstItem = i } } } /** * Adds view for item to items layout * @param index the item index * @param first the flag indicates if view should be first * @return true if corresponding item exists and is added */ private fun addViewItem(index: Int, first: Boolean): Boolean { val view = getItemView(index) if (view != null) { if (first) { itemsLayout?.addView(view, 0) } else { itemsLayout?.addView(view) } return true } return false } /** * Checks whether intem index is valid * @param index the item index * @return true if item index is not out of bounds or the wheel is cyclic */ private fun isValidItemIndex(index: Int?): Boolean { return viewAdapter != null && viewAdapter?.itemsCount!! > 0 && (isCyclic || index!! >= 0 && index < viewAdapter?.itemsCount!!) } /** * Returns view for specified item * @param index the item index * @return item view or empty view if index is out of bounds */ private fun getItemView(index: Int): View? { var index1 = index if (viewAdapter == null || viewAdapter?.itemsCount == 0) { return null } val count = viewAdapter?.itemsCount if (!isValidItemIndex(index1)) { return viewAdapter?.getEmptyItem(recycle.emptyItem, itemsLayout) } else { while (index1 < 0) { index1 += count!! } } index1 %= count!! val view = recycle.item val viewGroup = itemsLayout return viewAdapter?.getItem(index1, view, viewGroup) } /** * Stops scrolling */ fun stopScrolling() { scroller!!.stopScrolling() } companion object { /** Top and bottom items offset (to hide that) */ private const val ITEM_OFFSET_PERCENT = 0 /** Left and right padding value */ private const val PADDING = 10 /** Default count of visible items */ private const val DEF_VISIBLE_ITEMS = 5 } }
apache-2.0
74060eb70f85435dc46573b8caa49109
28.743437
132
0.571658
4.962963
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/streaming/FanfouTimelineStreamCallback.kt
1
1949
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util.streaming import de.vanita5.microblog.library.fanfou.callback.SimpleFanfouUserStreamCallback import de.vanita5.microblog.library.twitter.model.Activity import de.vanita5.microblog.library.twitter.model.InternalActivityCreator import de.vanita5.microblog.library.twitter.model.Status import de.vanita5.microblog.library.twitter.model.User import java.util.* abstract class FanfouTimelineStreamCallback( val accountId: String ) : SimpleFanfouUserStreamCallback() { override fun onStatusCreation(createdAt: Date, source: User, target: User?, status: Status): Boolean { var handled = false if (target == null) { handled = handled or onHomeTimeline(status) } if (target?.id == accountId) { handled = handled or onActivityAboutMe(InternalActivityCreator.status(status, accountId)) } return handled } protected abstract fun onHomeTimeline(status: Status): Boolean protected abstract fun onActivityAboutMe(activity: Activity): Boolean }
gpl-3.0
9e0ff210f7101c94a9e8b49732b302bb
37.235294
106
0.742432
4.246187
false
false
false
false
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/plugin/commands/ACommand.kt
1
1438
package com.projectcitybuild.plugin.commands import com.projectcitybuild.core.exceptions.InvalidCommandArgumentsException import com.projectcitybuild.platforms.bungeecord.extensions.add import com.projectcitybuild.plugin.environment.SpigotCommand import com.projectcitybuild.plugin.environment.SpigotCommandInput import net.md_5.bungee.api.ChatColor import net.md_5.bungee.api.chat.TextComponent import org.bukkit.Server import javax.inject.Inject class ACommand @Inject constructor( private val server: Server ) : SpigotCommand { override val label = "a" override val permission = "pcbridge.chat.staff_channel" override val usageHelp = "/a <message>" override suspend fun execute(input: SpigotCommandInput) { if (input.args.isEmpty()) { throw InvalidCommandArgumentsException() } val message = input.args.joinToString(separator = " ") val senderName = if (input.isConsole) "CONSOLE" else input.player.displayName server.onlinePlayers.forEach { player -> if (player.hasPermission("pcbridge.chat.staff_channel")) player.spigot().sendMessage( TextComponent() .add("(Staff) $senderName") { it.color = ChatColor.YELLOW } .add(" » ") { it.color = ChatColor.GRAY } .add(TextComponent.fromLegacyText(message)) ) } } }
mit
a70801dbe210730b486f3f2c46e0988f
36.815789
85
0.673626
4.533123
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/view/PaymentAuthWebViewActivityViewModel.kt
1
4642
package com.stripe.android.view import android.app.Application import android.content.Intent import android.net.Uri import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.stripe.android.Stripe import com.stripe.android.StripeIntentResult import com.stripe.android.auth.PaymentBrowserAuthContract import com.stripe.android.core.Logger import com.stripe.android.core.networking.AnalyticsRequest import com.stripe.android.core.networking.AnalyticsRequestExecutor import com.stripe.android.core.networking.DefaultAnalyticsRequestExecutor import com.stripe.android.core.networking.StripeClientUserAgentHeaderFactory import com.stripe.android.networking.PaymentAnalyticsEvent import com.stripe.android.networking.PaymentAnalyticsRequestFactory import com.stripe.android.payments.PaymentFlowResult import com.stripe.android.stripe3ds2.init.ui.StripeToolbarCustomization import kotlinx.coroutines.Dispatchers internal class PaymentAuthWebViewActivityViewModel( private val args: PaymentBrowserAuthContract.Args, private val analyticsRequestExecutor: AnalyticsRequestExecutor, private val paymentAnalyticsRequestFactory: PaymentAnalyticsRequestFactory ) : ViewModel() { val extraHeaders: Map<String, String> by lazy { StripeClientUserAgentHeaderFactory().create(Stripe.appInfo) } @JvmSynthetic internal val buttonText = args.toolbarCustomization?.let { toolbarCustomization -> toolbarCustomization.buttonText.takeUnless { it.isNullOrBlank() } } @JvmSynthetic internal val toolbarTitle = args.toolbarCustomization?.let { toolbarCustomization -> toolbarCustomization.headerText.takeUnless { it.isNullOrBlank() }?.let { ToolbarTitleData(it, toolbarCustomization) } } @JvmSynthetic internal val toolbarBackgroundColor = args.toolbarCustomization?.backgroundColor internal val paymentResult: PaymentFlowResult.Unvalidated @JvmSynthetic get() { return PaymentFlowResult.Unvalidated( clientSecret = args.clientSecret, sourceId = Uri.parse(args.url).lastPathSegment.orEmpty(), stripeAccountId = args.stripeAccountId ) } internal val cancellationResult: Intent @JvmSynthetic get() { return Intent().putExtras( paymentResult.copy( flowOutcome = if (args.shouldCancelIntentOnUserNavigation) { StripeIntentResult.Outcome.CANCELED } else { StripeIntentResult.Outcome.SUCCEEDED }, canCancelSource = args.shouldCancelSource ).toBundle() ) } /** * Log that 3DS1 challenge started. */ fun logStart() { fireAnalytics( paymentAnalyticsRequestFactory.createRequest(PaymentAnalyticsEvent.Auth3ds1ChallengeStart) ) fireAnalytics( paymentAnalyticsRequestFactory.createRequest( PaymentAnalyticsEvent.AuthWithWebView ) ) } /** * Log that 3DS1 challenge completed with an error. */ fun logError() { fireAnalytics( paymentAnalyticsRequestFactory.createRequest(PaymentAnalyticsEvent.Auth3ds1ChallengeError) ) } /** * Log that 3DS1 challenge completed without an error. */ fun logComplete() { fireAnalytics( paymentAnalyticsRequestFactory.createRequest(PaymentAnalyticsEvent.Auth3ds1ChallengeComplete) ) } private fun fireAnalytics( request: AnalyticsRequest ) { analyticsRequestExecutor.executeAsync(request) } internal data class ToolbarTitleData( internal val text: String, internal val toolbarCustomization: StripeToolbarCustomization ) internal class Factory( private val application: Application, private val logger: Logger, private val args: PaymentBrowserAuthContract.Args ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return PaymentAuthWebViewActivityViewModel( args, DefaultAnalyticsRequestExecutor(logger, Dispatchers.IO), PaymentAnalyticsRequestFactory( application, args.publishableKey, defaultProductUsageTokens = setOf("PaymentAuthWebViewActivity") ) ) as T } } }
mit
24b13aeaa8938db58f5ec7fdf799c920
33.902256
105
0.682464
5.619855
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/window/dialog/DialogTest.kt
3
17837
/* * 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.compose.ui.window.dialog import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.awt.ComposeDialog import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.focusTarget import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onKeyEvent import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.sendKeyEvent import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.launchApplication import androidx.compose.ui.window.rememberDialogState import androidx.compose.ui.window.runApplicationTest import com.google.common.truth.Truth.assertThat import org.junit.Test import java.awt.Dimension import java.awt.event.KeyEvent import java.awt.event.WindowAdapter import java.awt.event.WindowEvent @OptIn(ExperimentalComposeUiApi::class) class DialogTest { @Test fun `open and close custom dialog`() = runApplicationTest { var window: ComposeDialog? = null launchApplication { var isOpen by remember { mutableStateOf(true) } fun createWindow() = ComposeDialog().apply { size = Dimension(300, 200) addWindowListener(object : WindowAdapter() { override fun windowClosing(e: WindowEvent) { isOpen = false } }) } if (isOpen) { Dialog( create = ::createWindow, dispose = ComposeDialog::dispose ) { window = this.window Box(Modifier.size(32.dp).background(Color.Red)) } } } awaitIdle() assertThat(window?.isShowing).isTrue() window?.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING)) } @Test fun `update custom dialog`() = runApplicationTest { var window: ComposeDialog? = null var isOpen by mutableStateOf(true) var title by mutableStateOf("Title1") launchApplication { fun createWindow() = ComposeDialog().apply { size = Dimension(300, 200) addWindowListener(object : WindowAdapter() { override fun windowClosing(e: WindowEvent) { isOpen = false } }) } if (isOpen) { Dialog( create = ::createWindow, dispose = ComposeDialog::dispose, update = { it.title = title } ) { window = this.window Box(Modifier.size(32.dp).background(Color.Red)) } } } awaitIdle() assertThat(window?.isShowing).isTrue() assertThat(window?.title).isEqualTo(title) title = "Title2" awaitIdle() assertThat(window?.title).isEqualTo(title) isOpen = false } @Test fun `open and close dialog`() = runApplicationTest { var window: ComposeDialog? = null launchApplication { Dialog(onCloseRequest = ::exitApplication) { window = this.window Box(Modifier.size(32.dp).background(Color.Red)) } } awaitIdle() assertThat(window?.isShowing).isTrue() window?.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING)) } @Test fun `disable closing dialog`() = runApplicationTest { var isOpen by mutableStateOf(true) var isCloseCalled by mutableStateOf(false) var window: ComposeDialog? = null launchApplication { if (isOpen) { Dialog( onCloseRequest = { isCloseCalled = true } ) { window = this.window Box(Modifier.size(32.dp).background(Color.Red)) } } } awaitIdle() window?.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING)) awaitIdle() assertThat(isCloseCalled).isTrue() assertThat(window?.isShowing).isTrue() isOpen = false awaitIdle() assertThat(window?.isShowing).isFalse() } @Test fun `show splash screen`() = runApplicationTest { var window1: ComposeDialog? = null var window2: ComposeDialog? = null var isOpen by mutableStateOf(true) var isLoading by mutableStateOf(true) launchApplication { if (isOpen) { if (isLoading) { Dialog(onCloseRequest = {}) { window1 = this.window Box(Modifier.size(32.dp).background(Color.Red)) } } else { Dialog(onCloseRequest = {}) { window2 = this.window Box(Modifier.size(32.dp).background(Color.Blue)) } } } } awaitIdle() assertThat(window1?.isShowing).isTrue() assertThat(window2).isNull() isLoading = false awaitIdle() assertThat(window1?.isShowing).isFalse() assertThat(window2?.isShowing).isTrue() isOpen = false awaitIdle() assertThat(window1?.isShowing).isFalse() assertThat(window2?.isShowing).isFalse() } @Test fun `open two dialogs`() = runApplicationTest { var window1: ComposeDialog? = null var window2: ComposeDialog? = null var isOpen by mutableStateOf(true) launchApplication { if (isOpen) { Dialog(onCloseRequest = {}) { window1 = this.window Box(Modifier.size(32.dp).background(Color.Red)) } Dialog(onCloseRequest = {}) { window2 = this.window Box(Modifier.size(32.dp).background(Color.Blue)) } } } awaitIdle() assertThat(window1?.isShowing).isTrue() assertThat(window2?.isShowing).isTrue() isOpen = false awaitIdle() assertThat(window1?.isShowing).isFalse() assertThat(window2?.isShowing).isFalse() } @Test fun `open nested dialog`() = runApplicationTest { var window1: ComposeDialog? = null var window2: ComposeDialog? = null var isOpen by mutableStateOf(true) var isNestedOpen by mutableStateOf(true) launchApplication { if (isOpen) { Dialog( onCloseRequest = {}, state = rememberDialogState( size = DpSize(600.dp, 600.dp), ) ) { window1 = this.window Box(Modifier.size(32.dp).background(Color.Red)) if (isNestedOpen) { Dialog( onCloseRequest = {}, state = rememberDialogState( size = DpSize(300.dp, 300.dp), ) ) { window2 = this.window Box(Modifier.size(32.dp).background(Color.Blue)) } } } } } awaitIdle() assertThat(window1?.isShowing).isTrue() assertThat(window2?.isShowing).isTrue() isNestedOpen = false awaitIdle() assertThat(window1?.isShowing).isTrue() assertThat(window2?.isShowing).isFalse() isNestedOpen = true awaitIdle() assertThat(window1?.isShowing).isTrue() assertThat(window2?.isShowing).isTrue() isOpen = false awaitIdle() assertThat(window1?.isShowing).isFalse() assertThat(window2?.isShowing).isFalse() } @Test fun `pass composition local to dialogs`() = runApplicationTest { var actualValue1: Int? = null var actualValue2: Int? = null var isOpen by mutableStateOf(true) var testValue by mutableStateOf(0) val localTestValue = compositionLocalOf { testValue } launchApplication { if (isOpen) { CompositionLocalProvider(localTestValue provides testValue) { Dialog( onCloseRequest = {}, state = rememberDialogState( size = DpSize(600.dp, 600.dp), ) ) { actualValue1 = localTestValue.current Box(Modifier.size(32.dp).background(Color.Red)) Dialog( onCloseRequest = {}, state = rememberDialogState( size = DpSize(300.dp, 300.dp), ) ) { actualValue2 = localTestValue.current Box(Modifier.size(32.dp).background(Color.Blue)) } } } } } awaitIdle() assertThat(actualValue1).isEqualTo(0) assertThat(actualValue2).isEqualTo(0) testValue = 42 awaitIdle() assertThat(actualValue1).isEqualTo(42) assertThat(actualValue2).isEqualTo(42) isOpen = false } @Test fun `DisposableEffect call order`() = runApplicationTest { var initCount = 0 var disposeCount = 0 var isOpen by mutableStateOf(true) launchApplication { if (isOpen) { Dialog(onCloseRequest = {}) { DisposableEffect(Unit) { initCount++ onDispose { disposeCount++ } } } } } awaitIdle() assertThat(initCount).isEqualTo(1) assertThat(disposeCount).isEqualTo(0) isOpen = false awaitIdle() assertThat(initCount).isEqualTo(1) assertThat(disposeCount).isEqualTo(1) } @Test fun `catch key handlers`() = runApplicationTest { var window: ComposeDialog? = null val onKeyEventKeys = mutableSetOf<Key>() val onPreviewKeyEventKeys = mutableSetOf<Key>() fun clear() { onKeyEventKeys.clear() onPreviewKeyEventKeys.clear() } launchApplication { Dialog( onCloseRequest = ::exitApplication, onPreviewKeyEvent = { onPreviewKeyEventKeys.add(it.key) it.key == Key.Q }, onKeyEvent = { onKeyEventKeys.add(it.key) it.key == Key.W } ) { window = this.window } } awaitIdle() window?.sendKeyEvent(KeyEvent.VK_Q) awaitIdle() assertThat(onPreviewKeyEventKeys).isEqualTo(setOf(Key.Q)) assertThat(onKeyEventKeys).isEqualTo(emptySet<Key>()) clear() window?.sendKeyEvent(KeyEvent.VK_W) awaitIdle() assertThat(onPreviewKeyEventKeys).isEqualTo(setOf(Key.W)) assertThat(onKeyEventKeys).isEqualTo(setOf(Key.W)) clear() window?.sendKeyEvent(KeyEvent.VK_E) awaitIdle() assertThat(onPreviewKeyEventKeys).isEqualTo(setOf(Key.E)) assertThat(onKeyEventKeys).isEqualTo(setOf(Key.E)) exitApplication() } @Test fun `catch key handlers with focused node`() = runApplicationTest { var window: ComposeDialog? = null val onWindowKeyEventKeys = mutableSetOf<Key>() val onWindowPreviewKeyEventKeys = mutableSetOf<Key>() val onNodeKeyEventKeys = mutableSetOf<Key>() val onNodePreviewKeyEventKeys = mutableSetOf<Key>() fun clear() { onWindowKeyEventKeys.clear() onWindowPreviewKeyEventKeys.clear() onNodeKeyEventKeys.clear() onNodePreviewKeyEventKeys.clear() } launchApplication { Dialog( onCloseRequest = ::exitApplication, onPreviewKeyEvent = { onWindowPreviewKeyEventKeys.add(it.key) it.key == Key.Q }, onKeyEvent = { onWindowKeyEventKeys.add(it.key) it.key == Key.W }, ) { window = this.window val focusRequester = remember(::FocusRequester) LaunchedEffect(Unit) { focusRequester.requestFocus() } Box( Modifier .focusRequester(focusRequester) .focusTarget() .onPreviewKeyEvent { onNodePreviewKeyEventKeys.add(it.key) it.key == Key.E } .onKeyEvent { onNodeKeyEventKeys.add(it.key) it.key == Key.R } ) } } awaitIdle() window?.sendKeyEvent(KeyEvent.VK_Q) awaitIdle() assertThat(onWindowPreviewKeyEventKeys).isEqualTo(setOf(Key.Q)) assertThat(onNodePreviewKeyEventKeys).isEqualTo(emptySet<Key>()) assertThat(onNodeKeyEventKeys).isEqualTo(emptySet<Key>()) assertThat(onWindowKeyEventKeys).isEqualTo(emptySet<Key>()) clear() window?.sendKeyEvent(KeyEvent.VK_W) awaitIdle() assertThat(onWindowPreviewKeyEventKeys).isEqualTo(setOf(Key.W)) assertThat(onNodePreviewKeyEventKeys).isEqualTo(setOf(Key.W)) assertThat(onNodeKeyEventKeys).isEqualTo(setOf(Key.W)) assertThat(onWindowKeyEventKeys).isEqualTo(setOf(Key.W)) clear() window?.sendKeyEvent(KeyEvent.VK_E) awaitIdle() assertThat(onWindowPreviewKeyEventKeys).isEqualTo(setOf(Key.E)) assertThat(onNodePreviewKeyEventKeys).isEqualTo(setOf(Key.E)) assertThat(onNodeKeyEventKeys).isEqualTo(emptySet<Key>()) assertThat(onWindowKeyEventKeys).isEqualTo(emptySet<Key>()) clear() window?.sendKeyEvent(KeyEvent.VK_R) awaitIdle() assertThat(onWindowPreviewKeyEventKeys).isEqualTo(setOf(Key.R)) assertThat(onNodePreviewKeyEventKeys).isEqualTo(setOf(Key.R)) assertThat(onNodeKeyEventKeys).isEqualTo(setOf(Key.R)) assertThat(onWindowKeyEventKeys).isEqualTo(emptySet<Key>()) clear() window?.sendKeyEvent(KeyEvent.VK_T) awaitIdle() assertThat(onWindowPreviewKeyEventKeys).isEqualTo(setOf(Key.T)) assertThat(onNodePreviewKeyEventKeys).isEqualTo(setOf(Key.T)) assertThat(onNodeKeyEventKeys).isEqualTo(setOf(Key.T)) assertThat(onWindowKeyEventKeys).isEqualTo(setOf(Key.T)) exitApplication() } @Test(timeout = 30000) fun `should draw before dialog is visible`() = runApplicationTest { var isComposed = false var isDrawn = false var isVisibleOnFirstComposition = false var isVisibleOnFirstDraw = false launchApplication { Dialog(onCloseRequest = ::exitApplication) { if (!isComposed) { isVisibleOnFirstComposition = window.isVisible isComposed = true } Canvas(Modifier.fillMaxSize()) { if (!isDrawn) { isVisibleOnFirstDraw = window.isVisible isDrawn = true } } } } awaitIdle() assertThat(isVisibleOnFirstComposition).isFalse() assertThat(isVisibleOnFirstDraw).isFalse() exitApplication() } }
apache-2.0
2d3ff9e846da226a9d9d681e66fc02a9
31.140541
78
0.55284
5.34522
false
true
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/TaskDifficultyButtons.kt
1
4254
package com.habitrpg.android.habitica.ui.views.tasks.form import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.view.View import android.view.accessibility.AccessibilityEvent import android.widget.ImageView import android.widget.LinearLayout import android.widget.Space import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.view.children import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.asDrawable import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.models.tasks.TaskDifficulty import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper class TaskDifficultyButtons @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { var tintColor: Int = ContextCompat.getColor(context, R.color.brand_300) var textTintColor: Int? = null var selectedDifficulty: Float = 1f set(value) { field = value removeAllViews() addAllButtons() selectedButton.sendAccessibilityEvent(AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION) } private lateinit var selectedButton: View override fun setEnabled(isEnabled: Boolean) { super.setEnabled(isEnabled) for (child in this.children) { child.isEnabled = isEnabled } } override fun onAttachedToWindow() { super.onAttachedToWindow() removeAllViews() addAllButtons() } private fun addAllButtons() { val lastDifficulty = TaskDifficulty.values().last() for (difficulty in TaskDifficulty.values()) { val button = createButton(difficulty) addView(button) if (difficulty != lastDifficulty) { val space = Space(context) val layoutParams = LayoutParams(0, LayoutParams.WRAP_CONTENT) layoutParams.weight = 1f space.layoutParams = layoutParams addView(space) } if (difficulty.value == selectedDifficulty) { selectedButton = button } } } private fun createButton(difficulty: TaskDifficulty): View { val view = inflate(R.layout.task_form_task_difficulty, false) val isActive = selectedDifficulty == difficulty.value var difficultyColor = ContextCompat.getColor(context, R.color.white) if (isActive) { view.findViewById<ImageView>(R.id.image_view).background.mutate().setTint(tintColor) view.findViewById<TextView>(R.id.text_view).setTextColor(textTintColor ?: tintColor) view.findViewById<TextView>(R.id.text_view).typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) } else { view.findViewById<ImageView>(R.id.image_view).background.mutate().setTint(ContextCompat.getColor(context, R.color.taskform_gray)) view.findViewById<TextView>(R.id.text_view).setTextColor(ContextCompat.getColor(context, R.color.text_secondary)) difficultyColor = ContextCompat.getColor(context, R.color.disabled_background) view.findViewById<TextView>(R.id.text_view).typeface = Typeface.create("sans-serif", Typeface.NORMAL) } val drawable = HabiticaIconsHelper.imageOfTaskDifficultyStars(difficultyColor, difficulty.value, true).asDrawable(resources) view.findViewById<ImageView>(R.id.image_view).setImageDrawable(drawable) val buttonText = context.getText(difficulty.nameRes) view.findViewById<TextView>(R.id.text_view).text = buttonText view.contentDescription = toContentDescription(buttonText, isActive) view.setOnClickListener { selectedDifficulty = difficulty.value } return view } private fun toContentDescription(buttonText: CharSequence, isActive: Boolean): String { val statusString = if (isActive) { context.getString(R.string.selected) } else context.getString(R.string.not_selected) return "$buttonText, $statusString" } }
gpl-3.0
07dc86bec12d2db96a3b91956c4f8625
41.118812
141
0.693935
4.769058
false
false
false
false