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
ylemoigne/ReactKT
sampleprojects/demo-core/src/main/kotlin/fr/javatic/reactktSample/core/TodoFooter.kt
1
2492
/* * Copyright 2015 Yann Le Moigne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.javatic.reactktSample.core import fr.javatic.reactkt.core.Component import fr.javatic.reactkt.core.ReactElement import fr.javatic.reactkt.core.ktx import fr.javatic.reactktSample.core.interfaces.TodoFooterProps class TodoFooter : Component<TodoFooterProps, Any>() { override fun render(): ReactElement { var activeTodoWord = Utils.pluralize(this.props.count, "item"); var clearButton = if (this.props.completedCount > 0) { ktx { button("className" to "clear-completed", "onClick" to props.onClearCompleted) { +"Clear completed" } } } else null val nowShowing = this.props.nowShowing; return ktx { footer("className" to "footer") { span("className" to "todo-count") { strong() { +props.count.toString() } +" " +activeTodoWord +" left" } ul("className" to "filters") { li { a("href" to "#/", "className" to if (nowShowing == App.ALL_TODOS) "selected" else null) { +"All" } } +" " li { a("href" to "#/active", "className" to if (nowShowing == App.ACTIVE_TODOS) "selected" else null) { +"Active" } } +" " li { a("href" to "#/completed", "className" to if (nowShowing == App.COMPLETED_TODOS) "selected" else null) { +"Completed" } } } +clearButton } } } }
apache-2.0
34e758220eb79b37dc91e1970dd4eede
35.130435
128
0.505217
4.675422
false
false
false
false
leafclick/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestCaseExt.kt
1
16798
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.impl import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader import com.intellij.testGuiFramework.driver.ExtendedJTreePathFinder import com.intellij.testGuiFramework.fixtures.ActionButtonFixture import com.intellij.testGuiFramework.fixtures.GutterFixture import com.intellij.testGuiFramework.fixtures.IdeFrameFixture import com.intellij.testGuiFramework.fixtures.extended.ExtendedJTreePathFixture import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.framework.toPrintable import com.intellij.testGuiFramework.util.* import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.LocationUnavailableException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.timing.Timeout import org.hamcrest.Matcher import org.junit.Assert.assertTrue import org.junit.rules.ErrorCollector import java.awt.IllegalComponentStateException import javax.swing.JTree fun <T> ErrorCollector.checkThat(value: T, matcher: Matcher<T>, reason: () -> String) { checkThat(reason(), value, matcher) } /** * Closes the current project * */ fun GuiTestCase.closeProject() { ideFrame { step("close the project") { waitAMoment() closeProject() } } } /** * Provide waiting for background tasks to finish * This function should be used instead of [IdeFrameFixture.waitForBackgroundTasksToFinish] * because sometimes the latter doesn't wait enough time * The function searches for async icon indicator and waits for its disappearing * This occurs several times as background processes often goes one after another. * */ fun GuiTestCase.waitAMoment() { fun isWaitIndicatorPresent(): Boolean { var result = false ideFrame { result = indexingProcessIconNullable(Timeouts.seconds03) != null } return result } fun waitBackgroundTaskOneAttempt(attempt: Int) { step("wait for background task - attempt #$attempt") { ideFrame { this.waitForBackgroundTasksToFinish() val asyncIcon = indexingProcessIconNullable(Timeouts.seconds03) if (asyncIcon != null) { val timeoutForBackgroundTasks = Timeouts.minutes10 try { step("search and click on async icon") { asyncIcon.click() } step("wait for panel 'Background tasks' disappears") { waitForPanelToDisappear( panelTitle = "Background Tasks", timeoutToAppear = Timeouts.seconds01, timeoutToDisappear = timeoutForBackgroundTasks ) } } catch (ignore: NullPointerException) { // if asyncIcon disappears at once after getting the NPE from fest might occur // but it's ok - nothing to wait anymore } catch (ignore: IllegalComponentStateException) { // do nothing - asyncIcon disappears, background process has stopped } catch (ignore: ComponentLookupException) { // do nothing - panel hasn't appeared and it seems ok } catch (ignore: IllegalStateException) { // asyncIcon searched earlier might disappear at all (it's ok) } catch (ignore: IllegalArgumentException) { // asyncIcon searched earlier might disappear at all (it's ok) } catch (e: WaitTimedOutError) { throw WaitTimedOutError("Background process hadn't finished after ${timeoutForBackgroundTasks.toPrintable()}") } } else logInfo("no async icon found - no background process") } logInfo("attempt #$attempt of waiting for background task finished") } } step("wait for background task") { val maxAttemptsWaitForBackgroundTasks = 5 var currentAttempt = maxAttemptsWaitForBackgroundTasks while (isWaitIndicatorPresent() && currentAttempt >= 0) { waitBackgroundTaskOneAttempt(maxAttemptsWaitForBackgroundTasks - currentAttempt) currentAttempt-- } if (currentAttempt < 0) { throw WaitTimedOutError( "Background processes still continue after $maxAttemptsWaitForBackgroundTasks attempts to wait for their finishing") } logInfo("wait for background task finished") } } /** * Performs test whether the specified item exists in a tree * Note: the dialog with the investigated tree must be open * before using this test * @param expectedItem - expected exact item * @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message * @param predicate - searcher rule, how to compare an item and name. By default they are compared by equality * */ fun GuiTestCase.testTreeItemExist(name: String, vararg expectedItem: String, predicate: FinderPredicate = Predicate.equality, timeout: Timeout = Timeouts.defaultTimeout) { ideFrame { logInfo("Check that $name -> ${expectedItem.joinToString(" -> ")} exists in a tree element") kotlin.assert(exists { jTree(*expectedItem, predicate = predicate, timeout = timeout) }) { "$name '${expectedItem.joinToString(", ")}' not found" } } } /** * Performs test whether the specified item exists in a list * Note: the dialog with the investigated list must be open * before using this test * @param expectedItem - expected exact item * @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message * */ fun GuiTestCase.testListItemExist(name: String, expectedItem: String) { ideFrame { logInfo("Check that $name -> $expectedItem exists in a list element") kotlin.assert(exists { jList(expectedItem, timeout = Timeouts.seconds05) }) { "$name '$expectedItem' not found" } } } /** * Performs test whether the specified item exists in a table * Note: the dialog with the investigated list must be open * before using this test * @param expectedItem - expected exact item * @param name - name of item kind, such as "Library" or "Facet". Used for understandable error message * */ fun GuiTestCase.testTableItemExist(name: String, expectedItem: String) { ideFrame { logInfo("Check that $name -> $expectedItem exists in a list element") kotlin.assert(exists { table(expectedItem, timeout = Timeouts.seconds05) }) { "$name '$expectedItem' not found" } } } /** * Selects specified [path] in the tree by keyboard searching * @param path in string form * @param testCase - test case is required only because of keyboard related functions * * TODO: remove [testCase] parameter (so move [shortcut] and [typeText] functions * out of GuiTestCase) * */ fun ExtendedJTreePathFixture.selectWithKeyboard(testCase: GuiTestCase, vararg path: String) { fun currentValue(): String { val selectedRow = target().selectionRows.first() return valueAt(selectedRow) ?: throw IllegalStateException("Nothing is selected in the tree") } click() testCase.shortcut(Key.HOME) // select the top row for((index, step) in path.withIndex()){ if(currentValue() != step) { testCase.typeText(step) while (currentValue() != step) testCase.shortcut(Key.DOWN) } if(index < path.size -1) testCase.shortcut(Key.RIGHT) } } /** * Wait for Gradle reimport finishing * I detect end of reimport by following signs: * - action button "Refresh all external projects" becomes enable. But sometimes it becomes * enable only for a couple of moments and becomes disable again. * - status in the first line in the Build tool window becomes `sync finished` or `sync failed` * * @param rootPath root name expected to be shown in the tree. Checked only if [waitForProject] is true * @return status of reimport - true - successful, false - failed * */ fun GuiTestCase.waitForGradleReimport(rootPath: String): Boolean { val syncSuccessful = "sync finished" val syncFailed = "sync failed" var reimportStatus = "" step("wait for Gradle reimport") { GuiTestUtilKt.waitUntil("for gradle reimport finishing", timeout = Timeouts.minutes05) { var isReimportButtonEnabled: Boolean = false var syncState = false try { ideFrame { toolwindow(id = "Gradle") { content(tabName = "") { // first, check whether the action button "Refresh all external projects" is enabled val text = "Refresh all external projects" isReimportButtonEnabled = try { val fixtureByTextAnyState = ActionButtonFixture.fixtureByTextAnyState(this.target(), robot(), text) assertTrue("Gradle refresh button should be visible and showing", this.target().isShowing && this.target().isVisible) fixtureByTextAnyState.isEnabled } catch (e: Exception) { false } logInfo("'$text' button is ${if(isReimportButtonEnabled) "enabled" else "disabled"}") } } // second, check status in the Build tool window toolwindow(id = "Build") { content(tabName = "Sync") { val tree = treeTable().target().tree val pathStrings = listOf(rootPath) val treePath = try { ExtendedJTreePathFinder(tree).findMatchingPathByPredicate(pathStrings = pathStrings, predicate = Predicate.startWith) } catch (e: LocationUnavailableException) { null } if (treePath != null) { reimportStatus = ExtendedJTreeCellReader().valueAtExtended(tree, treePath) ?: "" syncState = reimportStatus.contains(syncSuccessful) || reimportStatus.contains(syncFailed) } else { syncState = false } logInfo("Reimport status is '$reimportStatus', synchronization is ${if(syncState) "finished" else "in process"}") } } } } catch (ignore: Exception) {} // final calculating of result val result = isReimportButtonEnabled && syncState result } logInfo("end of waiting for background task") } return reimportStatus.contains(syncSuccessful) } fun GuiTestCase.gradleReimport() { step("reimport gradle project") { ideFrame { toolwindow(id = "Gradle") { content(tabName = "") { waitAMoment() step("click 'Refresh all external projects' button") { actionButton("Refresh all external projects", timeout = Timeouts.minutes05).click() } } } } } } fun GuiTestCase.mavenReimport() { step("reimport maven project") { ideFrame { toolwindow(id = "Maven") { content(tabName = "") { step("search when button 'Reimport All Maven Projects' becomes enable and click it") { val reimportAction = "Reimport All Maven Projects" val showDepAction = "Show UML Diagram" // but tooltip says "Show Dependencies" GuiTestUtilKt.waitUntil("Wait for button '$reimportAction' to be enabled.", timeout = Timeouts.minutes02) { actionButton(reimportAction, timeout = Timeouts.seconds30).isEnabled } try { actionButton(showDepAction, timeout = Timeouts.minutes01) } catch (ignore: ComponentLookupException) { logInfo("Maven reimport: not found 'Show Dependencies' button after 1 min waiting") } robot().waitForIdle() actionButton(reimportAction).click() robot().waitForIdle() } } } } } } fun GuiTestCase.checkProjectIsCompiled(expectedStatus: String) { val textEventLog = "Event Log" ideFrame { step("check the project compiles") { step("invoke main menu 'CompileProject' ") { invokeMainMenu("CompileProject") } waitAMoment() toolwindow(id = textEventLog) { content(tabName = "") { editor { GuiTestUtilKt.waitUntil("Wait for '$expectedStatus' appears") { val output = this.getCurrentFileContents(false)?.lines() ?: emptyList() val lastLine = output.lastOrNull { it.trim().isNotEmpty() } ?: "" lastLine.contains(expectedStatus) } } } } } } } fun GuiTestCase.checkProjectIsRun(configuration: String, message: String) { val buttonRun = "Run" step("run configuration `$configuration`") { ideFrame { navigationBar { actionButton(buttonRun).click() } waitAMoment() toolwindow(id = buttonRun) { content(tabName = configuration) { editor { GuiTestUtilKt.waitUntil("Wait for '$message' appears") { val output = this.getCurrentFileContents(false)?.lines()?.filter { it.trim().isNotEmpty() } ?: listOf() logInfo("output: ${output.map { "\n\t$it" }}") logInfo("expected message = '$message'") output.firstOrNull { it.contains(message) } != null } } } } } } } fun GuiTestCase.checkGutterIcons(gutterIcon: GutterFixture.GutterIcon, expectedNumberOfIcons: Int, expectedLines: List<String>) { ideFrame { step("check whether $expectedNumberOfIcons '$gutterIcon' gutter icons are present") { editor { step("wait for editor file has been loaded") { waitUntilFileIsLoaded() waitAMoment() waitUntilErrorAnalysisFinishes() } } editor { step("wait for gutter icons appearing") { gutter.waitUntilIconsShown(mapOf(gutterIcon to expectedNumberOfIcons)) moveToLine(expectedNumberOfIcons) } val gutterLinesWithIcon = gutter.linesWithGutterIcon(gutterIcon) val contents = [email protected](false)?.lines() ?: listOf() for ((index, line) in gutterLinesWithIcon.withIndex()) { // line numbers start with 1, but index in the contents list starts with 0 val currentLine = contents[line - 1] val expectedLine = expectedLines[index] logInfo("Found line '$currentLine' with icon '$gutterIcon'. Expected line is '$expectedLine'") assert(currentLine.contains(expectedLine)) { "At line #$line the actual text is `$currentLine`, but it was expected `$expectedLine`" } } } } } } fun GuiTestCase.createJdk(jdkPath: String, jdkName: String = ""): String{ val dialogName = "Project Structure for New Projects" return step("create a JDK on the path `$jdkPath`") { lateinit var installedJdkName: String welcomeFrame { actionLink("Configure").click() popupMenu("Structure for New Projects").clickSearchedItem() step("open `$dialogName` dialog") { dialog(dialogName) { jList("SDKs").clickItem("SDKs") val sdkTree: ExtendedJTreePathFixture = jTree() fun JTree.getListOfInstalledSdks(): List<String> { val root = model.root return (0 until model.getChildCount(root)) .map { model.getChild(root, it).toString() }.toList() } val preInstalledSdks = sdkTree.tree.getListOfInstalledSdks() installedJdkName = if (jdkName.isEmpty() || preInstalledSdks.contains(jdkName).not()) { actionButton("Add New SDK").click() popupMenu("JDK").clickSearchedItem() step("open `Select Home Directory for JDK` dialog") { dialog("Select Home Directory for JDK") { actionButton("Refresh").click() step("type the path `$jdkPath`") { typeText(jdkPath) } step("close `Select Home Directory for JDK` dialog with OK") { button("OK").click() } } } val postInstalledSdks = sdkTree.tree.getListOfInstalledSdks() postInstalledSdks.first { preInstalledSdks.contains(it).not() } } else jdkName step("close `Default Project Structure` dialog with OK") { button("OK").click() } } // dialog Project Structure } } // ideFrame return@step installedJdkName } } fun <T1, T2, R> combine(first: Iterable<T1>, second: Iterable<T2>, combiner: (T1, T2) -> R): List<R> = first.flatMap { firstItem -> second.map { secondItem -> combiner(firstItem, secondItem) } }
apache-2.0
7a7e8b0f43d7643c7bed2128d9aa9d8a
38.431925
171
0.643946
4.803546
false
true
false
false
leafclick/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyStubPackages.kt
1
5542
// 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. @file:JvmName("PyStubPackages") package com.jetbrains.python.codeInsight.typing import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.util.QualifiedName import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.psi.resolve.RatedResolveResult import com.jetbrains.python.pyi.PyiFile import com.jetbrains.python.pyi.PyiUtil const val STUBS_SUFFIX = "-stubs" private val STUB_PACKAGE_KEY = Key<Boolean>("PY_STUB_PACKAGE") private val INLINE_PACKAGE_KEY = Key<Boolean>("PY_INLINE_PACKAGE") /** * If [name] argument points to element in stub package, * then [name] would be copied and `-stubs` suffix would be removed from the first component, * otherwise [name] would be returned. */ fun convertStubToRuntimePackageName(name: QualifiedName): QualifiedName { val top = name.firstComponent if (top != null && top.endsWith(STUBS_SUFFIX)) { return QualifiedName.fromComponents(name.components).apply { components[0] = components[0].dropLast(STUBS_SUFFIX.length) } } return name } /** * Returns stub package directory in the specified [dir] for the package with [referencedName] as a name. * * Requires [withoutStubs] to be False and [dir] to be lib root. */ fun findStubPackage(dir: PsiDirectory, referencedName: String, checkForPackage: Boolean, withoutStubs: Boolean): PsiDirectory? { if (!withoutStubs && dir.virtualFile.let { it == getClassOrContentOrSourceRoot(dir.project, it) }) { val stubPackageName = "$referencedName$STUBS_SUFFIX" val stubPackage = dir.findSubdirectory(stubPackageName) // see comment about case sensitivity in com.jetbrains.python.psi.resolve.ResolveImportUtil.resolveInDirectory if (stubPackage?.name == stubPackageName && (!checkForPackage || PyUtil.isPackage(stubPackage, dir))) { doTransferStubPackageMarker(stubPackage) return stubPackage } } return null } /** * Puts special mark to module resolved in stub package. */ fun transferStubPackageMarker(dir: PsiDirectory, resolvedSubmodule: PsiFile): PsiFile { if (dir.getUserData(STUB_PACKAGE_KEY) == true) resolvedSubmodule.putUserData(STUB_PACKAGE_KEY, true) return resolvedSubmodule } /** * Puts special mark to dir resolved in stub package. */ fun transferStubPackageMarker(dir: PsiDirectory, resolvedSubdir: PsiDirectory): PsiDirectory { if (dir.getUserData(STUB_PACKAGE_KEY) == true) doTransferStubPackageMarker(resolvedSubdir) return resolvedSubdir } private fun doTransferStubPackageMarker(resolvedSubdir: PsiDirectory) { resolvedSubdir.putUserData(STUB_PACKAGE_KEY, true) PyUtil.turnDirIntoInit(resolvedSubdir)?.putUserData(STUB_PACKAGE_KEY, true) } fun removeRuntimeModulesForWhomStubModulesFound(resolved: List<RatedResolveResult>): List<RatedResolveResult> { val stubPkgModules = mutableSetOf<String>() resolved.forEach { val stubPkgModule = it.element if (stubPkgModule is PyiFile && stubPkgModule.getUserData(STUB_PACKAGE_KEY) == true) stubPkgModules += stubPkgModule.name } return if (stubPkgModules.isEmpty()) resolved else resolved.filterNot { val runtimePkgModule = it.element runtimePkgModule is PyFile && runtimePkgModule !is PyiFile && stubPkgModules.contains(runtimePkgModule.name + "i") // py -> pyi } } private fun getClassOrContentOrSourceRoot(project: Project, file: VirtualFile): VirtualFile? { val index = ProjectFileIndex.getInstance(project) index.getClassRootForFile(file)?.let { return it } index.getSourceRootForFile(file)?.let { return it } index.getContentRootForFile(file)?.let { return it } return null } /** * See [findStubPackage] and [transferStubPackageMarker]. */ fun isInStubPackage(element: PsiElement) = element.getUserData(STUB_PACKAGE_KEY) == true /** * See [https://www.python.org/dev/peps/pep-0561/#packaging-type-information]. * Value is cached in element's user data. */ internal fun isInInlinePackage(element: PsiElement, module: Module?): Boolean { if (module == null) return false val cached = element.getUserData(INLINE_PACKAGE_KEY) if (cached != null) return cached val result = !PyiUtil.isPyiFileOfPackage(element) && (element is PyFile || PyUtil.turnDirIntoInit(element) is PyFile) && getPyTyped(element) != null element.putUserData(INLINE_PACKAGE_KEY, result) return result } /** * See [https://www.python.org/dev/peps/pep-0561/#packaging-type-information] */ private fun getPyTyped(element: PsiElement?): VirtualFile? { if (element == null) return null val file = if (element is PsiFileSystemItem) element.virtualFile else element.containingFile?.virtualFile if (file == null) return null val root = getClassOrContentOrSourceRoot(element.project, file) ?: return null var current = if (file.isDirectory) file else file.parent while (current != null && current != root && current.isDirectory) { val pyTyped = current.findChild("py.typed") if (pyTyped != null && !pyTyped.isDirectory) return pyTyped current = current.parent } return null }
apache-2.0
b153e3762dc5b6c3411e0f5da0131a0a
35.946667
150
0.752977
3.989921
false
false
false
false
JuliusKunze/kotlin-native
performance/src/main/kotlin/org/jetbrains/ring/LambdaBenchmark.kt
2
2583
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.ring var globalAddendum = 0 open class LambdaBenchmark { private fun <T> runLambda(x: () -> T): T = x() private fun <T> runLambdaNoInline(x: () -> T): T = x() fun setup() { globalAddendum = Random.nextInt(20) } //Benchmark fun noncapturingLambda(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda { globalAddendum } } return x } //Benchmark fun noncapturingLambdaNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline { globalAddendum } } return x } //Benchmark fun capturingLambda(): Int { val addendum = globalAddendum + 1 var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda { addendum } } return x } //Benchmark fun capturingLambdaNoInline(): Int { val addendum = globalAddendum + 1 var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline { addendum } } return x } //Benchmark fun mutatingLambda(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { runLambda { x += globalAddendum } } return x } //Benchmark fun mutatingLambdaNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { runLambdaNoInline { x += globalAddendum } } return x } //Benchmark fun methodReference(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambda(::referenced) } return x } //Benchmark fun methodReferenceNoInline(): Int { var x: Int = 0 for (i in 0..BENCHMARK_SIZE) { x += runLambdaNoInline(::referenced) } return x } } private fun referenced(): Int { return globalAddendum }
apache-2.0
874fa368f1d2a0cc7c0090aae1a01de6
23.367925
75
0.56446
4.283582
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddReifiedToTypeParameterOfFunctionFix.kt
2
1880
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class AddReifiedToTypeParameterOfFunctionFix( typeParameter: KtTypeParameter, function: KtNamedFunction ) : AddModifierFix(typeParameter, KtTokens.REIFIED_KEYWORD) { private val inlineFix = AddInlineToFunctionWithReifiedFix(function) private val elementName = getElementName(function) override fun getText() = element?.let { KotlinBundle.message("fix.make.type.parameter.reified", getElementName(it), elementName) } ?: "" override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) { super.invokeImpl(project, editor, file) inlineFix.invoke(project, editor, file) } companion object Factory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val element = Errors.TYPE_PARAMETER_AS_REIFIED.cast(diagnostic) val function = element.psiElement.getStrictParentOfType<KtNamedFunction>() val parameter = function?.typeParameterList?.parameters?.getOrNull(element.a.index) ?: return null return AddReifiedToTypeParameterOfFunctionFix(parameter, function) } } }
apache-2.0
61b99dbf832a6f61852be998f86a8333
44.878049
158
0.773404
4.676617
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/tests/git4idea/commands/GitHttpGuiAuthenticatorTest.kt
5
4675
// 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 git4idea.commands import com.intellij.credentialStore.Credentials import com.intellij.dvcs.DvcsRememberedInputs import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.openapi.components.service import com.intellij.openapi.ui.DialogWrapper import git4idea.commands.GitHttpGuiAuthenticator.PasswordSafeProvider.credentialAttributes import git4idea.commands.GitHttpGuiAuthenticator.PasswordSafeProvider.makeKey import git4idea.remote.GitRememberedInputs import git4idea.test.GitPlatformTest import git4idea.test.TestDialogHandler import java.io.File import javax.swing.UIManager class GitHttpGuiAuthenticatorTest : GitPlatformTest() { private lateinit var rememberedInputs: DvcsRememberedInputs private lateinit var passwordSafe: PasswordSafe private var dialogShown = false @Throws(Exception::class) public override fun setUp() { super.setUp() // otherwise login dialog doesn't work (missing LaF for JBOptionButton) UIManager.setLookAndFeel("com.intellij.ide.ui.laf.darcula.DarculaLaf") rememberedInputs = service<GitRememberedInputs>() passwordSafe = service() } @Throws(Exception::class) public override fun tearDown() { dialogShown = false rememberedInputs.clear() passwordSafe.set(CREDENTIAL_ATTRIBUTES, null) super.tearDown() } fun `test data saved when correct`() { registerDialogHandler(true) runAuthenticator(true) assertTrue(dialogShown) assertSavedPasswordEquals(TEST_PASSWORD) assertEquals(TEST_LOGIN, rememberedInputs.getUserNameForUrl(TEST_URL)) } fun `test password not saved when incorrect`() { registerDialogHandler(true) runAuthenticator(false) assertTrue(dialogShown) assertSavedPasswordEquals(null) } fun `test incorrect saved password forgotten`() { registerDialogHandler(true) rememberedInputs.addUrl(TEST_URL, TEST_LOGIN) passwordSafe.set(CREDENTIAL_ATTRIBUTES, Credentials(TEST_PSAFE_KEY, TEST_PASSWORD)) runAuthenticator(false) assertFalse(dialogShown) assertSavedPasswordEquals(null) } fun `test password not remembered`() { registerDialogHandler(true, false) runAuthenticator(true) assertTrue(dialogShown) assertSavedPasswordEquals(null) } fun `test dialog cancellation propagated`() { registerDialogHandler(false) val authenticator = runAuthenticator(false) assertTrue(dialogShown) assertTrue(authenticator.wasCancelled()) assertSavedPasswordEquals(null) } fun `test single dialog shown`() { registerDialogHandler(true) val authenticator = GitHttpGuiAuthenticator(project, listOf(TEST_URL), File(""), GitPassthroughAuthenticationGate.instance, GitAuthenticationMode.FULL) authenticator.askUsername(TEST_URL) assertTrue(dialogShown) dialogShown = false authenticator.askPassword(TEST_URL) assertFalse(dialogShown) } private fun registerDialogHandler(exitOk: Boolean, rememberPassword: Boolean = true) { dialogManager.registerDialogHandler(GitHttpLoginDialog::class.java, TestDialogHandler { dialogShown = true it.username = TEST_LOGIN it.password = TEST_PASSWORD it.rememberPassword = rememberPassword if (exitOk) DialogWrapper.OK_EXIT_CODE else DialogWrapper.CANCEL_EXIT_CODE }) } private fun runAuthenticator(assumeCorrect: Boolean): GitHttpGuiAuthenticator { val authenticator = GitHttpGuiAuthenticator(project, listOf(TEST_URL), File(""), GitPassthroughAuthenticationGate.instance, GitAuthenticationMode.FULL) val username = authenticator.askUsername(TEST_URL) val password = authenticator.askPassword(TEST_URL) if (assumeCorrect) { assertEquals(TEST_LOGIN, username) assertEquals(TEST_PASSWORD, password) authenticator.saveAuthData() } else { authenticator.forgetPassword() } return authenticator } private fun assertSavedPasswordEquals(match: String?) { assertEquals(match, passwordSafe.getPassword(CREDENTIAL_ATTRIBUTES)) } companion object { private const val TEST_URL = "http://nonexistent.site/repo.git" private const val TEST_LOGIN = "smith" private const val TEST_PASSWORD = "pwd" private val TEST_PSAFE_KEY = makeKey(TEST_URL, TEST_LOGIN) private val CREDENTIAL_ATTRIBUTES = credentialAttributes(TEST_PSAFE_KEY) } }
apache-2.0
e32205e134d7c7d2fc8e2f65e683428c
31.248276
140
0.731337
4.642502
false
true
false
false
LouisCAD/Splitties
modules/collections/src/commonMain/kotlin/splitties/collections/Lists.kt
1
4371
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.collections /** * Iterates the receiver [List] using an index instead of an [Iterator] like [forEach] would do. * Using this function saves an [Iterator] allocation, which is good for immutable lists or usages * confined to a single thread like UI thread only use. * However, this method will not detect concurrent modification, except if the size of the list * changes on an iteration as a result, which may lead to unpredictable behavior. * * @param action the action to invoke on each list element. */ inline fun <T> List<T>.forEachByIndex(action: (T) -> Unit) { val initialSize = size for (i in 0..lastIndex) { if (size != initialSize) throw ConcurrentModificationException() action(get(i)) } } /** * Iterates the receiver [List] using an index instead of an [Iterator] like [forEachIndexed] would * do. Using this function saves an [Iterator] allocation, which is good for immutable lists or * usages confined to a single thread like UI thread only use. * However, this method will not detect concurrent modification, except if the size of the list * changes on an iteration as a result, which may lead to unpredictable behavior. * * @param action the action to invoke on each list element. */ inline fun <T> List<T>.forEachWithIndex(action: (Int, T) -> Unit) { val initialSize = size for (i in 0..lastIndex) { if (size != initialSize) throw ConcurrentModificationException() action(i, get(i)) } } /** * Iterates the receiver [List] using an index instead of an [Iterator] like [forEach] would do, but * in reverse order (from last index down to zero). * Using this function saves an [Iterator] allocation, which is good for immutable lists or usages * confined to a single thread like UI thread only use. * However, this method will not detect concurrent modification, except if the size of the list * changes on an iteration as a result, which may lead to unpredictable behavior. * * @param action the action to invoke on each list element. */ inline fun <T> List<T>.forEachReversedByIndex(action: (T) -> Unit) { val initialSize = size for (i in lastIndex downTo 0) { if (size != initialSize) throw ConcurrentModificationException() action(get(i)) } } /** * Iterates the receiver [List] using an index instead of an [Iterator] like [forEachIndexed] would * do, but in reverse order (from last index down to zero). Using this function saves an [Iterator] * allocation, which is good for immutable lists or usages confined to a single thread like * UI thread only use. However, this method will not detect concurrent modification, except if the * size of the list changes on an iteration as a result, which may lead to unpredictable behavior. * * @param action the action to invoke on each list element. */ inline fun <T> List<T>.forEachReversedWithIndex(action: (Int, T) -> Unit) { val initialSize = size for (i in lastIndex downTo 0) { if (size != initialSize) throw ConcurrentModificationException() action(i, get(i)) } } /** * Iterates the receiver [List] using an index instead of an [Iterator] like [forEachIndexed] would * do, but in reverse order (from last index down to zero). Using this function saves an [Iterator] * allocation, which is good for immutable lists or usages confined to a single thread like * UI thread only use. However, this method will not detect all concurrent modification. * * If [allowSafeModifications] is true, you can mutate the list while iterating as long as iterating * down is still possible (otherwise a [ConcurrentModificationException] is thrown). * * @param action the action to invoke on each list element. */ inline fun <T> List<T>.forEachReversedWithIndex( allowSafeModifications: Boolean = false, action: (Int, T) -> Unit ) { val initialSize = size for (i in lastIndex downTo 0) { when { allowSafeModifications && i > lastIndex -> { throw ConcurrentModificationException() } allowSafeModifications.not() && size != initialSize -> { throw ConcurrentModificationException() } } action(i, get(i)) } }
apache-2.0
8c615d27e973e186ae68a32967e48a28
41.852941
109
0.703729
4.260234
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/immutable/ImmutableTransformationSupport.kt
19
1602
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.transformations.immutable import com.intellij.psi.CommonClassNames.JAVA_UTIL_MAP import org.jetbrains.plugins.groovy.lang.psi.impl.booleanValue import org.jetbrains.plugins.groovy.lang.psi.impl.findDeclaredDetachedValue import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_TRANSFORM_IMMUTABLE import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport import org.jetbrains.plugins.groovy.transformations.TransformationContext import org.jetbrains.plugins.groovy.transformations.plusAssign class ImmutableTransformationSupport : AstTransformationSupport { override fun applyTransformation(context: TransformationContext) { val annotation = context.getAnnotation(GROOVY_TRANSFORM_IMMUTABLE) ?: context.getAnnotation(GROOVY_TRANSFORM_IMMUTABLE_BASE) ?: return if (annotation.findDeclaredDetachedValue(immutableCopyWith)?.booleanValue() != true) return if (context.fields.isEmpty()) return if (context.findMethodsByName(immutableCopyWith, false).any { it.parameters.size == 1 }) return context += context.memberBuilder.method(immutableCopyWith) { addParameter("args", JAVA_UTIL_MAP) returnType = createType(context.codeClass) navigationElement = annotation methodKind = immutableCopyWithKind originInfo = immutableOrigin } } }
apache-2.0
b0ab48a7d74c4ae9c9651182f06fd1f9
54.241379
140
0.809613
4.590258
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt
1
5602
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.completion.AllClassesGetter import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.psi.PsiClass import com.intellij.psi.PsiLiteral import com.intellij.psi.search.PsiShortNamesCache import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.ClassifierDescriptorWithTypeParameters import org.jetbrains.kotlin.idea.caches.KotlinShortNamesCache import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper import org.jetbrains.kotlin.idea.core.isJavaClassNotToBeUsedInKotlin import org.jetbrains.kotlin.idea.project.TargetPlatformDetector import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.load.java.JvmAnnotationNames import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered class AllClassesCompletion( private val parameters: CompletionParameters, private val kotlinIndicesHelper: KotlinIndicesHelper, private val prefixMatcher: PrefixMatcher, private val resolutionFacade: ResolutionFacade, private val kindFilter: (ClassKind) -> Boolean, private val includeTypeAliases: Boolean, private val includeJavaClassesNotToBeUsed: Boolean ) { fun collect(classifierDescriptorCollector: (ClassifierDescriptorWithTypeParameters) -> Unit, javaClassCollector: (PsiClass) -> Unit) { //TODO: this is a temporary solution until we have built-ins in indices // we need only nested classes because top-level built-ins are all added through default imports for (builtInPackage in resolutionFacade.moduleDescriptor.builtIns.builtInPackagesImportedByDefault) { collectClassesFromScope(builtInPackage.memberScope) { if (it.containingDeclaration is ClassDescriptor) { classifierDescriptorCollector(it) } } } kotlinIndicesHelper.processKotlinClasses( { prefixMatcher.prefixMatches(it) }, kindFilter = kindFilter, processor = classifierDescriptorCollector ) if (includeTypeAliases) { kotlinIndicesHelper.processTopLevelTypeAliases(prefixMatcher.asStringNameFilter(), classifierDescriptorCollector) } if (TargetPlatformDetector.getPlatform(parameters.originalFile as KtFile).isJvm()) { addAdaptedJavaCompletion(javaClassCollector) } } private fun collectClassesFromScope(scope: MemberScope, collector: (ClassDescriptor) -> Unit) { for (descriptor in scope.getDescriptorsFiltered(DescriptorKindFilter.CLASSIFIERS)) { if (descriptor is ClassDescriptor) { if (kindFilter(descriptor.kind) && prefixMatcher.prefixMatches(descriptor.name.asString())) { collector(descriptor) } collectClassesFromScope(descriptor.unsubstitutedInnerClassesScope, collector) } } } private fun addAdaptedJavaCompletion(collector: (PsiClass) -> Unit) { val shortNamesCache = PsiShortNamesCache.EP_NAME.getExtensions(parameters.editor.project).firstOrNull { it is KotlinShortNamesCache } as KotlinShortNamesCache? shortNamesCache?.disableSearch?.set(true) try { AllClassesGetter.processJavaClasses(parameters, prefixMatcher, true) { psiClass -> if (psiClass!! !is KtLightClass) { // Kotlin class should have already been added as kotlin element before if (psiClass.isSyntheticKotlinClass()) return@processJavaClasses // filter out synthetic classes produced by Kotlin compiler val kind = when { psiClass.isAnnotationType -> ClassKind.ANNOTATION_CLASS psiClass.isInterface -> ClassKind.INTERFACE psiClass.isEnum -> ClassKind.ENUM_CLASS else -> ClassKind.CLASS } if (kindFilter(kind) && !isNotToBeUsed(psiClass)) { collector(psiClass) } } } } finally { shortNamesCache?.disableSearch?.set(false) } } private fun PsiClass.isSyntheticKotlinClass(): Boolean { if ('$' !in name!!) return false // optimization to not analyze annotations of all classes val metadata = modifierList?.findAnnotation(JvmAnnotationNames.METADATA_FQ_NAME.asString()) return (metadata?.findAttributeValue(JvmAnnotationNames.KIND_FIELD_NAME) as? PsiLiteral)?.value == KotlinClassHeader.Kind.SYNTHETIC_CLASS.id } private fun isNotToBeUsed(javaClass: PsiClass): Boolean { if (includeJavaClassesNotToBeUsed) return false val fqName = javaClass.getKotlinFqName() return fqName != null && isJavaClassNotToBeUsedInKotlin(fqName) } }
apache-2.0
7f2f35927dab673734d21c27d0b03dba
47.713043
158
0.714745
5.444121
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertOrdinaryPropertyToLazyIntention.kt
4
1683
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern class ConvertOrdinaryPropertyToLazyIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("convert.to.lazy.property") ) { override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean = !element.isVar && element.initializer != null && element.getter == null && !element.isLocal && !element.hasModifier(KtTokens.CONST_KEYWORD) override fun applyTo(element: KtProperty, editor: Editor?) { val initializer = element.initializer ?: return val psiFactory = KtPsiFactory(element) val newExpression = if (initializer is KtCallExpression && initializer.isCalling(FqName("kotlin.run"))) { initializer.calleeExpression?.replace(psiFactory.createExpression("lazy")) initializer } else { psiFactory.createExpressionByPattern("lazy { $0 }", initializer) } element.addAfter(psiFactory.createPropertyDelegate(newExpression), initializer) element.initializer = null } }
apache-2.0
8ad40a57bd44f9ee0959d048e37343a8
48.5
158
0.751634
4.808571
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/editor/quickDoc/OnMethodUsageWithTypeParameter.kt
9
1525
/** Some documentation * @param T the type parameter * @param a Some int * @param b String */ fun <T> testMethod(a: Int, b: String) { } fun test() { <caret>testMethod(1, "value") } //INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">fun</span> <span style="">&lt;</span><span style="color:#20999d;">T</span><span style="">&gt;</span> <span style="color:#000000;">testMethod</span>( //INFO: <span style="color:#000000;">a</span><span style="">: </span><span style="color:#000000;">Int</span>, //INFO: <span style="color:#000000;">b</span><span style="">: </span><span style="color:#000000;">String</span> //INFO: )<span style="">: </span><span style="color:#000000;">Unit</span></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Some documentation</p></div><table class='sections'><tr><td valign='top' class='section'><p>Params:</td><td valign='top'><p><code><a href="psi_element://T"><code style='font-size:96%;'><span style="color:#20999d;">T</span></code></a></code> - the type parameter<p><code><a href="psi_element://a"><code style='font-size:96%;'><span style="color:#0000ff;">a</span></code></a></code> - Some int<p><code><a href="psi_element://b"><code style='font-size:96%;'><span style="color:#0000ff;">b</span></code></a></code> - String</td></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/>&nbsp;OnMethodUsageWithTypeParameter.kt<br/></div>
apache-2.0
1f3483a776662b47e155d5caaef4f401
79.263158
809
0.651803
3.15735
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-api/src/org/jetbrains/kotlin/idea/frontend/api/symbols/DebugSymbolRenderer.kt
2
3046
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.frontend.api.symbols import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.* import org.jetbrains.kotlin.idea.frontend.api.types.KtType import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import java.lang.reflect.InvocationTargetException import kotlin.reflect.KProperty import kotlin.reflect.jvm.javaGetter object DebugSymbolRenderer { fun render(symbol: KtSymbol): String = buildString { val klass = symbol::class appendLine("${klass.simpleName}:") klass.members.filterIsInstance<KProperty<*>>().sortedBy { it.name }.forEach { property -> if (property.name in ignoredPropertyNames) return@forEach val getter = property.javaGetter ?: return@forEach val value = try { getter.invoke(symbol) } catch (e: InvocationTargetException) { "Could not render due to ${e.cause}" } val stringValue = renderValue(value) appendLine(" ${property.name}: $stringValue") } } private fun renderValue(value: Any?): String = when (value) { null -> "null" is String -> value is Boolean -> value.toString() is Long -> value.toString() is Name -> value.asString() is FqName -> value.asString() is ClassId -> value.asString() is Enum<*> -> value.name is List<*> -> buildString { append("[") value.joinTo(this) { renderValue(it) } append("]") } is KtType -> value.asStringForDebugging() is KtSymbol -> { val symbolTag = when (value) { is KtClassLikeSymbol -> renderValue(value.classIdIfNonLocal ?: "<local>/${value.name}") is KtFunctionSymbol -> renderValue(value.callableIdIfNonLocal ?: "<local>/${value.name}") is KtConstructorSymbol -> "<constructor>" is KtNamedSymbol -> renderValue(value.name) is KtPropertyGetterSymbol -> "<getter>" is KtPropertySetterSymbol -> "<setter>" else -> TODO(value::class.toString()) } "${value::class.simpleName!!}($symbolTag)" } is KtSimpleConstantValue<*> -> renderValue(value.value) is KtNamedConstantValue -> "${renderValue(value.name)} = ${renderValue(value.expression)}" is KtAnnotationCall -> "${renderValue(value.classId)}${value.arguments.joinToString(prefix = "(", postfix = ")") { renderValue(it) }}" is KtTypeAndAnnotations -> "${renderValue(value.annotations)} ${renderValue(value.type)}" else -> value::class.simpleName!! } private val ignoredPropertyNames = setOf("firRef", "psi", "token") }
apache-2.0
db1df1f1ca48ca54acc8b126692fdc55
42.528571
123
0.621799
4.812006
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/copy/kt18149/after/refactor/copy2/test.kt
13
4411
package refactor.copy2 import refactor.ParentJava import kotlin.properties.Delegates enum class Possible { NO, YES } data class Potable(val p1: String) class Insider(val peace: String) class Init { fun referred() = 0 fun moved() = referred() } interface FaceToFace { fun extract() } abstract class AbsToAbs { abstract fun extract() } class Simple { fun extract() {} } annotation class MemAnn class Variety<C> { // object object ExtractedObject {} // function tailrec fun tailrecFun(p: Int) { if (p > 0) tailrecFun(p - 1) } operator fun plus(other: Variety<C>) {} infix fun infixFun(other: Variety<C>) {} inline fun inlineFun(f: () -> Int) = f() external fun externalFun() internal fun internalFun() = 0 protected fun protectedFun() = 0 private fun privateFun() = 0 fun <T> genFunB(p: T): T = p fun <T> genFunC(p: T): C where T : C = p @MemAnn fun annotatedFun() = 0 final fun finalFun() = 0 // property var publicProp = 0 internal var internalProp = 0 protected var protectedProp = 0 private var privateProp = 0 var <T> List<T>.genVarJ: T get() = last() set(p) {} var <T> List<T>.genVarL: T where T : C get() = last() set(p) {} @MemAnn val annotatedVal = 0 var byVar by Delegates.notNull<Int>() lateinit var lateVal: String final val finalVal = 0 // class class ExtractedClass {} // inner class inner class ExtractedInnerClass {} // anonymousInitializer init {} // secondaryConstructor constructor(p: Int) fun refer(p1: List<String>) { val v1 = ExtractedObject val v2 = ExtractedClass() val v3 = ExtractedInnerClass() val v4 = tailrecFun(2) val v5 = this + this val v6 = this infixFun this val v7 = inlineFun { 7 } val vv = externalFun() val v8 = internalFun() val v9 = protectedFun() val vA = privateFun() val vB = genFunB(0) val vD = annotatedFun() val vw = finalFun() publicProp = publicProp + 1 internalProp = internalProp + 1 protectedProp = protectedProp + 1 privateProp = privateProp + 1 p1.genVarJ = p1.genVarJ + "+" val vK = annotatedVal byVar = byVar + 1 lateVal = lateVal + "+" val vN = finalVal } } fun <C> Variety<C>.extend() {} object VarietyObject { const val constProp = 0 fun refer() { val vE = constProp } } abstract class AbstractVariety { abstract fun abstractFun(): Int abstract var abstractVar: Int fun refer() = abstractFun() + abstractVar } interface FaceVarietyObligation { fun abstractToAbstract() fun abstractToConcrete() fun concreteToConcrete() } interface FaceVariety : FaceVarietyObligation { fun abstractFun() var abstractProperty: String fun concreteFun() {} override fun abstractToAbstract() override fun abstractToConcrete() {} override fun concreteToConcrete() {} } @Suppress("LeakingThis") open class CtorParameter(pp: String, open val pv: String, open var pr: String) { var vb = pp + pv + pr init { vb += pp + pv + pr } constructor() : this("p", "v", "r") fun refer() { pr += pv vb += pr } companion object { val instance = CtorParameter() } } class CtorParameterChild(val pvc: String, var prc: String) : CtorParameter(pvc, pvc, prc) class CtorParameterChild2: CtorParameter { constructor() : super("", "", "") } class CtorParameterChild3(override val pv: String, override var pr: String) : CtorParameter(pv, pv, pr) data class CtorData(val pv: String, var pr: String) {} class Company { companion object { val companyVal = 0 var companyVar = 0 fun companyFun() = 0 class CompanyClass {} object CompanyObject {} } fun refer() { println(companyVal) companyVar = companyVar + 1 println(companyFun()) val v1 = CompanyClass() val v2 = CompanyObject } } fun referCompany() { println(Company.companyVal) Company.companyVar = Company.companyVar + 1 println(Company.companyFun()) val v1 = Company.Companion.CompanyClass() val v2 = Company.Companion.CompanyObject } class JavaChild : ParentJava.FaceJava { override fun inherit() {} }
apache-2.0
fbff68483f33dd5cff5d6ce27886f695
23.786517
103
0.616867
3.779777
false
false
false
false
Peekazoo/Peekazoo-Android
app/src/main/java/com/tofi/peekazoo/models/InkbunnySubmission.kt
1
890
package com.tofi.peekazoo.models /** * Created by Derek on 18/05/2017. * Api response for a submission from Inkbunny */ data class InkbunnySubmission(var submissionId: String = "", var title: String = "", var submissionTypeId: String = "", var thumbnailUrlMedium: String? = null, var thumbnailUrlMediumNoncustom: String? = null, var friendsOnly: String = "", var guestBlock: String = "", var username: String = "", var userId: String = ""): BaseSubmission { override fun fetchTitle(): String { return title } override fun fetchThumbnailUrl(): String? { return thumbnailUrlMedium?: thumbnailUrlMediumNoncustom } }
apache-2.0
530c2b3b43b2a91d073907202a649045
36.125
78
0.511236
5.779221
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt
1
19411
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations import com.intellij.ide.highlighter.JavaFileType import com.intellij.ide.util.EditorHelper import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler import com.intellij.refactoring.rename.RenameUtil import com.intellij.refactoring.util.NonCodeUsageInfo import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.refactoring.util.TextOccurrencesUtil import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewDescriptor import com.intellij.usageView.UsageViewUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.HashingStrategy import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration import org.jetbrains.kotlin.asJava.findFacadeClass import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests import org.jetbrains.kotlin.idea.core.deleteSingle import org.jetbrains.kotlin.idea.core.quoteIfNeeded import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName import org.jetbrains.kotlin.idea.refactoring.move.* import org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories.MoveKotlinClassHandler import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.kotlin.idea.search.restrictByFileType import org.jetbrains.kotlin.idea.util.projectStructure.module import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.utils.ifEmpty import org.jetbrains.kotlin.utils.keysToMap import kotlin.math.max import kotlin.math.min interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration { object Default : Mover { override fun invoke(originalElement: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration { return when (targetContainer) { is KtFile -> { val declarationContainer: KtElement = if (targetContainer.isScript()) targetContainer.script!!.blockExpression else targetContainer declarationContainer.add(originalElement) as KtNamedDeclaration } is KtClassOrObject -> targetContainer.addDeclaration(originalElement) else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}") }.apply { val container = originalElement.containingClassOrObject if (container is KtObjectDeclaration && container.isCompanion() && container.declarations.singleOrNull() == originalElement ) { container.deleteSingle() } else { originalElement.deleteSingle() } } } } } sealed class MoveSource { abstract val elementsToMove: Collection<KtNamedDeclaration> class Elements(override val elementsToMove: Collection<KtNamedDeclaration>) : MoveSource() class File(val file: KtFile) : MoveSource() { override val elementsToMove: Collection<KtNamedDeclaration> get() = file.declarations.filterIsInstance<KtNamedDeclaration>() } } fun MoveSource(declaration: KtNamedDeclaration) = MoveSource.Elements(listOf(declaration)) fun MoveSource(declarations: Collection<KtNamedDeclaration>) = MoveSource.Elements(declarations) fun MoveSource(file: KtFile) = MoveSource.File(file) class MoveDeclarationsDescriptor @JvmOverloads constructor( val project: Project, val moveSource: MoveSource, val moveTarget: KotlinMoveTarget, val delegate: MoveDeclarationsDelegate, val searchInCommentsAndStrings: Boolean = true, val searchInNonCode: Boolean = true, val deleteSourceFiles: Boolean = false, val moveCallback: MoveCallback? = null, val openInEditor: Boolean = false, val allElementsToMove: List<PsiElement>? = null, val analyzeConflicts: Boolean = true, val searchReferences: Boolean = true ) class ConflictUsageInfo(element: PsiElement, val messages: Collection<String>) : UsageInfo(element) private object ElementHashingStrategy : HashingStrategy<PsiElement> { override fun equals(e1: PsiElement?, e2: PsiElement?): Boolean { if (e1 === e2) return true // Name should be enough to distinguish different light elements based on the same original declaration if (e1 is KtLightDeclaration<*, *> && e2 is KtLightDeclaration<*, *>) { return e1.kotlinOrigin == e2.kotlinOrigin && e1.name == e2.name } return e1 == e2 } override fun hashCode(e: PsiElement?): Int { return when (e) { null -> 0 is KtLightDeclaration<*, *> -> (e.kotlinOrigin?.hashCode() ?: 0) * 31 + (e.name?.hashCode() ?: 0) else -> e.hashCode() } } } class MoveKotlinDeclarationsProcessor( val descriptor: MoveDeclarationsDescriptor, val mover: Mover = Mover.Default, private val throwOnConflicts: Boolean = false ) : BaseRefactoringProcessor(descriptor.project) { companion object { const val REFACTORING_ID = "move.kotlin.declarations" } val project get() = descriptor.project private var nonCodeUsages: Array<NonCodeUsageInfo>? = null private val moveEntireFile = descriptor.moveSource is MoveSource.File private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e -> e.parent != descriptor.moveTarget.getTargetPsiIfExists(e) } private val kotlinToLightElementsBySourceFile = elementsToMove .groupBy { it.containingKtFile } .mapValues { it.value.keysToMap { declaration -> declaration.toLightElements().ifEmpty { listOf(declaration) } } } private val conflicts = MultiMap<PsiElement, String>() override fun getRefactoringId() = REFACTORING_ID override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor { val targetContainerFqName = descriptor.moveTarget.targetContainerFqName?.let { if (it.isRoot) UsageViewBundle.message("default.package.presentable.name") else it.asString() } ?: UsageViewBundle.message("default.package.presentable.name") return MoveMultipleElementsViewDescriptor(elementsToMove.toTypedArray(), targetContainerFqName) } fun getConflictsAsUsages(): List<UsageInfo> = conflicts.entrySet().map { ConflictUsageInfo(it.key, it.value) } public override fun findUsages(): Array<UsageInfo> { if (!descriptor.searchReferences || elementsToMove.isEmpty()) return UsageInfo.EMPTY_ARRAY val newContainerName = descriptor.moveTarget.targetContainerFqName?.asString() ?: "" fun getSearchScope(element: PsiElement): GlobalSearchScope? { val projectScope = project.projectScope() val ktDeclaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return projectScope if (ktDeclaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) return projectScope val moveTarget = descriptor.moveTarget val (oldContainer, newContainer) = descriptor.delegate.getContainerChangeInfo(ktDeclaration, moveTarget) val targetModule = moveTarget.getTargetModule(project) ?: return projectScope if (oldContainer != newContainer || ktDeclaration.module != targetModule) return projectScope // Check if facade class may change if (newContainer is ContainerInfo.Package) { val javaScope = projectScope.restrictByFileType(JavaFileType.INSTANCE) val currentFile = ktDeclaration.containingKtFile val newFile = when (moveTarget) { is KotlinMoveTargetForExistingElement -> moveTarget.targetElement as? KtFile ?: return null is KotlinMoveTargetForDeferredFile -> return javaScope else -> return null } val currentFacade = currentFile.findFacadeClass() val newFacade = newFile.findFacadeClass() return if (currentFacade?.qualifiedName != newFacade?.qualifiedName) javaScope else null } return null } fun UsageInfo.intersectsWith(usage: UsageInfo): Boolean { if (element?.containingFile != usage.element?.containingFile) return false val firstSegment = segment ?: return false val secondSegment = usage.segment ?: return false return max(firstSegment.startOffset, secondSegment.startOffset) <= min(firstSegment.endOffset, secondSegment.endOffset) } fun collectUsages(kotlinToLightElements: Map<KtNamedDeclaration, List<PsiNamedElement>>, result: MutableCollection<UsageInfo>) { kotlinToLightElements.values.flatten().flatMapTo(result) { lightElement -> val searchScope = getSearchScope(lightElement) ?: return@flatMapTo emptyList() val elementName = lightElement.name ?: return@flatMapTo emptyList() val newFqName = StringUtil.getQualifiedName(newContainerName, elementName) val foundReferences = HashSet<PsiReference>() val results = ReferencesSearch .search(lightElement, searchScope) .mapNotNullTo(ArrayList()) { ref -> if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element) }) { createMoveUsageInfoIfPossible(ref, lightElement, addImportToOriginalFile = true, isInternal = false) } else null } val name = lightElement.getKotlinFqName()?.quoteIfNeeded()?.asString() if (name != null) { fun searchForKotlinNameUsages(results: ArrayList<UsageInfo>) { TextOccurrencesUtil.findNonCodeUsages( lightElement, searchScope, name, descriptor.searchInCommentsAndStrings, descriptor.searchInNonCode, FqName(newFqName).quoteIfNeeded().asString(), results ) } val facadeContainer = lightElement.parent as? KtLightClassForFacade if (facadeContainer != null) { val oldFqNameWithFacade = StringUtil.getQualifiedName(facadeContainer.qualifiedName, elementName) val newFqNameWithFacade = StringUtil.getQualifiedName( StringUtil.getQualifiedName(newContainerName, facadeContainer.name), elementName ) TextOccurrencesUtil.findNonCodeUsages( lightElement, searchScope, oldFqNameWithFacade, descriptor.searchInCommentsAndStrings, descriptor.searchInNonCode, FqName(newFqNameWithFacade).quoteIfNeeded().asString(), results ) ArrayList<UsageInfo>().also { searchForKotlinNameUsages(it) }.forEach { kotlinNonCodeUsage -> if (results.none { it.intersectsWith(kotlinNonCodeUsage) }) { results.add(kotlinNonCodeUsage) } } } else { searchForKotlinNameUsages(results) } } MoveClassHandler.EP_NAME.extensions.filter { it !is MoveKotlinClassHandler }.forEach { handler -> handler.preprocessUsages(results) } results } } val usages = ArrayList<UsageInfo>() val conflictChecker = MoveConflictChecker( project, elementsToMove, descriptor.moveTarget, elementsToMove.first(), allElementsToMove = descriptor.allElementsToMove ) for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) { val internalUsages = LinkedHashSet<UsageInfo>() val externalUsages = LinkedHashSet<UsageInfo>() if (moveEntireFile) { val changeInfo = ContainerChangeInfo( ContainerInfo.Package(sourceFile.packageFqName), descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage ) internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo) } else { kotlinToLightElements.keys.forEach { val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget) internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo) } } internalUsages += descriptor.delegate.findInternalUsages(descriptor) collectUsages(kotlinToLightElements, externalUsages) if (descriptor.analyzeConflicts) { conflictChecker.checkAllConflicts(externalUsages, internalUsages, conflicts) descriptor.delegate.collectConflicts(descriptor, internalUsages, conflicts) } usages += internalUsages usages += externalUsages } return UsageViewUtil.removeDuplicatedUsages(usages.toTypedArray()) } override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean { return showConflicts(conflicts, refUsages.get()) } override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean { if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException() return super.showConflicts(conflicts, usages) } override fun performRefactoring(usages: Array<out UsageInfo>) = doPerformRefactoring(usages.toList()) internal fun doPerformRefactoring(usages: List<UsageInfo>) { fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration { val targetContainer = moveTarget.getOrCreateTargetPsi(declaration) descriptor.delegate.preprocessDeclaration(descriptor, declaration) if (moveEntireFile) return declaration return mover(declaration, targetContainer).apply { addToBeShortenedDescendantsToWaitingSet() } } val (oldInternalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal } val newInternalUsages = ArrayList<UsageInfo>() markInternalUsages(oldInternalUsages) val usagesToProcess = ArrayList(externalUsages) try { descriptor.delegate.preprocessUsages(descriptor, usages) val oldToNewElementsMapping = CollectionFactory.createCustomHashingStrategyMap<PsiElement, PsiElement>(ElementHashingStrategy) val newDeclarations = ArrayList<KtNamedDeclaration>() for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) { for ((oldDeclaration, oldLightElements) in kotlinToLightElements) { val elementListener = transaction?.getElementListener(oldDeclaration) val newDeclaration = moveDeclaration(oldDeclaration, descriptor.moveTarget) newDeclarations += newDeclaration oldToNewElementsMapping[oldDeclaration] = newDeclaration oldToNewElementsMapping[sourceFile] = newDeclaration.containingKtFile elementListener?.elementMoved(newDeclaration) for ((oldElement, newElement) in oldLightElements.asSequence().zip(newDeclaration.toLightElements().asSequence())) { oldToNewElementsMapping[oldElement] = newElement } if (descriptor.openInEditor) { EditorHelper.openInEditor(newDeclaration) } } if (descriptor.deleteSourceFiles && sourceFile.declarations.isEmpty()) { sourceFile.delete() } } val internalUsageScopes: List<KtElement> = if (moveEntireFile) { newDeclarations.asSequence().map { it.containingKtFile }.distinct().toList() } else { newDeclarations } internalUsageScopes.forEach { newInternalUsages += restoreInternalUsages(it, oldToNewElementsMapping) } usagesToProcess += newInternalUsages nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray() performDelayedRefactoringRequests(project) } catch (e: IncorrectOperationException) { nonCodeUsages = null RefactoringUIUtil.processIncorrectOperation(myProject, e) } finally { cleanUpInternalUsages(newInternalUsages + oldInternalUsages) } } override fun performPsiSpoilingRefactoring() { nonCodeUsages?.let { nonCodeUsages -> RenameUtil.renameNonCodeUsages(myProject, nonCodeUsages) } descriptor.moveCallback?.refactoringCompleted() } fun execute(usages: List<UsageInfo>) { execute(usages.toTypedArray()) } override fun doRun() { try { super.doRun() } finally { broadcastRefactoringExit(myProject, refactoringId) } } override fun getCommandName(): String = KotlinBundle.message("text.move.declarations") }
apache-2.0
4e927ed92981f5838b590a7b0f7d8f0d
46.928395
158
0.670908
5.85904
false
false
false
false
HenningLanghorst/fancy-kotlin-stuff
src/main/kotlin/de/henninglanghorst/kotlinstuff/http/HttpClientExample.kt
1
724
package de.henninglanghorst.kotlinstuff.http import org.slf4j.Logger import org.slf4j.LoggerFactory val log: Logger = LoggerFactory.getLogger(Exception().stackTrace[0].className) fun main(args: Array<String>) { val post = httpRequest("https://postman-echo.com/post?hhhhh=5") { requestMethod = "POST" headers["Authorization"] = "Basic d2lraTpwZWRpYQ==" headers["Content-Type"] = "application/json; charset=utf-8" body = json(6, "Miller") } log.info("POST result {}", post) val get = httpRequest("https://postman-echo.com/status/400") { requestMethod = "GET" headers["Authorization"] = "Basic d2lraTpwZWRpYQ==" } log.info("GET result {}", get) }
apache-2.0
2f4bd2287b49654677c39ca7cd6aa104
26.846154
78
0.654696
3.399061
false
false
false
false
kivensolo/UiUsingListView
module-Home/src/main/java/com/zeke/home/adapter/ExamplePagerAdapter.kt
1
1559
package com.zeke.home.adapter import android.graphics.Color import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.TextView /** * author:KingZ * date:2020/2/16 * description:MagicIndicator Demo的Pager适配器 */ class ExamplePagerAdapter(private var dataList: List<String>?) : androidx.viewpager.widget.PagerAdapter() { override fun getCount(): Int { return if(dataList == null){ 0 }else{ dataList!!.size } } override fun isViewFromObject(view: View, obj: Any): Boolean { return view === obj } /** * 实例化Item */ override fun instantiateItem(container: ViewGroup, position: Int): Any { val textView = TextView(container.context) textView.text = dataList!![position] textView.gravity = Gravity.CENTER textView.setTextColor(Color.parseColor("#F79817")) textView.textSize = 26f container.addView(textView) return textView } override fun destroyItem(container: ViewGroup, position: Int, obj: Any) { container.removeView(obj as View) } override fun getItemPosition(obj: Any): Int { val textView = obj as TextView val text = textView.text.toString() val index = dataList!!.indexOf(text) return if (index >= 0) { index } else androidx.viewpager.widget.PagerAdapter.POSITION_NONE } override fun getPageTitle(position: Int): CharSequence? { return dataList!![position] } }
gpl-2.0
152eaad0f0b6bdd3968f2f4c55ecce19
27.518519
107
0.653671
4.422414
false
false
false
false
jwren/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/rest/PackageSearchRestService.kt
1
5463
package com.jetbrains.packagesearch.intellij.plugin.rest import com.google.gson.GsonBuilder import com.intellij.ide.impl.ProjectUtil import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.util.io.origin import com.intellij.util.net.NetUtils import com.intellij.util.text.nullize import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpMethod import io.netty.handler.codec.http.HttpRequest import io.netty.handler.codec.http.HttpResponseStatus import io.netty.handler.codec.http.HttpUtil import io.netty.handler.codec.http.QueryStringDecoder import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.ide.RestService import java.net.URI import java.net.URISyntaxException internal class PackageSearchRestService : RestService() { override fun getServiceName() = "packageSearch" override fun isMethodSupported(method: HttpMethod) = method === HttpMethod.GET || method === HttpMethod.POST override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? { when (getStringParameter("action", urlDecoder)) { "projects" -> listProjects(request, context) "install" -> installPackage(request, context) else -> sendStatus(HttpResponseStatus.NOT_FOUND, HttpUtil.isKeepAlive(request), context.channel()) } return null } private fun listProjects(request: FullHttpRequest, context: ChannelHandlerContext) { val out = BufferExposingByteArrayOutputStream() val name = ApplicationNamesInfo.getInstance().productName val build = ApplicationInfo.getInstance().build createJsonWriter(out).apply { beginObject() name("name").value(name) name("buildNumber").value(build.asString()) name("projects") beginArray() ProjectManager.getInstance().openProjects.forEach { value(it.name) } endArray() endObject() close() } send(out, request, context) } private fun installPackage( request: FullHttpRequest, context: ChannelHandlerContext ) { val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create() val data = gson.fromJson<InstallPackageRequest>(createJsonReader(request), InstallPackageRequest::class.java) val project = ProjectManager.getInstance().openProjects.find { it.name.equals(data.project, ignoreCase = true) } val pkg = data.`package` val query = data.query.nullize(true) if (project == null || pkg == null) { sendStatus(HttpResponseStatus.BAD_REQUEST, HttpUtil.isKeepAlive(request), context.channel()) return } AppUIExecutor.onUiThread().execute { ProjectUtil.focusProjectWindow(project, true) PackageSearchToolWindowFactory.activateToolWindow(project) { // project.packageSearchDataService.programmaticSearchQueryStateFlow.tryEmit(query ?: pkg.replace(':', ' ')) // rootModel.setSelectedPackage(pkg) // TODO preselect proper package notify(project, pkg) } } sendOk(request, context) } override fun isAccessible(request: HttpRequest) = true override fun isHostTrusted(request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean { val origin = request.origin val originHost = try { if (origin == null) null else URI(origin).host.nullize() } catch (ignored: URISyntaxException) { return false } val isTrusted = originHost?.let { it == "package-search.jetbrains.com" || it.endsWith("package-search.services.jetbrains.com") || NetUtils.isLocalhost(it) } ?: false return isTrusted || super.isHostTrusted(request, urlDecoder) } @Suppress("DialogTitleCapitalization") // It's the Package Search plugin name... private fun notify(project: Project, @Nls pkg: String) { NotificationGroupManager.getInstance() .getNotificationGroup(PluginEnvironment.PACKAGE_SEARCH_NOTIFICATION_GROUP_ID) .createNotification( PackageSearchBundle.message("packagesearch.title"), PackageSearchBundle.message("packagesearch.restService.readyForInstallation"), NotificationType.INFORMATION ) .setSubtitle(pkg) .notify(project) } } internal class InstallPackageRequest { var project: String? = null @NlsSafe var `package`: String? = null @NonNls var query: String? = null }
apache-2.0
8a8b98e3739a1bf0384bfcb2a6ef2583
39.466667
125
0.704924
5.025759
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUntilWithRangeToIntention.kt
1
1642
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.util.getRangeBinaryExpressionType import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe internal fun KtExpression.getArguments() = when (this) { is KtBinaryExpression -> this.left to this.right is KtDotQualifiedExpression -> this.receiverExpression to this.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression() else -> null } class ReplaceUntilWithRangeToIntention : SelfTargetingIntention<KtExpression>( KtExpression::class.java, KotlinBundle.lazyMessage("replace.with.0.operator", "..") ) { override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean { if (element !is KtBinaryExpression && element !is KtDotQualifiedExpression) return false val fqName = element.getCallableDescriptor()?.fqNameUnsafe?.asString() ?: return false return fqName == "kotlin.ranges.until" } override fun applyTo(element: KtExpression, editor: Editor?) { val args = element.getArguments() ?: return val psiFactory = KtPsiFactory(element.project) element.replace(psiFactory.createExpressionByPattern("$0..$1 - 1", args.first ?: return, args.second ?: return)) } }
apache-2.0
7a19953d62e9704ff23e96446a5f9d4a
48.787879
158
0.763703
4.787172
false
false
false
false
yschimke/okhttp
mockwebserver-junit5/src/main/kotlin/mockwebserver3/junit5/internal/MockWebServerExtension.kt
4
3430
/* * Copyright (C) 2020 Square, 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 mockwebserver3.junit5.internal import java.io.IOException import java.util.logging.Level import java.util.logging.Logger import mockwebserver3.MockWebServer import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement import org.junit.jupiter.api.extension.AfterAllCallback import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.BeforeAllCallback import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.extension.ParameterContext import org.junit.jupiter.api.extension.ParameterResolver /** Runs MockWebServer for the duration of a single test method. */ class MockWebServerExtension : BeforeAllCallback, BeforeEachCallback, AfterAllCallback, AfterEachCallback, ParameterResolver { private val ExtensionContext.resource: Resource get() { val store = getStore(namespace) var result = store.get(uniqueId) as Resource? if (result == null) { result = Resource() store.put(uniqueId, result) } return result } private class Resource { private val servers = mutableListOf<MockWebServer>() private var started = false fun newServer(): MockWebServer { return MockWebServer() .also { result -> if (started) result.start() servers += result } } fun startAll() { started = true for (server in servers) { server.start() } } fun shutdownAll() { try { for (server in servers) { server.shutdown() } } catch (e: IOException) { logger.log(Level.WARNING, "MockWebServer shutdown failed", e) } } } @IgnoreJRERequirement override fun supportsParameter( parameterContext: ParameterContext, extensionContext: ExtensionContext ): Boolean = parameterContext.parameter.type === MockWebServer::class.java override fun resolveParameter( parameterContext: ParameterContext, extensionContext: ExtensionContext ): Any = extensionContext.resource.newServer() /** Start the servers passed in as test class constructor parameters. */ override fun beforeAll(context: ExtensionContext) { context.resource.startAll() } /** Start the servers passed in as test method parameters. */ override fun beforeEach(context: ExtensionContext) { context.resource.startAll() } override fun afterEach(context: ExtensionContext) { context.resource.shutdownAll() } override fun afterAll(context: ExtensionContext) { context.resource.shutdownAll() } companion object { private val logger = Logger.getLogger(MockWebServerExtension::class.java.name) private val namespace = ExtensionContext.Namespace.create(MockWebServerExtension::class.java) } }
apache-2.0
927008e70459ca4120068afbd9e81e0c
30.759259
99
0.722741
4.61642
false
false
false
false
ebean-orm/avaje-ebeanorm-examples
e-kotlin-maven/src/main/java/org/example/domain/Country.kt
1
796
package org.example.domain; import com.avaje.ebean.Model import com.avaje.ebean.annotation.CacheStrategy import com.avaje.ebean.annotation.CacheTuning import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Size; /** * Country entity bean. * <p> * Uses constructor with properties having default values. */ @CacheStrategy(readOnly = true) @CacheTuning(maxSize = 500) @Entity @Table(name = "o_country") public class Country( @Id @Size(max = 2) public var code: String, @Size(max = 60) public var name: String ) : Model() { override fun toString(): String { return "code:$code name:$name"; } /** * Find helper singleton. */ companion object : Model.Find<String, Country>() {} }
apache-2.0
d90a588dc50c9ac485f196e8f490b732
19.410256
58
0.70603
3.585586
false
false
false
false
androidx/androidx
biometric/biometric-ktx/src/main/java/androidx/biometric/auth/Class3BiometricOrCredentialAuthExtensions.kt
3
9459
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.biometric.auth import android.os.Build import androidx.annotation.RequiresApi import androidx.biometric.BiometricPrompt.AuthenticationResult import androidx.biometric.BiometricPrompt.CryptoObject import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import kotlinx.coroutines.suspendCancellableCoroutine import java.util.concurrent.Executor /** * Shows an authentication prompt to the user. * * @param host A wrapper for the component that will host the prompt. * @param crypto A cryptographic object to be associated with this authentication. * * @return [AuthenticationResult] for a successful authentication. * * @throws AuthPromptErrorException when an unrecoverable error has been encountered and * authentication has stopped. * @throws AuthPromptFailureException when an authentication attempt by the user has been rejected. * * @see Class3BiometricOrCredentialAuthPrompt.authenticate( * AuthPromptHost, * AuthPromptCallback * ) * * @sample androidx.biometric.samples.auth.class3BiometricOrCredentialAuth */ @RequiresApi(Build.VERSION_CODES.R) public suspend fun Class3BiometricOrCredentialAuthPrompt.authenticate( host: AuthPromptHost, crypto: CryptoObject?, ): AuthenticationResult { return suspendCancellableCoroutine { continuation -> val authPrompt = startAuthentication( host, crypto, Runnable::run, CoroutineAuthPromptCallback(continuation) ) continuation.invokeOnCancellation { authPrompt.cancelAuthentication() } } } /** * Prompts the user to authenticate with a **Class 3** biometric (e.g. fingerprint, face, or iris) * or the screen lock credential (i.e. PIN, pattern, or password) for the device. * * @param crypto A cryptographic object to be associated with this authentication. * @param title The title to be displayed on the prompt. * @param subtitle An optional subtitle to be displayed on the prompt. * @param description An optional description to be displayed on the prompt. * @param confirmationRequired Whether user confirmation should be required for passive biometrics. * @param executor An executor for [callback] methods. If `null`, these will run on the main thread. * @param callback The object that will receive and process authentication events. * @return An [AuthPrompt] handle to the shown prompt. * * @see Class3BiometricOrCredentialAuthPrompt */ @RequiresApi(Build.VERSION_CODES.R) public fun FragmentActivity.startClass3BiometricOrCredentialAuthentication( crypto: CryptoObject?, title: CharSequence, subtitle: CharSequence? = null, description: CharSequence? = null, confirmationRequired: Boolean = true, executor: Executor? = null, callback: AuthPromptCallback ): AuthPrompt { return startClass3BiometricOrCredentialAuthenticationInternal( AuthPromptHost(this), crypto, title, subtitle, description, confirmationRequired, executor, callback ) } /** * Prompts the user to authenticate with a **Class 3** biometric (e.g. fingerprint, face, or iris) * or the screen lock credential (i.e. PIN, pattern, or password) for the device. * * @param crypto A cryptographic object to be associated with this authentication. * @param title The title to be displayed on the prompt. * @param subtitle An optional subtitle to be displayed on the prompt. * @param description An optional description to be displayed on the prompt. * @param confirmationRequired Whether user confirmation should be required for passive biometrics. * * @return [AuthenticationResult] for a successful authentication. * * @throws AuthPromptErrorException when an unrecoverable error has been encountered and * authentication has stopped. * @throws AuthPromptFailureException when an authentication attempt by the user has been rejected. * * @see Class3BiometricOrCredentialAuthPrompt */ @RequiresApi(Build.VERSION_CODES.R) public suspend fun FragmentActivity.authenticateWithClass3BiometricsOrCredentials( crypto: CryptoObject?, title: CharSequence, subtitle: CharSequence? = null, description: CharSequence? = null, confirmationRequired: Boolean = true, ): AuthenticationResult { val authPrompt = buildClass3BiometricOrCredentialAuthPrompt( title, subtitle, description, confirmationRequired ) return authPrompt.authenticate(AuthPromptHost(this), crypto) } /** * Prompts the user to authenticate with a **Class 3** biometric (e.g. fingerprint, face, or iris) * or the screen lock credential (i.e. PIN, pattern, or password) for the device. * * @param crypto A cryptographic object to be associated with this authentication. * @param title The title to be displayed on the prompt. * @param subtitle An optional subtitle to be displayed on the prompt. * @param description An optional description to be displayed on the prompt. * @param confirmationRequired Whether user confirmation should be required for passive biometrics. * @param executor An executor for [callback] methods. If `null`, these will run on the main thread. * @param callback The object that will receive and process authentication events. * @return An [AuthPrompt] handle to the shown prompt. * * @see Class3BiometricOrCredentialAuthPrompt */ @RequiresApi(Build.VERSION_CODES.R) public fun Fragment.startClass3BiometricOrCredentialAuthentication( crypto: CryptoObject?, title: CharSequence, subtitle: CharSequence? = null, description: CharSequence? = null, confirmationRequired: Boolean = true, executor: Executor? = null, callback: AuthPromptCallback ): AuthPrompt { return startClass3BiometricOrCredentialAuthenticationInternal( AuthPromptHost(this), crypto, title, subtitle, description, confirmationRequired, executor, callback ) } /** * Prompts the user to authenticate with a **Class 3** biometric (e.g. fingerprint, face, or iris) * or the screen lock credential (i.e. PIN, pattern, or password) for the device. * * @param crypto A cryptographic object to be associated with this authentication. * @param title The title to be displayed on the prompt. * @param subtitle An optional subtitle to be displayed on the prompt. * @param description An optional description to be displayed on the prompt. * @param confirmationRequired Whether user confirmation should be required for passive biometrics. * * @return [AuthenticationResult] for a successful authentication. * * @throws AuthPromptErrorException when an unrecoverable error has been encountered and * authentication has stopped. * @throws AuthPromptFailureException when an authentication attempt by the user has been rejected. * * @see Class3BiometricOrCredentialAuthPrompt */ @RequiresApi(Build.VERSION_CODES.R) public suspend fun Fragment.authenticateWithClass3BiometricsOrCredentials( crypto: CryptoObject?, title: CharSequence, subtitle: CharSequence? = null, description: CharSequence? = null, confirmationRequired: Boolean = true, ): AuthenticationResult { val authPrompt = buildClass3BiometricOrCredentialAuthPrompt( title, subtitle, description, confirmationRequired, ) return authPrompt.authenticate(AuthPromptHost(this), crypto) } /** * Creates a [Class3BiometricOrCredentialAuthPrompt] with the given parameters and starts * authentication. */ @RequiresApi(Build.VERSION_CODES.R) private fun startClass3BiometricOrCredentialAuthenticationInternal( host: AuthPromptHost, crypto: CryptoObject?, title: CharSequence, subtitle: CharSequence?, description: CharSequence?, confirmationRequired: Boolean, executor: Executor?, callback: AuthPromptCallback ): AuthPrompt { val prompt = buildClass3BiometricOrCredentialAuthPrompt( title, subtitle, description, confirmationRequired ) return if (executor == null) { prompt.startAuthentication(host, crypto, callback) } else { prompt.startAuthentication(host, crypto, executor, callback) } } /** * Creates a [Class3BiometricOrCredentialAuthPrompt] with the given parameters. */ @RequiresApi(Build.VERSION_CODES.R) private fun buildClass3BiometricOrCredentialAuthPrompt( title: CharSequence, subtitle: CharSequence?, description: CharSequence?, confirmationRequired: Boolean, ): Class3BiometricOrCredentialAuthPrompt = Class3BiometricOrCredentialAuthPrompt.Builder(title) .apply { subtitle?.let { setSubtitle(it) } description?.let { setDescription(it) } setConfirmationRequired(confirmationRequired) } .build()
apache-2.0
da57c15d7a34f8c641d522f36c17bc97
36.094118
100
0.74511
4.611897
false
false
false
false
androidx/androidx
testutils/testutils-common/src/main/java/androidx/testutils/ParameterizedHelper.kt
3
2321
/* * 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.testutils /** * Generate all argument enumerations for Parameterized tests. For example, * `generateAllEnumerations(listOf(false, true), listOf(1, 2, 3))` would return: * * ``` * [ * [false, 1], * [false, 2], * [false, 3], * [true, 1], * [true, 2], * [true, 3] * ] * ``` * * See [ParameterizedHelperTest] for more examples. */ fun generateAllEnumerations(vararg args: List<Any>): List<Array<Any>> = generateAllEnumerationsIteratively(args.toList()).map { it.toTypedArray() } internal fun generateAllEnumerationsIteratively(elements: List<List<Any>>): List<List<Any>> { if (elements.isEmpty()) return emptyList() var number = elements.map { RadixDigit(it.size, 0) } val total = elements.map { it.size }.product() val result = mutableListOf<List<Any>>() for (i in 0 until total) { result.add(elements.mapIndexed { index, element -> element[number[index].digit] }) number = increment(number) } return result } internal fun increment(number: List<RadixDigit>): List<RadixDigit> { var index = number.size - 1 var carry = 1 val result = mutableListOf<RadixDigit>() while (index >= 0) { val rd = number[index] if (carry > 0) { if (rd.digit < rd.radix - 1) { result.add(rd.copy(digit = rd.digit + 1)) carry = 0 } else { result.add(rd.copy(digit = 0)) } } else { result.add(rd) } index-- } return result.reversed() } internal fun List<Int>.product() = this.fold(1) { acc, elem -> acc * elem } internal data class RadixDigit(val radix: Int, val digit: Int)
apache-2.0
5e32d51fec593a420becc6daf7e5c06a
30.378378
93
0.632917
3.689984
false
false
false
false
ligi/SurvivalManual
android/src/main/kotlin/org/ligi/survivalmanual/ui/ProductLinkProcessor.kt
1
2942
package org.ligi.survivalmanual.ui import android.app.Activity import android.content.DialogInterface import android.content.Intent import androidx.appcompat.app.AlertDialog import org.ligi.kaxt.inflate import org.ligi.kaxt.startActivityFromURL import org.ligi.survivalmanual.R val PRODUCT_MAP = mapOf( "SolarUSBCharger" to "B01EXWCPLC/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B01EXWCPLC&linkCode=as2&tag=ligi-20&linkId=91a10115f5e5cfae9b2529ca1a96c074", "CampStoveUSB" to "B00BQHET9O/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B00BQHET9O&linkCode=as2&tag=ligi-20&linkId=d949a1aca04d67b5e61d3bf77ce89d22", "HandCrankUSB" to "B08D9KLNV3/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B08D9KLNV3&linkCode=as2&tag=ligi-20&linkId=2f8f83d3bb8ec615be3f8849abf751c2", "CarUSBCharger" to "B00VH84L5E/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B00VH84L5E&linkCode=as2&tag=ligi-20&linkId=41a56b9c800ed019a0af367a49050502", "OHTMultiTool" to "B008069YXA/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B008069YXA&linkCode=as2&tag=ligi-20&linkId=a286d415f362e4650652f63a4dae9a3e", "LifeStraw" to "B006QF3TW4/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B006QF3TW4&linkCode=as2&tag=ligi-20&linkId=140954cab61f21b92f27217172f3ec35", "TreadMultiTool" to "B018IOXXP8/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B018IOXXP8&linkCode=as2&tag=ligi-20&linkId=1c14c69653606e308b9f4b98372a5a51", "PandaDubLionsDen" to "B00F48QJUS/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B00F48QJUS&linkCode=as2&tag=ligi-20&linkId=3e9b42f0dee5e03da96ea1f14be223ea", "Audible" to "B00NB86OYE/?ref_=assoc_tag_ph_1485906643682&_encoding=UTF8&camp=1789&creative=9325&linkCode=pf4&tag=ligi-20&linkId=38dacab0a96e0ecaa625fa375f70c517" ) fun processProductLinks(it: String, activity: Activity): Boolean { if (PRODUCT_MAP.containsKey(it)) { val url = "https://www.amazon.com/gp/product/" + PRODUCT_MAP[it] val view = activity.inflate(R.layout.alert_product_link) AlertDialog.Builder(activity) .setTitle(R.string.amazon_link_title) .setView(view) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.to_amazon) { _: DialogInterface, _: Int -> activity.startActivityFromURL(url) } .setNeutralButton(R.string.send_link) { _: DialogInterface, _: Int -> val sendIntent = Intent(Intent.ACTION_SEND).apply { putExtra(Intent.EXTRA_TEXT, url) type = "text/plain" } activity.startActivity(Intent.createChooser(sendIntent, "Send link to")) } .show() return true } else { return false } }
gpl-3.0
1e3ff5fe1a56086f45c77b97dc431070
60.3125
177
0.706662
2.754682
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/PrivacyNoticeComponent.kt
8
4079
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.diagnostic import com.intellij.icons.AllIcons import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.SystemInfo import com.intellij.ui.BrowserHyperlinkListener import com.intellij.ui.ColorUtil import com.intellij.util.ui.HTMLEditorKitBuilder import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.JComponent import javax.swing.JEditorPane import javax.swing.JLabel import javax.swing.JPanel class PrivacyNoticeComponent(@NlsContexts.Label private val label: String, @NlsContexts.Label private val expandedLabel: String) : JPanel( GridBagLayout()) { private val iconLabel: JLabel = JLabel() private val titleLabel = JLabel() private val privacyPolicyPane: JEditorPane = JEditorPane() var expanded: Boolean = true set(expanded) { field = expanded if (expanded) { titleLabel.text = expandedLabel iconLabel.icon = AllIcons.General.ArrowDown privacyPolicyPane.isVisible = true } else { titleLabel.text = label iconLabel.icon = AllIcons.General.ArrowRight privacyPolicyPane.isVisible = false } } var privacyPolicy: String get() = privacyPolicyPane.text set(@Nls(capitalization = Nls.Capitalization.Sentence) text) { privacyPolicyPane.text = text } init { background = backgroundColor() val iconLabelPanel = JPanel(BorderLayout()) useInHeader(iconLabelPanel) iconLabelPanel.add(iconLabel, BorderLayout.WEST) val mySeparatorPanel = JPanel() useInHeader(mySeparatorPanel) mySeparatorPanel.preferredSize = Dimension(6, 1) useInHeader(titleLabel) titleLabel.foreground = titleColor() titleLabel.font = titleLabel.font.deriveFont((titleLabel.font.size - 1).toFloat()) privacyPolicyPane.isEditable = false privacyPolicyPane.isFocusable = false privacyPolicyPane.background = backgroundColor() privacyPolicyPane.foreground = noticeColor() privacyPolicyPane.font = privacyPolicyPane.font.deriveFont((privacyPolicyPane.font.size - if (SystemInfo.isWindows) 2 else 1).toFloat()) privacyPolicyPane.editorKit = HTMLEditorKitBuilder.simple() privacyPolicyPane.border = JBUI.Borders.empty(0, 0, 6, 6) privacyPolicyPane.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE) add(mySeparatorPanel, GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.VERTICAL, JBInsets.emptyInsets(), 0, 0)) add(iconLabelPanel, GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, JBInsets.emptyInsets(), 0, 0)) add(titleLabel, GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBInsets.emptyInsets(), 0, 0)) add(privacyPolicyPane, GridBagConstraints(2, 1, 1, 1, 0.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBInsets.emptyInsets(), 0, 0)) expanded = true } private fun useInHeader(component: JComponent) { component.border = JBUI.Borders.empty(6, 0) component.background = backgroundColor() component.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) component.addMouseListener(object : MouseAdapter() { override fun mouseReleased(e: MouseEvent?) { expanded = !expanded } }) } companion object { private fun titleColor() = UIUtil.getLabelForeground() private fun noticeColor() = UIUtil.getContextHelpForeground() private fun backgroundColor() = ColorUtil.hackBrightness(JBUI.CurrentTheme.CustomFrameDecorations.paneBackground(), 1, 1 / 1.05f) } }
apache-2.0
b5f14251d4315953a1f31a19b951f30f
38.230769
143
0.715126
4.661714
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinSmartEnterHandler.kt
4
5962
// 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.editor import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.tree.TokenSet import com.intellij.util.text.CharArrayUtil import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.editor.fixers.* import org.jetbrains.kotlin.idea.formatter.kotlinCommonSettings import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class KotlinSmartEnterHandler : SmartEnterProcessorWithFixers() { init { addFixers( KotlinIfConditionFixer(), KotlinMissingIfBranchFixer(), KotlinWhileConditionFixer(), KotlinForConditionFixer(), KotlinMissingForOrWhileBodyFixer(), KotlinWhenSubjectCaretFixer(), KotlinMissingWhenBodyFixer(), KotlinMissingWhenEntryBodyFixer(), KotlinDoWhileFixer(), KotlinFunctionParametersFixer(), KotlinFunctionDeclarationBodyFixer(), KotlinPropertySetterParametersFixer(), KotlinPropertyAccessorBodyFixer(), KotlinTryBodyFixer(), KotlinCatchParameterFixer(), KotlinCatchBodyFixer(), KotlinFinallyBodyFixer(), KotlinLastLambdaParameterFixer(), KotlinClassInitializerFixer(), KotlinClassBodyFixer(), KotlinValueArgumentListFixer() ) addEnterProcessors(KotlinPlainEnterProcessor()) } override fun getStatementAtCaret(editor: Editor?, psiFile: PsiFile?): PsiElement? { var atCaret = super.getStatementAtCaret(editor, psiFile) if (atCaret is PsiWhiteSpace) return null while (atCaret != null) { when { atCaret.isKotlinStatement() -> return atCaret atCaret.parent is KtFunctionLiteral -> return atCaret atCaret is KtDeclaration -> { val declaration = atCaret when { declaration is KtParameter && !declaration.isInLambdaExpression() -> {/* proceed to function declaration */ } declaration.parent is KtForExpression -> {/* skip variable declaration in 'for' expression */ } else -> return atCaret } } } atCaret = atCaret.parent } return null } override fun moveCaretInsideBracesIfAny(editor: Editor, file: PsiFile) { var caretOffset = editor.caretModel.offset val chars = editor.document.charsSequence if (CharArrayUtil.regionMatches(chars, caretOffset, "{}")) { caretOffset += 2 } else { if (CharArrayUtil.regionMatches(chars, caretOffset, "{\n}")) { caretOffset += 3 } } caretOffset = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t") + 1 if (CharArrayUtil.regionMatches(chars, caretOffset - "{}".length, "{}") || CharArrayUtil.regionMatches(chars, caretOffset - "{\n}".length, "{\n}") ) { commit(editor) val settings = file.kotlinCommonSettings val old = settings.KEEP_LINE_BREAKS settings.KEEP_LINE_BREAKS = true file.findElementAt(caretOffset - 1)?.getStrictParentOfType<KtBlockExpression>()?.let(::reformat) settings.KEEP_LINE_BREAKS = old editor.caretModel.moveToOffset(caretOffset - 1) } } private fun PsiElement.isKotlinStatement() = when { parent is KtBlockExpression && node?.elementType !in BRACES -> true parent?.node?.elementType in BRANCH_CONTAINERS && this !is KtBlockExpression -> true else -> false } class KotlinPlainEnterProcessor : SmartEnterProcessorWithFixers.FixEnterProcessor() { private fun getControlStatementBlock(caret: Int, element: PsiElement): KtExpression? { when (element) { is KtDeclarationWithBody -> return element.bodyExpression is KtIfExpression -> { if (element.then.isWithCaret(caret)) return element.then if (element.`else`.isWithCaret(caret)) return element.`else` } is KtLoopExpression -> return element.body } return null } override fun doEnter(atCaret: PsiElement, file: PsiFile?, editor: Editor, modified: Boolean): Boolean { if (modified && atCaret is KtCallExpression) return true val block = getControlStatementBlock(editor.caretModel.offset, atCaret) as? KtBlockExpression if (block != null) { val firstElement = block.firstChild?.nextSibling val offset = if (firstElement != null) { firstElement.textRange!!.startOffset - 1 } else { block.textRange!!.endOffset } editor.caretModel.moveToOffset(offset) } plainEnter(editor) return true } } override fun processDefaultEnter(project: Project, editor: Editor, file: PsiFile) { plainEnter(editor) } } private val BRANCH_CONTAINERS = TokenSet.create(KtNodeTypes.THEN, KtNodeTypes.ELSE, KtNodeTypes.BODY) private val BRACES = TokenSet.create(KtTokens.RBRACE, KtTokens.LBRACE) private fun KtParameter.isInLambdaExpression() = this.parent.parent is KtFunctionLiteral
apache-2.0
2fe9401e8529216ee970c7aa7c9c7486
35.802469
158
0.626635
5.619227
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractableAnalysisUtil.kt
1
40631
// 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.refactoring.introduce.extractionEngine import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode import org.jetbrains.kotlin.cfg.pseudocode.* import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionWithNext import org.jetbrains.kotlin.cfg.pseudocode.instructions.KtElementInstruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.* import org.jetbrains.kotlin.cfg.pseudocode.instructions.jumps.* import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.LocalFunctionDeclarationInstruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.special.MarkInstruction import org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraversalOrder import org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraverseInstructionResult import org.jetbrains.kotlin.cfg.pseudocodeTraverser.traverse import org.jetbrains.kotlin.cfg.pseudocodeTraverser.traverseFollowingInstructions import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator import org.jetbrains.kotlin.idea.base.util.names.FqNames import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.OLD_EXPERIMENTAL_FQ_NAME import org.jetbrains.kotlin.idea.core.OPT_IN_FQ_NAMES import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.refactoring.createTempCopy import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.AnalysisResult.ErrorMessage import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.AnalysisResult.Status import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.* import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.* import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.checkers.OptInNames import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly import org.jetbrains.kotlin.utils.DFS.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.* internal val KotlinBuiltIns.defaultReturnType: KotlinType get() = unitType internal val KotlinBuiltIns.defaultParameterType: KotlinType get() = nullableAnyType private fun DeclarationDescriptor.renderForMessage(): String { return IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(this) } private val TYPE_RENDERER = DescriptorRenderer.FQ_NAMES_IN_TYPES.withOptions { typeNormalizer = IdeDescriptorRenderers.APPROXIMATE_FLEXIBLE_TYPES } private fun KotlinType.renderForMessage(): String = TYPE_RENDERER.renderType(this) private fun KtDeclaration.renderForMessage(bindingContext: BindingContext): String? = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this]?.renderForMessage() private fun List<Instruction>.getModifiedVarDescriptors(bindingContext: BindingContext): Map<VariableDescriptor, List<KtExpression>> { val result = HashMap<VariableDescriptor, MutableList<KtExpression>>() for (instruction in filterIsInstance<WriteValueInstruction>()) { val expression = instruction.element as? KtExpression val descriptor = PseudocodeUtil.extractVariableDescriptorIfAny(instruction, bindingContext) if (expression != null && descriptor != null) { result.getOrPut(descriptor) { ArrayList() }.add(expression) } } return result } private fun List<Instruction>.getVarDescriptorsAccessedAfterwards(bindingContext: BindingContext): Set<VariableDescriptor> { val accessedAfterwards = HashSet<VariableDescriptor>() val visitedInstructions = HashSet<Instruction>() fun doTraversal(instruction: Instruction) { traverseFollowingInstructions(instruction, visitedInstructions) { when { it is AccessValueInstruction && it !in this -> PseudocodeUtil.extractVariableDescriptorIfAny( it, bindingContext )?.let { descriptor -> accessedAfterwards.add(descriptor) } it is LocalFunctionDeclarationInstruction -> doTraversal(it.body.enterInstruction) } TraverseInstructionResult.CONTINUE } } forEach(::doTraversal) return accessedAfterwards } private fun List<Instruction>.getExitPoints(): List<Instruction> = filter { localInstruction -> localInstruction.nextInstructions.any { it !in this } } private fun ExtractionData.getResultTypeAndExpressions( instructions: List<Instruction>, bindingContext: BindingContext, targetScope: LexicalScope?, options: ExtractionOptions, module: ModuleDescriptor ): Pair<KotlinType, List<KtExpression>> { fun instructionToExpression(instruction: Instruction, unwrapReturn: Boolean): KtExpression? { return when (instruction) { is ReturnValueInstruction -> (if (unwrapReturn) null else instruction.returnExpressionIfAny) ?: instruction.returnedValue.element as? KtExpression is InstructionWithValue -> instruction.outputValue?.element as? KtExpression else -> null } } fun instructionToType(instruction: Instruction): KotlinType? { val expression = instructionToExpression(instruction, true) ?: return null substringInfo?.let { if (it.template == expression) return it.type } if (options.inferUnitTypeForUnusedValues && expression.isUsedAsStatement(bindingContext)) return null return bindingContext.getType(expression) ?: (expression as? KtReferenceExpression)?.let { (bindingContext[BindingContext.REFERENCE_TARGET, it] as? CallableDescriptor)?.returnType } } val resultTypes = instructions.mapNotNull(::instructionToType) val commonSupertype = if (resultTypes.isNotEmpty()) CommonSupertypes.commonSupertype(resultTypes) else module.builtIns.defaultReturnType val resultType = commonSupertype.approximateWithResolvableType(targetScope, false) val expressions = instructions.mapNotNull { instructionToExpression(it, false) } return resultType to expressions } private fun getCommonNonTrivialSuccessorIfAny(instructions: List<Instruction>): Instruction? { val singleSuccessorCheckingVisitor = object : InstructionVisitorWithResult<Boolean>() { var target: Instruction? = null override fun visitInstructionWithNext(instruction: InstructionWithNext): Boolean { return when (instruction) { is LoadUnitValueInstruction, is MergeInstruction, is MarkInstruction -> { instruction.next?.accept(this) ?: true } else -> visitInstruction(instruction) } } override fun visitJump(instruction: AbstractJumpInstruction): Boolean { return when (instruction) { is ConditionalJumpInstruction -> visitInstruction(instruction) else -> instruction.resolvedTarget?.accept(this) ?: true } } override fun visitInstruction(instruction: Instruction): Boolean { if (target != null && target != instruction) return false target = instruction return true } } if (instructions.flatMap { it.nextInstructions }.any { !it.accept(singleSuccessorCheckingVisitor) }) return null return singleSuccessorCheckingVisitor.target ?: instructions.firstOrNull()?.owner?.sinkInstruction } private fun KotlinType.isMeaningful(): Boolean { return !KotlinBuiltIns.isUnit(this) && !KotlinBuiltIns.isNothing(this) } private fun ExtractionData.getLocalDeclarationsWithNonLocalUsages( pseudocode: Pseudocode, localInstructions: List<Instruction>, bindingContext: BindingContext ): List<KtNamedDeclaration> { val declarations = HashSet<KtNamedDeclaration>() pseudocode.traverse(TraversalOrder.FORWARD) { instruction -> if (instruction !in localInstructions) { instruction.getPrimaryDeclarationDescriptorIfAny(bindingContext)?.let { descriptor -> val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) if (declaration is KtNamedDeclaration && declaration.isInsideOf(physicalElements)) { declarations.add(declaration) } } } } return declarations.sortedBy { it.textRange!!.startOffset } } private fun ExtractionData.analyzeControlFlow( localInstructions: List<Instruction>, pseudocode: Pseudocode, module: ModuleDescriptor, bindingContext: BindingContext, modifiedVarDescriptors: Map<VariableDescriptor, List<KtExpression>>, options: ExtractionOptions, targetScope: LexicalScope?, parameters: Set<Parameter> ): Pair<ControlFlow, ErrorMessage?> { val exitPoints = localInstructions.getExitPoints() val valuedReturnExits = ArrayList<ReturnValueInstruction>() val defaultExits = ArrayList<Instruction>() val jumpExits = ArrayList<AbstractJumpInstruction>() exitPoints.forEach { val e = (it as? UnconditionalJumpInstruction)?.element when (val inst = when { it !is ReturnValueInstruction && it !is ReturnNoValueInstruction && it.owner != pseudocode -> null it is UnconditionalJumpInstruction && it.targetLabel.isJumpToError -> it e != null && e !is KtBreakExpression && e !is KtContinueExpression -> it.previousInstructions.firstOrNull() else -> it }) { is ReturnValueInstruction -> if (inst.owner == pseudocode) { if (inst.returnExpressionIfAny == null) { defaultExits.add(inst) } else { valuedReturnExits.add(inst) } } is AbstractJumpInstruction -> { val element = inst.element if ((element is KtReturnExpression && inst.owner == pseudocode) || element is KtBreakExpression || element is KtContinueExpression ) jumpExits.add(inst) else if (element !is KtThrowExpression && !inst.targetLabel.isJumpToError) defaultExits.add(inst) } else -> if (inst != null && inst !is LocalFunctionDeclarationInstruction) defaultExits.add(inst) } } val nonLocallyUsedDeclarations = getLocalDeclarationsWithNonLocalUsages(pseudocode, localInstructions, bindingContext) val (declarationsToCopy, declarationsToReport) = nonLocallyUsedDeclarations.partition { it is KtProperty && it.isLocal } val (typeOfDefaultFlow, defaultResultExpressions) = getResultTypeAndExpressions( defaultExits, bindingContext, targetScope, options, module ) val (returnValueType, valuedReturnExpressions) = getResultTypeAndExpressions( valuedReturnExits, bindingContext, targetScope, options, module ) val emptyControlFlow = ControlFlow(Collections.emptyList(), { OutputValueBoxer.AsTuple(it, module) }, declarationsToCopy) val defaultReturnType = if (returnValueType.isMeaningful()) returnValueType else typeOfDefaultFlow if (defaultReturnType.isError) return emptyControlFlow to ErrorMessage.ERROR_TYPES val controlFlow = if (defaultReturnType.isMeaningful()) { emptyControlFlow.copy(outputValues = Collections.singletonList(ExpressionValue(false, defaultResultExpressions, defaultReturnType))) } else emptyControlFlow if (declarationsToReport.isNotEmpty()) { val localVarStr = declarationsToReport.map { it.renderForMessage(bindingContext)!! }.distinct().sorted() return controlFlow to ErrorMessage.DECLARATIONS_ARE_USED_OUTSIDE.addAdditionalInfo(localVarStr) } val outParameters = parameters.filter { it.mirrorVarName != null && modifiedVarDescriptors[it.originalDescriptor] != null }.sortedBy { it.nameForRef } val outDeclarations = declarationsToCopy.filter { modifiedVarDescriptors[bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]] != null } val modifiedValueCount = outParameters.size + outDeclarations.size val outputValues = ArrayList<OutputValue>() val multipleExitsError = controlFlow to ErrorMessage.MULTIPLE_EXIT_POINTS val outputAndExitsError = controlFlow to ErrorMessage.OUTPUT_AND_EXIT_POINT if (typeOfDefaultFlow.isMeaningful()) { if (valuedReturnExits.isNotEmpty() || jumpExits.isNotEmpty()) return multipleExitsError outputValues.add(ExpressionValue(false, defaultResultExpressions, typeOfDefaultFlow)) } else if (valuedReturnExits.isNotEmpty()) { if (jumpExits.isNotEmpty()) return multipleExitsError if (defaultExits.isNotEmpty()) { if (modifiedValueCount != 0) return outputAndExitsError if (valuedReturnExits.size != 1) return multipleExitsError val element = valuedReturnExits.first().element as KtExpression return controlFlow.copy(outputValues = Collections.singletonList(Jump(listOf(element), element, true, module.builtIns))) to null } if (getCommonNonTrivialSuccessorIfAny(valuedReturnExits) == null) return multipleExitsError outputValues.add(ExpressionValue(true, valuedReturnExpressions, returnValueType)) } outDeclarations.mapTo(outputValues) { val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as? CallableDescriptor Initializer(it as KtProperty, descriptor?.returnType ?: module.builtIns.defaultParameterType) } outParameters.mapTo(outputValues) { ParameterUpdate(it, modifiedVarDescriptors[it.originalDescriptor]!!) } if (outputValues.isNotEmpty()) { if (jumpExits.isNotEmpty()) return outputAndExitsError val boxerFactory: (List<OutputValue>) -> OutputValueBoxer = when { outputValues.size > 3 -> { if (!options.enableListBoxing) { val outValuesStr = (outParameters.map { it.originalDescriptor.renderForMessage() } + outDeclarations.map { it.renderForMessage(bindingContext)!! }).sorted() return controlFlow to ErrorMessage.MULTIPLE_OUTPUT.addAdditionalInfo(outValuesStr) } { values -> OutputValueBoxer.AsList(values) } } else -> controlFlow.boxerFactory } return controlFlow.copy(outputValues = outputValues, boxerFactory = boxerFactory) to null } if (jumpExits.isNotEmpty()) { val jumpTarget = getCommonNonTrivialSuccessorIfAny(jumpExits) ?: return multipleExitsError val singleExit = getCommonNonTrivialSuccessorIfAny(defaultExits) == jumpTarget val conditional = !singleExit && defaultExits.isNotEmpty() val elements = jumpExits.map { it.element as KtExpression } val elementToInsertAfterCall = if (singleExit) null else elements.first() return controlFlow.copy( outputValues = Collections.singletonList( Jump( elements, elementToInsertAfterCall, conditional, module.builtIns ) ) ) to null } return controlFlow to null } fun ExtractionData.createTemporaryDeclaration(pattern: String): KtNamedDeclaration { val targetSiblingMarker = Any() PsiTreeUtil.mark(targetSibling, targetSiblingMarker) val tmpFile = originalFile.createTempCopy("") tmpFile.deleteChildRange(tmpFile.firstChild, tmpFile.lastChild) tmpFile.addRange(originalFile.firstChild, originalFile.lastChild) val newTargetSibling = PsiTreeUtil.releaseMark(tmpFile, targetSiblingMarker)!! val newTargetParent = newTargetSibling.parent val declaration = KtPsiFactory(originalFile).createDeclarationByPattern<KtNamedDeclaration>( pattern, PsiChildRange(originalElements.firstOrNull(), originalElements.lastOrNull()) ) return if (insertBefore) { newTargetParent.addBefore(declaration, newTargetSibling) as KtNamedDeclaration } else { newTargetParent.addAfter(declaration, newTargetSibling) as KtNamedDeclaration } } internal fun ExtractionData.createTemporaryCodeBlock(): KtBlockExpression { if (options.extractAsProperty) { return ((createTemporaryDeclaration("val = {\n$0\n}\n") as KtProperty).initializer as KtLambdaExpression).bodyExpression!! } return (createTemporaryDeclaration("fun() {\n$0\n}\n") as KtNamedFunction).bodyBlockExpression!! } private fun KotlinType.collectReferencedTypes(processTypeArguments: Boolean): List<KotlinType> { if (!processTypeArguments) return Collections.singletonList(this) return dfsFromNode( this, Neighbors<KotlinType> { current -> current.arguments.map { it.type } }, VisitedWithSet(), object : CollectingNodeHandler<KotlinType, KotlinType, ArrayList<KotlinType>>(ArrayList()) { override fun afterChildren(current: KotlinType) { result.add(current) } } )!! } fun KtTypeParameter.collectRelevantConstraints(): List<KtTypeConstraint> { val typeConstraints = getNonStrictParentOfType<KtTypeParameterListOwner>()?.typeConstraints ?: return Collections.emptyList() return typeConstraints.filter { it.subjectTypeParameterName?.mainReference?.resolve() == this } } fun TypeParameter.collectReferencedTypes(bindingContext: BindingContext): List<KotlinType> { val typeRefs = ArrayList<KtTypeReference>() originalDeclaration.extendsBound?.let { typeRefs.add(it) } originalConstraints.mapNotNullTo(typeRefs) { it.boundTypeReference } return typeRefs.mapNotNull { bindingContext[BindingContext.TYPE, it] } } private fun KotlinType.isExtractable(targetScope: LexicalScope?): Boolean { return collectReferencedTypes(true).fold(true) { extractable, typeToCheck -> val parameterTypeDescriptor = typeToCheck.constructor.declarationDescriptor as? TypeParameterDescriptor val typeParameter = parameterTypeDescriptor?.let { DescriptorToSourceUtils.descriptorToDeclaration(it) } as? KtTypeParameter extractable && (typeParameter != null || typeToCheck.isResolvableInScope(targetScope, false)) } } internal fun KotlinType.processTypeIfExtractable( typeParameters: MutableSet<TypeParameter>, nonDenotableTypes: MutableSet<KotlinType>, options: ExtractionOptions, targetScope: LexicalScope?, processTypeArguments: Boolean = true ): Boolean { return collectReferencedTypes(processTypeArguments).fold(true) { extractable, typeToCheck -> val parameterTypeDescriptor = typeToCheck.constructor.declarationDescriptor as? TypeParameterDescriptor val typeParameter = parameterTypeDescriptor?.let { DescriptorToSourceUtils.descriptorToDeclaration(it) } as? KtTypeParameter when { typeToCheck.isResolvableInScope(targetScope, true) -> extractable typeParameter != null -> { typeParameters.add(TypeParameter(typeParameter, typeParameter.collectRelevantConstraints())) extractable } typeToCheck.isError -> false else -> { nonDenotableTypes.add(typeToCheck) false } } } } internal class MutableParameter( override val argumentText: String, override val originalDescriptor: DeclarationDescriptor, override val receiverCandidate: Boolean, private val targetScope: LexicalScope?, private val originalType: KotlinType, private val possibleTypes: Set<KotlinType> ) : Parameter { // All modifications happen in the same thread private var writable: Boolean = true private val defaultTypes = LinkedHashSet<KotlinType>() private val typePredicates = HashSet<TypePredicate>() var refCount: Int = 0 fun addDefaultType(kotlinType: KotlinType) { assert(writable) { "Can't add type to non-writable parameter $currentName" } if (kotlinType in possibleTypes) { defaultTypes.add(kotlinType) } } fun addTypePredicate(predicate: TypePredicate) { assert(writable) { "Can't add type predicate to non-writable parameter $currentName" } typePredicates.add(predicate) } var currentName: String? = null override val name: String get() = currentName!! override var mirrorVarName: String? = null private val defaultType: KotlinType by lazy { writable = false if (defaultTypes.isNotEmpty()) { TypeIntersector.intersectTypes(defaultTypes)!! } else originalType } private val allParameterTypeCandidates: List<KotlinType> by lazy { writable = false val typePredicate = and(typePredicates) val typeSet = if (defaultType.isFlexible()) { val bounds = defaultType.asFlexibleType() LinkedHashSet<KotlinType>().apply { if (typePredicate(bounds.upperBound)) add(bounds.upperBound) if (typePredicate(bounds.lowerBound)) add(bounds.lowerBound) } } else linkedSetOf(defaultType) val addNullableTypes = defaultType.isNullabilityFlexible() && typeSet.size > 1 val superTypes = TypeUtils.getAllSupertypes(defaultType).filter(typePredicate) for (superType in superTypes) { if (addNullableTypes) { typeSet.add(superType.makeNullable()) } typeSet.add(superType) } typeSet.toList() } override fun getParameterTypeCandidates(): List<KotlinType> { return allParameterTypeCandidates.filter { it.isExtractable(targetScope) } } override val parameterType: KotlinType get() = getParameterTypeCandidates().firstOrNull() ?: defaultType override fun copy(name: String, parameterType: KotlinType): Parameter = DelegatingParameter(this, name, parameterType) } private class DelegatingParameter( val original: Parameter, override val name: String, override val parameterType: KotlinType ) : Parameter by original { override fun copy(name: String, parameterType: KotlinType): Parameter = DelegatingParameter(original, name, parameterType) } private fun ExtractionData.checkDeclarationsMovingOutOfScope( enclosingDeclaration: KtDeclaration, controlFlow: ControlFlow, bindingContext: BindingContext ): ErrorMessage? { val declarationsOutOfScope = HashSet<KtNamedDeclaration>() controlFlow.jumpOutputValue?.elementToInsertAfterCall?.accept( object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val target = expression.mainReference.resolve() if (target is KtNamedDeclaration && target.isInsideOf(physicalElements) && target.getStrictParentOfType<KtDeclaration>() == enclosingDeclaration ) { declarationsOutOfScope.add(target) } } } ) if (declarationsOutOfScope.isNotEmpty()) { val declStr = declarationsOutOfScope.map { it.renderForMessage(bindingContext)!! }.sorted() return ErrorMessage.DECLARATIONS_OUT_OF_SCOPE.addAdditionalInfo(declStr) } return null } private fun ExtractionData.getLocalInstructions(pseudocode: Pseudocode): List<Instruction> { val instructions = ArrayList<Instruction>() pseudocode.traverse(TraversalOrder.FORWARD) { if (it is KtElementInstruction && it.element.isInsideOf(physicalElements)) { instructions.add(it) } } return instructions } fun ExtractionData.isLocal(): Boolean { val parent = targetSibling.parent return parent !is KtClassBody && (parent !is KtFile || parent.isScript()) } fun ExtractionData.isVisibilityApplicable(): Boolean { if (isLocal()) return false if (commonParent.parentsWithSelf.any { it is KtNamedFunction && it.hasModifier(KtTokens.INLINE_KEYWORD) && it.isPublic }) return false return true } fun ExtractionData.getDefaultVisibility(): KtModifierKeywordToken? { if (!isVisibilityApplicable()) return null val parent = targetSibling.getStrictParentOfType<KtDeclaration>() if (parent is KtClass) { if (parent.isInterface()) return null if (parent.isEnum() && commonParent.getNonStrictParentOfType<KtEnumEntry>()?.getStrictParentOfType<KtClass>() == parent) return null } return KtTokens.PRIVATE_KEYWORD } private data class ExperimentalMarkers( val propagatingMarkerDescriptors: List<AnnotationDescriptor>, val optInMarkers: List<FqName> ) { companion object { val empty = ExperimentalMarkers(emptyList(), emptyList()) } } private fun ExtractionData.getExperimentalMarkers(): ExperimentalMarkers { fun AnnotationDescriptor.isExperimentalMarker(): Boolean { if (fqName == null) return false val annotations = annotationClass?.annotations ?: return false return annotations.hasAnnotation(OptInNames.REQUIRES_OPT_IN_FQ_NAME) || annotations.hasAnnotation(FqNames.OptInFqNames.OLD_EXPERIMENTAL_FQ_NAME) } val bindingContext = bindingContext ?: return ExperimentalMarkers.empty val container = commonParent.getStrictParentOfType<KtNamedFunction>() ?: return ExperimentalMarkers.empty val propagatingMarkerDescriptors = mutableListOf<AnnotationDescriptor>() val optInMarkerNames = mutableListOf<FqName>() for (annotationEntry in container.annotationEntries) { val annotationDescriptor = bindingContext[BindingContext.ANNOTATION, annotationEntry] ?: continue val fqName = annotationDescriptor.fqName ?: continue if (fqName in OptInNames.OPT_IN_FQ_NAMES) { for (argument in annotationEntry.valueArguments) { val argumentExpression = argument.getArgumentExpression()?.safeAs<KtClassLiteralExpression>() ?: continue val markerFqName = bindingContext[ BindingContext.REFERENCE_TARGET, argumentExpression.lhs?.safeAs<KtNameReferenceExpression>() ]?.fqNameSafe ?: continue optInMarkerNames.add(markerFqName) } } else if (annotationDescriptor.isExperimentalMarker()) { propagatingMarkerDescriptors.add(annotationDescriptor) } } val requiredMarkers = mutableSetOf<FqName>() if (propagatingMarkerDescriptors.isNotEmpty() || optInMarkerNames.isNotEmpty()) { originalElements.forEach { element -> element.accept(object : KtTreeVisitorVoid() { override fun visitReferenceExpression(expression: KtReferenceExpression) { val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, expression] if (descriptor != null) { for (descr in setOf(descriptor, descriptor.getImportableDescriptor())) { for (ann in descr.annotations) { val fqName = ann.fqName ?: continue if (ann.isExperimentalMarker()) { requiredMarkers.add(fqName) } } } } super.visitReferenceExpression(expression) } }) } } return ExperimentalMarkers( propagatingMarkerDescriptors.filter { it.fqName in requiredMarkers }, optInMarkerNames.filter { it in requiredMarkers } ) } fun ExtractionData.performAnalysis(): AnalysisResult { if (originalElements.isEmpty()) return AnalysisResult(null, Status.CRITICAL_ERROR, listOf(ErrorMessage.NO_EXPRESSION)) val noContainerError = AnalysisResult(null, Status.CRITICAL_ERROR, listOf(ErrorMessage.NO_CONTAINER)) val bindingContext = bindingContext ?: return noContainerError val declaration = commonParent.containingDeclarationForPseudocode ?: return noContainerError val pseudocode = declaration.getContainingPseudocode(bindingContext) ?: return AnalysisResult(null, Status.CRITICAL_ERROR, listOf(ErrorMessage.SYNTAX_ERRORS)) val localInstructions = getLocalInstructions(pseudocode) val modifiedVarDescriptorsWithExpressions = localInstructions.getModifiedVarDescriptors(bindingContext) val virtualBlock = createTemporaryCodeBlock() val targetScope = targetSibling.getResolutionScope(bindingContext, commonParent.getResolutionFacade()) val paramsInfo = inferParametersInfo( virtualBlock, commonParent, pseudocode, bindingContext, targetScope, modifiedVarDescriptorsWithExpressions.keys ) if (paramsInfo.errorMessage != null) { return AnalysisResult(null, Status.CRITICAL_ERROR, listOf(paramsInfo.errorMessage!!)) } val messages = ArrayList<ErrorMessage>() val modifiedVarDescriptorsForControlFlow = HashMap(modifiedVarDescriptorsWithExpressions) modifiedVarDescriptorsForControlFlow.keys.retainAll(localInstructions.getVarDescriptorsAccessedAfterwards(bindingContext)) val (controlFlow, controlFlowMessage) = analyzeControlFlow( localInstructions, pseudocode, originalFile.findModuleDescriptor(), bindingContext, modifiedVarDescriptorsForControlFlow, options, targetScope, paramsInfo.parameters ) controlFlowMessage?.let { messages.add(it) } val returnType = controlFlow.outputValueBoxer.returnType returnType.processTypeIfExtractable(paramsInfo.typeParameters, paramsInfo.nonDenotableTypes, options, targetScope) if (paramsInfo.nonDenotableTypes.isNotEmpty()) { val typeStr = paramsInfo.nonDenotableTypes.map { it.renderForMessage() }.sorted() return AnalysisResult( null, Status.CRITICAL_ERROR, listOf(ErrorMessage.DENOTABLE_TYPES.addAdditionalInfo(typeStr)) ) } val enclosingDeclaration = commonParent.getStrictParentOfType<KtDeclaration>()!! checkDeclarationsMovingOutOfScope(enclosingDeclaration, controlFlow, bindingContext)?.let { messages.add(it) } controlFlow.jumpOutputValue?.elementToInsertAfterCall?.accept( object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { paramsInfo.originalRefToParameter[expression].firstOrNull()?.let { it.refCount-- } } } ) val adjustedParameters = paramsInfo.parameters.filterTo(LinkedHashSet<Parameter>()) { it.refCount > 0 } val receiverCandidates = adjustedParameters.filterTo(hashSetOf()) { it.receiverCandidate } val receiverParameter = if (receiverCandidates.size == 1 && !options.canWrapInWith) receiverCandidates.first() else null receiverParameter?.let { adjustedParameters.remove(it) } val experimentalMarkers = getExperimentalMarkers() var descriptor = ExtractableCodeDescriptor( this, bindingContext, suggestFunctionNames(returnType), getDefaultVisibility(), adjustedParameters.toList(), receiverParameter, paramsInfo.typeParameters.sortedBy { it.originalDeclaration.name!! }, paramsInfo.replacementMap, if (messages.isEmpty()) controlFlow else controlFlow.toDefault(), returnType, emptyList(), annotations = experimentalMarkers.propagatingMarkerDescriptors, optInMarkers = experimentalMarkers.optInMarkers ) val generatedDeclaration = ExtractionGeneratorConfiguration( descriptor, ExtractionGeneratorOptions(inTempFile = true, allowExpressionBody = false) ).generateDeclaration().declaration val virtualContext = generatedDeclaration.analyzeWithContent() if (virtualContext.diagnostics.all() .any { it.factory == Errors.ILLEGAL_SUSPEND_FUNCTION_CALL || it.factory == Errors.ILLEGAL_SUSPEND_PROPERTY_ACCESS } ) { descriptor = descriptor.copy(modifiers = listOf(KtTokens.SUSPEND_KEYWORD)) } for (analyser in AdditionalExtractableAnalyser.EP_NAME.extensions) { descriptor = analyser.amendDescriptor(descriptor) } return AnalysisResult( descriptor, if (messages.isEmpty()) Status.SUCCESS else Status.NON_CRITICAL_ERROR, messages ) } private fun ExtractionData.suggestFunctionNames(returnType: KotlinType): List<String> { val functionNames = LinkedHashSet<String>() val validator = Fe10KotlinNewDeclarationNameValidator( targetSibling.parent, if (targetSibling is KtAnonymousInitializer) targetSibling.parent else targetSibling, when { options.extractAsProperty -> KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE else -> KotlinNameSuggestionProvider.ValidatorTarget.FUNCTION } ) if (!KotlinBuiltIns.isUnit(returnType)) { functionNames.addAll(Fe10KotlinNameSuggester.suggestNamesByType(returnType, validator)) } expressions.singleOrNull()?.let { expr -> val property = expr.getStrictParentOfType<KtProperty>() if (property?.initializer == expr) { property.name?.let { functionNames.add(Fe10KotlinNameSuggester.suggestNameByName("get" + it.capitalizeAsciiOnly(), validator)) } } } return functionNames.toList() } internal fun KtNamedDeclaration.getGeneratedBody() = when (this) { is KtNamedFunction -> bodyExpression else -> { val property = this as KtProperty property.getter?.bodyExpression?.let { return it } property.initializer?.let { return it } // We assume lazy property here with delegate expression 'by Delegates.lazy { body }' property.delegateExpression?.let { val call = it.getCalleeExpressionIfAny()?.parent as? KtCallExpression call?.lambdaArguments?.singleOrNull()?.getLambdaExpression()?.bodyExpression } } } ?: throw AssertionError("Couldn't get block body for this declaration: ${getElementTextWithContext()}") @JvmOverloads fun ExtractableCodeDescriptor.validate(target: ExtractionTarget = ExtractionTarget.FUNCTION): ExtractableCodeDescriptorWithConflicts { fun getDeclarationMessage(declaration: PsiElement, messageKey: String, capitalize: Boolean = true): String { val declarationStr = RefactoringUIUtil.getDescription(declaration, true) val message = KotlinBundle.message(messageKey, declarationStr) return if (capitalize) message.capitalize() else message } val conflicts = MultiMap<PsiElement, String>() val result = ExtractionGeneratorConfiguration( this, ExtractionGeneratorOptions(inTempFile = true, allowExpressionBody = false, target = target) ).generateDeclaration() val valueParameterList = (result.declaration as? KtNamedFunction)?.valueParameterList val typeParameterList = (result.declaration as? KtNamedFunction)?.typeParameterList val generatedDeclaration = result.declaration val bindingContext = generatedDeclaration.analyzeWithContent() fun processReference(currentRefExpr: KtSimpleNameExpression) { val resolveResult = currentRefExpr.resolveResult ?: return if (currentRefExpr.parent is KtThisExpression) return val diagnostics = bindingContext.diagnostics.forElement(currentRefExpr) val currentDescriptor = bindingContext[BindingContext.REFERENCE_TARGET, currentRefExpr] val currentTarget = currentDescriptor?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(extractionData.project, it) } as? PsiNamedElement if (currentTarget is KtParameter && currentTarget.parent == valueParameterList) return if (currentTarget is KtTypeParameter && currentTarget.parent == typeParameterList) return if (currentDescriptor is LocalVariableDescriptor && parameters.any { it.mirrorVarName == currentDescriptor.name.asString() } ) return if (diagnostics.any { it.factory in Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS } || (currentDescriptor != null && !ErrorUtils.isError(currentDescriptor) && !compareDescriptors(extractionData.project, currentDescriptor, resolveResult.descriptor))) { conflicts.putValue( resolveResult.originalRefExpr, getDeclarationMessage(resolveResult.declaration, "0.will.no.longer.be.accessible.after.extraction") ) return } diagnostics.firstOrNull { it.factory in Errors.INVISIBLE_REFERENCE_DIAGNOSTICS }?.let { val message = when (it.factory) { Errors.INVISIBLE_SETTER -> getDeclarationMessage(resolveResult.declaration, "setter.of.0.will.become.invisible.after.extraction", false) else -> getDeclarationMessage(resolveResult.declaration, "0.will.become.invisible.after.extraction") } conflicts.putValue(resolveResult.originalRefExpr, message) } } result.declaration.accept( object : KtTreeVisitorVoid() { override fun visitUserType(userType: KtUserType) { val refExpr = userType.referenceExpression ?: return val diagnostics = bindingContext.diagnostics.forElement(refExpr) diagnostics.firstOrNull { it.factory == Errors.INVISIBLE_REFERENCE }?.let { val declaration = refExpr.mainReference.resolve() as? PsiNamedElement ?: return conflicts.putValue(declaration, getDeclarationMessage(declaration, "0.will.become.invisible.after.extraction")) } } override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { processReference(expression) } } ) return ExtractableCodeDescriptorWithConflicts(this, conflicts) }
apache-2.0
48c8627ee63aa20923ab450da7adb365
43.260349
158
0.710566
5.395883
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SpecifyExplicitLambdaSignatureIntention.kt
1
4152
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtParameterList import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.isError open class SpecifyExplicitLambdaSignatureIntention : SelfTargetingOffsetIndependentIntention<KtLambdaExpression>( KtLambdaExpression::class.java, KotlinBundle.lazyMessage("specify.explicit.lambda.signature") ), LowPriorityAction { override fun isApplicableTo(element: KtLambdaExpression): Boolean { if (element.functionLiteral.arrow != null && element.valueParameters.all { it.typeReference != null }) return false val functionDescriptor = element.analyze(BodyResolveMode.PARTIAL)[BindingContext.FUNCTION, element.functionLiteral] ?: return false return functionDescriptor.valueParameters.none { it.type.isError } } override fun applyTo(element: KtLambdaExpression, editor: Editor?) { applyTo(element) } companion object { fun applyTo(element: KtLambdaExpression) { val functionLiteral = element.functionLiteral val functionDescriptor = element.analyze(BodyResolveMode.PARTIAL)[BindingContext.FUNCTION, functionLiteral]!! applyWithParameters(element, functionDescriptor.valueParameters .asSequence() .mapIndexed { index, parameterDescriptor -> parameterDescriptor.render(psiName = functionLiteral.valueParameters.getOrNull(index)?.let { it.name ?: it.destructuringDeclaration?.text }) } .joinToString()) } fun KtFunctionLiteral.setParameterListIfAny(psiFactory: KtPsiFactory, newParameterList: KtParameterList?) { val oldParameterList = valueParameterList if (oldParameterList != null && newParameterList != null) { oldParameterList.replace(newParameterList) } else { val openBraceElement = lBrace val nextSibling = openBraceElement.nextSibling val addNewline = nextSibling is PsiWhiteSpace && nextSibling.text?.contains("\n") ?: false val (whitespace, arrow) = psiFactory.createWhitespaceAndArrow() addRangeAfter(whitespace, arrow, openBraceElement) if (newParameterList != null) { addAfter(newParameterList, openBraceElement) } if (addNewline) { addAfter(psiFactory.createNewLine(), openBraceElement) } } } fun applyWithParameters(element: KtLambdaExpression, parameterString: String) { val psiFactory = KtPsiFactory(element) val functionLiteral = element.functionLiteral val newParameterList = psiFactory.createLambdaParameterListIfAny(parameterString) runWriteAction { functionLiteral.setParameterListIfAny(psiFactory, newParameterList) ShortenReferences.DEFAULT.process(element.valueParameters) } } } } private fun ValueParameterDescriptor.render(psiName: String?): String = IdeDescriptorRenderers.SOURCE_CODE.let { "${psiName ?: it.renderName(name, true)}: ${it.renderType(type)}" }
apache-2.0
e13d8f79c9b3ce5385b4080e47b3d6f1
48.428571
158
0.707611
5.536
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/tests/test/org/jetbrains/kotlin/jps/build/dependeciestxt/MppJpsIncTestsGenerator.kt
1
16280
// 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.jps.build.dependeciestxt import java.io.File /** * Utility for generating common/platform module stub contents based on it's dependencies. */ fun actualizeMppJpsIncTestCaseDirs(rootDir: String, dir: String) { val rootDirFile = File("$rootDir/$dir") check(rootDirFile.isDirectory) { "`$rootDirFile` is not a directory" } rootDirFile.listFiles { it: File -> it.isDirectory }.forEach { dirFile -> val dependenciesTxtFile = File(dirFile, "dependencies.txt") if (dependenciesTxtFile.exists()) { val fileTitle = "$dir/${dirFile.name}/dependencies.txt" val dependenciesTxt = ModulesTxtBuilder().readFile(dependenciesTxtFile, fileTitle) MppJpsIncTestsGenerator(dependenciesTxt) { File(dirFile, it.name) } .actualizeTestCasesDirs(dirFile) } } return } class MppJpsIncTestsGenerator(val txt: ModulesTxt, val testCaseDirProvider: (TestCase) -> File) { val ModulesTxt.Module.capitalName get() = name.capitalize() val testCases: List<TestCase> init { val testCases = mutableListOf<TestCase>() txt.modules.forEach { if (it.edit) testCases.add(EditingTestCase(it, changeJavaClass = false)) if (it.editJvm && it.isJvmModule) testCases.add(EditingTestCase(it, changeJavaClass = true)) if (it.editExpectActual && it.isCommonModule) testCases.add(EditingExpectActualTestCase(it)) } this.testCases = testCases } fun actualizeTestCasesDirs(rootDir: File) { val requiredDirs = mutableSetOf<File>() testCases.forEach { val dir = it.dir check(requiredDirs.add(dir)) { "TestCase dir clash $dir" } if (!dir.exists()) { File(dir, "build.log").setFileContent("") } } rootDir.listFiles().forEach { if (it.isDirectory && it !in requiredDirs) { it.deleteRecursively() } } } /** * Set required content for [this] [File]. */ fun File.setFileContent(content: String) { check(!exists()) { "File `$this` already exists," + "\n\n============= contents ============\n" + readText() + "\n===================================\n" + "\n============ new content ==========\n" + content + "\n===================================\n" } parentFile.mkdirs() writeText(content) } data class ModuleContentSettings( val module: ModulesTxt.Module, val serviceNameSuffix: String = "", val generateActualDeclarationsFor: List<ModulesTxt.Module> = module.expectedBy.map { it.to }, val generatePlatformDependent: Boolean = true, var generateKtFile: Boolean = true, var generateJavaFile: Boolean = true ) inner class EditingTestCase(val module: ModulesTxt.Module, val changeJavaClass: Boolean) : TestCase() { override val name: String = if (changeJavaClass) "editing${module.capitalName}Java" else "editing${module.capitalName}Kotlin" override val dir: File = testCaseDirProvider(this) override fun generate() { generateBaseContent() // create new file with service implementation // don't create expect/actual functions (generatePlatformDependent = false) module.contentsSettings = ModuleContentSettings( module, serviceNameSuffix = "New", generatePlatformDependent = false, generateKtFile = !changeJavaClass, generateJavaFile = changeJavaClass ) when { module.isCommonModule -> { step("create new service") { generateCommonFile( module, fileNameSuffix = ".new.$step" ) } step("edit new service") { generateCommonFile( module, fileNameSuffix = ".touch.$step" ) } step("delete new service") { serviceKtFile( module, fileNameSuffix = ".delete.$step" ).setFileContent("") } } else -> { step("create new service") { // generateKtFile event if changeJavaClass requested (for test calling java from kotlin) val prevModuleContentsSettings = module.contentsSettings module.contentsSettings = module.contentsSettings.copy(generateKtFile = true) generatePlatformFile( module, fileNameSuffix = ".new.$step" ) module.contentsSettings = prevModuleContentsSettings } step("edit new service") { generatePlatformFile( module, fileNameSuffix = ".touch.$step" ) } step("delete new service") { if (changeJavaClass) serviceJavaFile(module, fileNameSuffix = ".delete.$step").setFileContent("") // kotlin file also created for testing java class serviceKtFile(module, fileNameSuffix = ".delete.$step").setFileContent("") } } } generateStepsTxt() } } inner class EditingExpectActualTestCase(val commonModule: ModulesTxt.Module) : TestCase() { override val name: String = "editing${commonModule.capitalName}ExpectActual" override val dir: File = testCaseDirProvider(this) override fun generate() { generateBaseContent() check(commonModule.isCommonModule) val implModules = commonModule.usages .asSequence() .filter { it.kind == ModulesTxt.Dependency.Kind.EXPECTED_BY || it.kind == ModulesTxt.Dependency.Kind.INCLUDE } .map { it.from } commonModule.contentsSettings = ModuleContentSettings(commonModule, serviceNameSuffix = "New") implModules.forEach { implModule -> implModule.contentsSettings = ModuleContentSettings( implModule, serviceNameSuffix = "New", generateActualDeclarationsFor = listOf(commonModule) ) } step("create new service in ${commonModule.name}") { generateCommonFile(commonModule, fileNameSuffix = ".new.$step") } implModules.forEach { implModule -> step("create new service in ${implModule.name}") { generatePlatformFile(implModule, fileNameSuffix = ".new.$step") } } step("change new service in ${commonModule.name}") { generateCommonFile(commonModule, fileNameSuffix = ".touch.$step") } implModules.forEach { implModule -> if (implModule.isJvmModule) { implModule.contentsSettings.generateKtFile = false implModule.contentsSettings.generateJavaFile = true step("change new service in ${implModule.name}: java") { generatePlatformFile(implModule, fileNameSuffix = ".touch.$step") } implModule.contentsSettings.generateKtFile = true implModule.contentsSettings.generateJavaFile = false step("change new service in ${implModule.name}: kotlin") { generatePlatformFile(implModule, fileNameSuffix = ".touch.$step") } } else { step("change new service in ${implModule.name}") { generatePlatformFile(implModule, fileNameSuffix = ".touch.$step") } } } implModules.forEach { implModule -> step("delete new service in ${implModule.name}") { serviceKtFile(implModule, fileNameSuffix = ".delete.$step").setFileContent("") } } step("delete new service in ${commonModule.name}") { serviceKtFile(commonModule, fileNameSuffix = ".delete.$step").setFileContent("") } generateStepsTxt() } } abstract inner class TestCase() { abstract val name: String abstract fun generate() abstract val dir: File private val modules = mutableMapOf<ModulesTxt.Module, ModuleContentSettings>() var step = 1 val steps = mutableListOf<String>() protected inline fun step(name: String, body: () -> Unit) { body() steps.add(name) step++ } var ModulesTxt.Module.contentsSettings: ModuleContentSettings get() = modules.getOrPut(this) { ModuleContentSettings(this) } set(value) { modules[this] = value } protected fun generateStepsTxt() { File(dir, "_steps.txt").setFileContent(steps.joinToString("\n")) } fun generateBaseContent() { dir.mkdir() txt.modules.forEach { generateModuleContents(it) } } private fun generateModuleContents(module: ModulesTxt.Module) { when { module.isCommonModule -> { // common module generateCommonFile(module) } module.expectedBy.isEmpty() -> { // regular module generatePlatformFile(module) } else -> { // common module platform implementation generatePlatformFile(module) } } } private val ModulesTxt.Module.serviceName get() = "$capitalName${contentsSettings.serviceNameSuffix}" private val ModulesTxt.Module.javaClassName get() = "${serviceName}JavaClass" protected fun serviceKtFile(module: ModulesTxt.Module, fileNameSuffix: String = ""): File { val suffix = if (module.isCommonModule) "${module.serviceName}Header" else "${module.name.capitalize()}${module.contentsSettings.serviceNameSuffix}Impl" return File(dir, "${module.indexedName}_service$suffix.kt$fileNameSuffix") } fun serviceJavaFile(module: ModulesTxt.Module, fileNameSuffix: String = ""): File { return File(dir, "${module.indexedName}_${module.javaClassName}.java$fileNameSuffix") } private val ModulesTxt.Module.platformDependentFunName: String get() { check(isCommonModule) return "${name}_platformDependent$serviceName" } private val ModulesTxt.Module.platformIndependentFunName: String get() { check(isCommonModule) return "${name}_platformIndependent$serviceName" } private val ModulesTxt.Module.platformOnlyFunName: String get() { // platformOnly fun names already unique, so no module name prefix required return "${name}_platformOnly${contentsSettings.serviceNameSuffix}" } protected fun generateCommonFile( module: ModulesTxt.Module, fileNameSuffix: String = "" ) { val settings = module.contentsSettings serviceKtFile(module, fileNameSuffix).setFileContent(buildString { if (settings.generatePlatformDependent) appendLine("expect fun ${module.platformDependentFunName}(): String") appendLine("fun ${module.platformIndependentFunName}() = \"common$fileNameSuffix\"") appendTestFun(module, settings) }) } protected fun generatePlatformFile( module: ModulesTxt.Module, fileNameSuffix: String = "" ) { val isJvm = module.isJvmModule val settings = module.contentsSettings val javaClassName = module.javaClassName if (settings.generateKtFile) { serviceKtFile(module, fileNameSuffix).setFileContent(buildString { if (settings.generatePlatformDependent) { for (expectedBy in settings.generateActualDeclarationsFor) { appendLine( "actual fun ${expectedBy.platformDependentFunName}(): String" + " = \"${module.name}$fileNameSuffix\"" ) } } appendLine( "fun ${module.platformOnlyFunName}()" + " = \"${module.name}$fileNameSuffix\"" ) appendTestFun(module, settings) }) } if (isJvm && settings.generateJavaFile) { serviceJavaFile(module, fileNameSuffix).setFileContent( """ |public class $javaClassName { | public String doStuff() { | return "${module.name}$fileNameSuffix"; | } |} """.trimMargin() ) } } // call all functions declared in this module and all of its dependencies recursively private fun StringBuilder.appendTestFun( module: ModulesTxt.Module, settings: ModuleContentSettings ) { appendLine() appendLine("fun Test${module.serviceName}() {") val thisAndDependencies = mutableSetOf(module) module.collectDependenciesRecursivelyTo(thisAndDependencies) thisAndDependencies.forEach { thisOrDependent -> if (thisOrDependent.isCommonModule) { appendLine(" ${thisOrDependent.platformIndependentFunName}()") if (settings.generatePlatformDependent) { appendLine(" ${thisOrDependent.platformDependentFunName}()") } } else { // platform module appendLine(" ${thisOrDependent.platformOnlyFunName}()") if (thisOrDependent.isJvmModule && thisOrDependent.contentsSettings.generateJavaFile) { appendLine(" ${thisOrDependent.javaClassName}().doStuff()") } } } appendLine("}") } private fun ModulesTxt.Module.collectDependenciesRecursivelyTo( collection: MutableCollection<ModulesTxt.Module>, exportedOnly: Boolean = false ) { dependencies.forEach { if (!exportedOnly || it.effectivelyExported) { val dependentModule = it.to collection.add(dependentModule) dependentModule.collectDependenciesRecursivelyTo(collection, exportedOnly = true) } } } override fun toString() = name } }
apache-2.0
d5c211eaa4f7067d68be9f327c803ea3
36.16895
158
0.52586
5.613793
false
true
false
false
jwren/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223JvmScriptEngine4Idea.kt
3
4081
// 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.jsr223 import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.repl.* import org.jetbrains.kotlin.daemon.client.DaemonReportMessage import org.jetbrains.kotlin.daemon.client.DaemonReportingTargets import org.jetbrains.kotlin.daemon.client.KotlinCompilerClient import org.jetbrains.kotlin.daemon.client.KotlinRemoteReplCompilerClient import org.jetbrains.kotlin.daemon.common.* import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts import org.jetbrains.kotlin.utils.KotlinPaths import org.jetbrains.kotlin.utils.KotlinPathsFromHomeDir import java.io.File import java.util.concurrent.locks.ReentrantReadWriteLock import javax.script.ScriptContext import javax.script.ScriptEngineFactory import javax.script.ScriptException import kotlin.io.path.exists import kotlin.reflect.KClass // TODO: need to manage resources here, i.e. call replCompiler.dispose when engine is collected class KotlinJsr223JvmScriptEngine4Idea( factory: ScriptEngineFactory, templateClasspath: List<File>, templateClassName: String, private val getScriptArgs: (ScriptContext, Array<out KClass<out Any>>?) -> ScriptArgsWithTypes?, private val scriptArgsTypes: Array<out KClass<out Any>>? ) : KotlinJsr223JvmScriptEngineBase(factory) { private val daemon by lazy { val libPath = KotlinPathsFromHomeDir(KotlinArtifacts.instance.kotlincDirectory) val classPath = libPath.classPath(KotlinPaths.ClassPaths.CompilerWithScripting) assert(classPath.all { it.toPath().exists() }) val compilerId = CompilerId.makeCompilerId(classPath) val daemonOptions = configureDaemonOptions() val daemonJVMOptions = DaemonJVMOptions() val daemonReportMessages = arrayListOf<DaemonReportMessage>() KotlinCompilerClient.connectToCompileService( compilerId, daemonJVMOptions, daemonOptions, DaemonReportingTargets(null, daemonReportMessages), autostart = true, checkId = true ) ?: throw ScriptException( "Unable to connect to repl server:" + daemonReportMessages.joinToString("\n ", prefix = "\n ") { "${it.category.name} ${it.message}" } ) } private val messageCollector = MyMessageCollector() override val replCompiler: ReplCompilerWithoutCheck by lazy { KotlinRemoteReplCompilerClient( daemon, makeAutodeletingFlagFile("idea-jsr223-repl-session"), CompileService.TargetPlatform.JVM, emptyArray(), messageCollector, templateClasspath, templateClassName ) } override fun overrideScriptArgs(context: ScriptContext): ScriptArgsWithTypes? = getScriptArgs(getContext(), scriptArgsTypes) private val localEvaluator: ReplFullEvaluator by lazy { GenericReplCompilingEvaluator(replCompiler, templateClasspath, Thread.currentThread().contextClassLoader) } override val replEvaluator: ReplFullEvaluator get() = localEvaluator override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = replEvaluator.createState(lock) private class MyMessageCollector : MessageCollector { private var hasErrors: Boolean = false override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?) { System.err.println(message) // TODO: proper location printing if (!hasErrors) { hasErrors = severity == CompilerMessageSeverity.EXCEPTION || severity == CompilerMessageSeverity.ERROR } } override fun clear() {} override fun hasErrors(): Boolean = hasErrors } }
apache-2.0
8018e377caa1224cd7dc73dd5309dbf9
41.957895
158
0.74026
4.928744
false
false
false
false
GunoH/intellij-community
platform/platform-api/src/com/intellij/openapi/observable/properties/PropertyGraph.kt
2
5187
// 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.observable.operation.core.AtomicOperationTrace import com.intellij.openapi.observable.operation.core.traceRun import com.intellij.openapi.observable.operation.core.whenOperationFinished import com.intellij.openapi.util.RecursionManager import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList /** * PropertyGraph is traces modifications inside observable properties. It creates graph of dependent properties. * * PropertyGraph can recognize and stop infinity updates between properties. For example, we have properties * A -> B -> C -> A (-> depends on) and property A is modified. Then property graph detects this cycle, and it doesn't * make last modification. * * PropertyGraph can block propagation through property, which was modified externally (outside PropertyGraph). * It is needed for UI cases. For example, we have dependent properties id and name. When we modify property id, we put * id's value into property name. But if we modify property name and after that try to modify id property then property * name isn't modified automatically. * * @param isBlockPropagation if true then property changes propagation will be blocked through modified properties. */ class PropertyGraph(debugName: String? = null, private val isBlockPropagation: Boolean = true) { private val propagation = AtomicOperationTrace("Graph ${debugName ?: "UNKNOWN"} propagation") private val properties = ConcurrentHashMap<ObservableProperty<*>, PropertyNode>() private val dependencies = ConcurrentHashMap<PropertyNode, CopyOnWriteArrayList<Dependency<*>>>() private val recursionGuard = RecursionManager.createGuard<PropertyNode>(PropertyGraph::class.java.name) /** * Creates graph simple builder property. */ fun <T> property(initial: T): GraphProperty<T> = GraphPropertyImpl(this) { initial } /** * Creates graph builder property with lazy initialization. */ fun <T> lazyProperty(initial: () -> T): GraphProperty<T> = GraphPropertyImpl(this, initial) /** * Creates dependency between [child] and [parent] properties. * @param update, result of this function will be applied into [child] when [parent] is modified. * @see PropertyGraph */ fun <T> dependsOn(child: ObservableMutableProperty<T>, parent: ObservableProperty<*>, update: () -> T) { val childNode = getOrRegisterNode(child) val parentNode = getOrRegisterNode(parent) dependencies.computeIfAbsent(parentNode) { CopyOnWriteArrayList() } .add(Dependency(childNode, child, update)) } /** * Registers callback on propagation process. * @param listener is callback which will be called when properties changes are finished. * @see PropertyGraph */ fun afterPropagation(listener: () -> Unit) { propagation.whenOperationFinished(listener) } /** * Registers callback on propagation process. * @param parentDisposable is used to arly unsubscribe from property graph propagation events. * @param listener is callback which will be called when properties changes are finished. * @see PropertyGraph */ fun afterPropagation(parentDisposable: Disposable?, listener: () -> Unit) { if (parentDisposable == null) { propagation.whenOperationFinished(listener) } else { propagation.whenOperationFinished(parentDisposable, listener) } } private fun getOrRegisterNode(property: ObservableProperty<*>): PropertyNode { return properties.computeIfAbsent(property) { PropertyNode().also { node -> property.afterChange { recursionGuard.doPreventingRecursion(node, false) { propagation.traceRun { node.isPropagationBlocked = isBlockPropagation propagateChange(node) } } } } } } private fun propagateChange(parent: PropertyNode) { val dependencies = dependencies[parent] ?: return for (dependency in dependencies) { val child = dependency.node if (child.isPropagationBlocked) continue recursionGuard.doPreventingRecursion(child, false) { dependency.applyUpdate() propagateChange(child) } } } @ApiStatus.Internal fun register(property: ObservableProperty<*>) { getOrRegisterNode(property) } @TestOnly fun isPropagationBlocked(property: ObservableProperty<*>) = properties.getValue(property).isPropagationBlocked private class PropertyNode { @Volatile var isPropagationBlocked = false } private data class Dependency<T>( val node: PropertyNode, private val property: ObservableMutableProperty<T>, private val update: () -> T ) { fun applyUpdate() { if (property is AtomicMutableProperty) { property.updateAndGet { update() } } else { property.set(update()) } } } }
apache-2.0
d92f87515e3717caa1aa8593e86e953c
37.147059
140
0.728167
4.898017
false
false
false
false
smmribeiro/intellij-community
platform/platform-tests/testSrc/com/intellij/ui/charts/LineChartKotlinTest.kt
10
2622
package com.intellij.ui.charts import com.intellij.ui.charts.* import com.intellij.util.ui.ImageUtil import org.junit.Assert import org.junit.Test import java.awt.Dimension import java.awt.image.BufferedImage import kotlin.math.roundToInt class LineChartKotlinTest { @Test fun simpleCreation() { val chart = lineChart<Int, Int> { datasets { dataset { values { x = listOf(2, 3, 4) y = listOf(1, 2, 3) } } } } val xy = chart.findMinMax() Assert.assertEquals(2, xy.xMin) Assert.assertEquals(4, xy.xMax) Assert.assertEquals(1, xy.yMin) Assert.assertEquals(3, xy.yMax) } @Test fun checkDoubleCreation() { val chart = lineChart<Double, Double> { datasets { dataset { generate { x = generator(0.01).prepare(0.0, 100.0) y = { it } } } } } val xy = chart.findMinMax() Assert.assertEquals(0.0, xy.xMin, 1e-6) Assert.assertEquals(100.0, xy.xMax, 1e-6) Assert.assertEquals(0.0, xy.yMin, 1e-6) Assert.assertEquals(100.0, xy.yMax, 1e-6) } @Test fun testLinearChart() { val size = 1000 val chart = lineChart<Double, Double> { dataset { generate { x = generator(10.0 / size).prepare(0.0, size / 10.0) y = { it } } } } val img = ImageUtil.createImage(size, size, BufferedImage.TYPE_INT_RGB) chart.component.apply { this.size = Dimension(size, size) invalidate() paint(img.createGraphics()) } val xy = chart.findMinMax() for (i in 0..size) { val loc = chart.findLocation(xy, i / 10.0 to i / 10.0) Assert.assertEquals("x fails, i = $i", i.toDouble(), loc.x, 1e-6) Assert.assertEquals("y fails, i = $i", (size - i).toDouble(), loc.y, 1e-6) } } @Test fun testLinearChartAndScaled() { val size = 1000 val chart = lineChart<Double, Double> { dataset { generate { x = generator(10.0 / size).prepare(0.0, size / 10.0) y = { it } } } } val img = ImageUtil.createImage(size, size, BufferedImage.TYPE_INT_RGB) chart.component.apply { this.size = Dimension(size, (size * 1.5).roundToInt()) invalidate() paint(img.createGraphics()) } val xy = chart.findMinMax() for (i in 0..size) { val loc = chart.findLocation(xy, i / 10.0 to i / 10.0) Assert.assertEquals("x fails, i = $i", i.toDouble(), loc.x, 1e-6) Assert.assertEquals("y fails, i = $i", (size - i) * 1.5, loc.y, 1e-6) } } }
apache-2.0
68cff4eba9ce04fd75062bd1f546d0c2
24.466019
80
0.56865
3.331639
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/checker/Variance.kt
13
1302
package variance abstract class Consumer<in T> {} abstract class Producer<out T> {} abstract class Usual<T> {} fun foo(c: Consumer<Int>, p: Producer<Int>, u: Usual<Int>) { val c1: Consumer<Any> = <error>c</error> val <warning>c2</warning>: Consumer<Int> = c1 val p1: Producer<Any> = p val <warning>p2</warning>: Producer<Int> = <error>p1</error> val u1: Usual<Any> = <error>u</error> val <warning>u2</warning>: Usual<Int> = <error>u1</error> } //Arrays copy example class Array<T>(val length : Int, val t : T) { fun get(<warning>index</warning> : Int) : T { return t } fun set(<warning>index</warning> : Int, <warning>value</warning> : T) { /* ... */ } } fun copy1(<warning>from</warning> : Array<Any>, <warning>to</warning> : Array<Any>) {} fun copy2(<warning>from</warning> : Array<out Any>, <warning>to</warning> : Array<in Any>) {} fun <T> copy3(<warning>from</warning> : Array<out T>, <warning>to</warning> : Array<in T>) {} fun copy4(<warning>from</warning> : Array<out Number>, <warning>to</warning> : Array<in Int>) {} fun f(ints: Array<Int>, any: Array<Any>, numbers: Array<Number>) { copy1(<error>ints</error>, any) copy2(ints, any) //ok copy2(ints, <error>numbers</error>) copy3<Int>(ints, numbers) copy4(ints, numbers) //ok }
apache-2.0
f6c386dde1d3609c83549c8a669747b5
31.55
96
0.632104
2.880531
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/SyntheticPropertyAccessorReference.kt
1
8450
// 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.references import com.intellij.psi.PsiElement import com.intellij.util.SmartList import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.propertyNameByGetMethodName import org.jetbrains.kotlin.load.java.propertyNameBySetMethodName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.utils.addIfNotNull class SyntheticPropertyAccessorReferenceDescriptorImpl( expression: KtNameReferenceExpression, getter: Boolean ) : SyntheticPropertyAccessorReference(expression, getter), KtDescriptorsBasedReference { override fun isReferenceTo(element: PsiElement): Boolean = super<SyntheticPropertyAccessorReference>.isReferenceTo(element) override fun additionalIsReferenceToChecker(element: PsiElement): Boolean = matchesTarget(element) override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> { val descriptors = expression.getReferenceTargets(context) if (descriptors.none { it is SyntheticJavaPropertyDescriptor }) return emptyList() val result = SmartList<FunctionDescriptor>() for (descriptor in descriptors) { if (descriptor is SyntheticJavaPropertyDescriptor) { if (getter) { result.add(descriptor.getMethod) } else { result.addIfNotNull(descriptor.setMethod) } } } return result } private fun renameByPropertyName(newName: String): PsiElement? { val nameIdentifier = KtPsiFactory(expression).createNameIdentifier(newName) expression.getReferencedNameElement().replace(nameIdentifier) return expression } private fun KtExpression.createCall( psiFactory: KtPsiFactory, newName: String? = null, argument: KtExpression? = null ): KtExpression { return if (this is KtQualifiedExpression) { copied().also { val selector = it.getQualifiedElementSelector() as? KtExpression selector?.replace(selector.createCall(psiFactory, newName, argument)) } } else { psiFactory.buildExpression { if (newName != null) { appendFixedText(newName) } else { appendExpression(this@createCall) } appendFixedText("(") if (argument != null) { appendExpression(argument) } appendFixedText(")") } } } override fun handleElementRename(newElementName: String): PsiElement? { if (!Name.isValidIdentifier(newElementName)) return expression val newNameAsName = Name.identifier(newElementName) val newName = if (getter) { propertyNameByGetMethodName(newNameAsName) } else { //TODO: it's not correct //TODO: setIsY -> setIsIsY bug propertyNameBySetMethodName( newNameAsName, withIsPrefix = expression.getReferencedNameAsName().asString().startsWith("is") ) } // get/set becomes ordinary method if (newName == null) { val psiFactory = KtPsiFactory(expression) val newGetterName = if (getter) newElementName else JvmAbi.getterName(expression.getReferencedName()) if (expression.readWriteAccess(false) == ReferenceAccess.READ) { return expression.replaced(expression.createCall(psiFactory, newGetterName)) } val newSetterName = if (getter) JvmAbi.setterName(expression.getReferencedName()) else newElementName val fullExpression = expression.getQualifiedExpressionForSelectorOrThis() fullExpression.getAssignmentByLHS()?.let { assignment -> val rhs = assignment.right ?: return expression val operationToken = assignment.operationToken as? KtSingleValueToken ?: return expression val counterpartOp = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[operationToken] val setterArgument = if (counterpartOp != null) { val getterCall = if (getter) fullExpression.createCall(psiFactory, newGetterName) else fullExpression psiFactory.createExpressionByPattern("$0 ${counterpartOp.value} $1", getterCall, rhs) } else { rhs } val newSetterCall = fullExpression.createCall(psiFactory, newSetterName, setterArgument) return assignment.replaced(newSetterCall).getQualifiedElementSelector() } fullExpression.getStrictParentOfType<KtUnaryExpression>()?.let { unaryExpr -> val operationToken = unaryExpr.operationToken as? KtSingleValueToken ?: return expression if (operationToken !in OperatorConventions.INCREMENT_OPERATIONS) return expression val operationName = OperatorConventions.getNameForOperationSymbol(operationToken) val originalValue = if (getter) fullExpression.createCall(psiFactory, newGetterName) else fullExpression val incDecValue = psiFactory.createExpressionByPattern("$0.$operationName()", originalValue) val parent = unaryExpr.parent val context = parent.parentsWithSelf.firstOrNull { it is KtBlockExpression || it is KtDeclarationContainer } if (context == parent || context == null) { val newSetterCall = fullExpression.createCall(psiFactory, newSetterName, incDecValue) return unaryExpr.replaced(newSetterCall).getQualifiedElementSelector() } else { val anchor = parent.parentsWithSelf.firstOrNull { it.parent == context } val validator = NewDeclarationNameValidator( context, anchor, NewDeclarationNameValidator.Target.VARIABLES ) val varName = KotlinNameSuggester.suggestNamesByExpressionAndType( unaryExpr, null, unaryExpr.analyze(), validator, "p" ).first() val isPrefix = unaryExpr is KtPrefixExpression val varInitializer = if (isPrefix) incDecValue else originalValue val newVar = psiFactory.createDeclarationByPattern<KtProperty>("val $varName = $0", varInitializer) val setterArgument = psiFactory.createExpression(if (isPrefix) varName else "$varName.$operationName()") val newSetterCall = fullExpression.createCall(psiFactory, newSetterName, setterArgument) val newLine = psiFactory.createNewLine() context.addBefore(newVar, anchor) context.addBefore(newLine, anchor) context.addBefore(newSetterCall, anchor) return unaryExpr.replaced(psiFactory.createExpression(varName)) } } return expression } return renameByPropertyName(newName.identifier) } override val resolvesByNames: Collection<Name> get() = listOf(element.getReferencedNameAsName()) }
apache-2.0
4ba49ef9be6c5c4427ebec36fc3b7a16
48.127907
158
0.654911
5.904962
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewSharedSettings.kt
2
1707
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectView.impl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.SettingsCategory import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil /** * @author Konstantin Bulenkov */ @State(name = "ProjectViewSharedSettings", storages = [(Storage(value = "projectView.xml"))], category = SettingsCategory.UI) class ProjectViewSharedSettings : PersistentStateComponent<ProjectViewSharedSettings> { var flattenPackages: Boolean = false var showMembers: Boolean = false var sortByType: Boolean = false var showModules: Boolean = true var flattenModules: Boolean = false var showExcludedFiles: Boolean = true var showVisibilityIcons: Boolean = false var showLibraryContents: Boolean = true var hideEmptyPackages: Boolean = true var compactDirectories: Boolean = false var abbreviatePackages: Boolean = false var autoscrollFromSource: Boolean = false var autoscrollToSource: Boolean = false var foldersAlwaysOnTop: Boolean = true var manualOrder: Boolean = false override fun getState(): ProjectViewSharedSettings? { return this } override fun loadState(state: ProjectViewSharedSettings) { XmlSerializerUtil.copyBean(state, this) } companion object { val instance: ProjectViewSharedSettings get() = ApplicationManager.getApplication().getService(ProjectViewSharedSettings::class.java) } }
apache-2.0
05a03df1158052d38add6582fedb86e9
37.795455
140
0.78969
4.768156
false
false
false
false
mackristof/FollowMe
mobile/src/main/java/org/mackristof/followme/message/ActivateGpsMsg.kt
1
2137
package org.mackristof.followme.message import android.content.Context import android.os.Bundle import android.util.Log import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.wearable.MessageApi import com.google.android.gms.wearable.MessageEvent import com.google.android.gms.wearable.Wearable import org.mackristof.followme.Constants import kotlin.concurrent.thread /** * Created by christophem on 05/01/2016. */ class ActivateGpsMsg constructor(context: Context, nodeId: String, text: String?, succes: (nodeWearId:String) -> Unit, failure:() -> Unit): Msg, GoogleApiClient.ConnectionCallbacks, MessageApi.MessageListener { override val path = Constants.COMMAND_ACTIVATE_GPS override val text: String? = text private var mApiClient: GoogleApiClient? = null val nodeId = nodeId val succes = succes val failure = failure init { if (mApiClient == null) { mApiClient = GoogleApiClient.Builder(context) .addConnectionCallbacks(this) .addApi(Wearable.API) .build() mApiClient?.connect() } } // on receiving msg from wearable device override fun onMessageReceived(messageEvent: MessageEvent) { if (messageEvent.path == Constants.COMMAND_ACTIVATE_GPS) { Log.i(Constants.TAG,"gps locked with "+String(messageEvent.data)) if (messageEvent.data.toString()=="true"){ succes(messageEvent.sourceNodeId) } else { failure() } mApiClient?.disconnect() } } //on google wearable connected override fun onConnected(bundle: Bundle?) { Wearable.MessageApi.addListener(mApiClient,this) } //on google wearable suspended override fun onConnectionSuspended(p0: Int) { throw UnsupportedOperationException() } fun sendMessage() { thread() { Log.i(Constants.TAG, "send ActivateGpsMsg") Wearable.MessageApi.sendMessage(mApiClient, nodeId, path, text?.toByteArray()).await(); } } }
apache-2.0
cd3a3bd4d8c9ae4f2233c9b90aa9960a
30.910448
210
0.659336
4.480084
false
false
false
false
kmikusek/light-sensor
app/src/main/java/pl/pw/mgr/lightsensor/main/MainPresenter.kt
1
2965
package pl.pw.mgr.lightsensor.main import android.hardware.SensorManager import pl.pw.mgr.lightsensor.common.C import pl.pw.mgr.lightsensor.common.Calibrator import pl.pw.mgr.lightsensor.common.EventsHandler import pl.pw.mgr.lightsensor.common.ObservableFixedSizeQueue import pl.pw.mgr.lightsensor.data.model.Calibration import pl.pw.mgr.lightsensor.data.source.DataSource import pl.pw.mgr.lightsensor.data.source.Repository import javax.inject.Inject internal class MainPresenter @Inject constructor( private val view: MainContract.View, private val repository: Repository, private val calibrator: Calibrator, sensorManager: SensorManager ) : MainContract.Presenter { private val values = ObservableFixedSizeQueue<Float>( C.Chart.TIME_PERIOD_IN_SECONDS, { if (view.isActive()) { view.showValues(it.map { calibrator.compute(it) }) if (validRange.first != C.INVALID_FLOAT && validRange.second != C.INVALID_FLOAT) { if (it.last < validRange.first || it.last > validRange.second) { view.showInvalidCalibrationRangeError() } else { view.hideInvalidCalibrationRangeError() } } else { view.hideInvalidCalibrationRangeError() } } } ) private val eventHandler = EventsHandler( C.Chart.REFRESHING_FREQUENCY, sensorManager, { values.add(it) } ) private var id: String? = null private var validRange = Pair(C.INVALID_FLOAT, C.INVALID_FLOAT) override fun start() { id?.let { repository.getCalibration(it, object : DataSource.GetCalibrationCallback { override fun onCalibrationLoaded(calibration: Calibration) = setCalibration(calibration) override fun onDataNotAvailable() = setNoCalibration() }) } ?: setNoCalibration() eventHandler.start() } override fun onStop() = eventHandler.stop() override fun onResult(id: String?) { this.id = id } private fun setCalibration(calibration: Calibration) { calibrator.setPoints(calibration.points.map { Pair(it.before, it.after) }) val range = mutableListOf<Float>() range.addAll(calibration.points.map { it.before }) if (range.size > 1) { range.sort() this.validRange = Pair(range.first(), range.last()) } else { this.validRange = Pair(C.INVALID_FLOAT, C.INVALID_FLOAT) } if (view.isActive()) view.showCalibration(calibration) } private fun setNoCalibration() { calibrator.setPoints(listOf()) validRange = Pair(C.INVALID_FLOAT, C.INVALID_FLOAT) if (view.isActive()) view.showNoCalibration() } }
mit
1f11121bbc157b557d34f4418e3b97ba
34.722892
104
0.612816
4.512938
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/HttpRequester.kt
1
11186
package ch.rmy.android.http_shortcuts.http import android.content.ContentResolver import android.content.Context import android.net.Uri import ch.rmy.android.framework.extensions.logInfo import ch.rmy.android.framework.extensions.runFor import ch.rmy.android.framework.extensions.runIf import ch.rmy.android.framework.extensions.runIfNotNull import ch.rmy.android.framework.extensions.takeUnlessEmpty import ch.rmy.android.http_shortcuts.data.domains.variables.VariableId import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKey import ch.rmy.android.http_shortcuts.data.enums.ParameterType import ch.rmy.android.http_shortcuts.data.enums.RequestBodyType import ch.rmy.android.http_shortcuts.data.enums.ShortcutAuthenticationType import ch.rmy.android.http_shortcuts.data.models.ShortcutModel import ch.rmy.android.http_shortcuts.http.RequestUtil.FORM_MULTIPART_CONTENT_TYPE import ch.rmy.android.http_shortcuts.http.RequestUtil.FORM_URLENCODE_CONTENT_TYPE import ch.rmy.android.http_shortcuts.utils.UserAgentUtil import ch.rmy.android.http_shortcuts.variables.Variables import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ensureActive import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import okhttp3.CookieJar import okhttp3.Response import java.net.UnknownHostException import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException class HttpRequester @Inject constructor( private val context: Context, private val httpClientFactory: HttpClientFactory, private val responseFileStorageFactory: ResponseFileStorageFactory, private val cookieManager: CookieManager, ) { private val contentResolver: ContentResolver get() = context.contentResolver suspend fun executeShortcut( context: Context, shortcut: ShortcutModel, sessionId: String, variableValues: Map<VariableId, String>, fileUploadResult: FileUploadManager.Result? = null, useCookieJar: Boolean = false, ): ShortcutResponse = withContext(Dispatchers.IO) { val responseFileStorage = responseFileStorageFactory.create(sessionId) val requestData = RequestData( url = Variables.rawPlaceholdersToResolvedValues(shortcut.url, variableValues).trim(), username = Variables.rawPlaceholdersToResolvedValues(shortcut.username, variableValues), password = Variables.rawPlaceholdersToResolvedValues(shortcut.password, variableValues), authToken = Variables.rawPlaceholdersToResolvedValues(shortcut.authToken, variableValues), body = Variables.rawPlaceholdersToResolvedValues(shortcut.bodyContent, variableValues), proxyHost = shortcut.proxyHost ?.let { Variables.rawPlaceholdersToResolvedValues(it, variableValues) } ?.trim(), ) val cookieJar = if (useCookieJar) cookieManager.getCookieJar() else null try { makeRequest(context, shortcut, variableValues, requestData, responseFileStorage, fileUploadResult, cookieJar) } catch (e: UnknownHostException) { ensureActive() if (ServiceDiscoveryHelper.isDiscoverable(requestData.uri)) { val newRequestData = try { val newHost = ServiceDiscoveryHelper.discoverService(context, requestData.uri.host!!) ensureActive() requestData.copy( url = requestData.uri .buildUpon() .encodedAuthority("${newHost.address}:${newHost.port}") .build() .toString() ) } catch (discoveryError: ServiceDiscoveryHelper.ServiceLookupTimeoutException) { requestData } makeRequest(context, shortcut, variableValues, newRequestData, responseFileStorage, fileUploadResult, cookieJar) } else { throw e } } } private suspend fun makeRequest( context: Context, shortcut: ShortcutModel, variablesValues: Map<VariableId, String>, requestData: RequestData, responseFileStorage: ResponseFileStorage, fileUploadResult: FileUploadManager.Result? = null, cookieJar: CookieJar? = null, ): ShortcutResponse = suspendCancellableCoroutine { continuation -> val useDigestAuth = shortcut.authenticationType == ShortcutAuthenticationType.DIGEST val client = httpClientFactory.getClient( context = context, clientCertParams = shortcut.clientCertParams, acceptAllCertificates = shortcut.acceptAllCertificates, username = requestData.username.takeIf { useDigestAuth }, password = requestData.password.takeIf { useDigestAuth }, followRedirects = shortcut.followRedirects, timeout = shortcut.timeout.toLong(), proxyHost = requestData.proxyHost, proxyPort = shortcut.proxyPort, cookieJar = cookieJar, ) val request = RequestBuilder(shortcut.method, requestData.url) .header(HttpHeaders.CONNECTION, "close") .userAgent(UserAgentUtil.userAgent) .runIf(shortcut.usesCustomBody()) { contentType(determineContentType(shortcut)) .body(requestData.body) } .runIf(shortcut.usesGenericFileBody() || shortcut.usesImageFileBody()) { val file = fileUploadResult?.getFile(0) runIfNotNull(file) { contentType(determineContentType(shortcut) ?: it.mimeType) .body(contentResolver.openInputStream(it.data)!!, length = it.fileSize) } } .runIf(shortcut.usesRequestParameters()) { contentType(determineContentType(shortcut)) .run { attachParameters(this, shortcut, variablesValues, fileUploadResult) } } .runFor(shortcut.headers) { header -> header( Variables.rawPlaceholdersToResolvedValues(header.key, variablesValues), Variables.rawPlaceholdersToResolvedValues(header.value, variablesValues) ) } .runIf(shortcut.authenticationType == ShortcutAuthenticationType.BASIC) { basicAuth(requestData.username, requestData.password) } .runIf(shortcut.authenticationType == ShortcutAuthenticationType.BEARER) { bearerAuth(requestData.authToken) } .build() responseFileStorage.clear() logInfo("Starting HTTP request") client .newCall(request) .apply { continuation.invokeOnCancellation { cancel() } } .execute() .use { okHttpResponse -> logInfo("HTTP request completed") val contentFile = if (shortcut.usesResponseBody) { responseFileStorage.store(okHttpResponse) } else null val shortcutResponse = prepareResponse(requestData.url, okHttpResponse, contentFile) if (okHttpResponse.code in 200..399) { continuation.resume(shortcutResponse) } else { continuation.resumeWithException(ErrorResponse(shortcutResponse)) } } } private fun attachParameters( requestBuilder: RequestBuilder, shortcut: ShortcutModel, variables: Map<VariableKey, String>, fileUploadResult: FileUploadManager.Result?, ): RequestBuilder { var fileIndex = -1 return requestBuilder.runFor(shortcut.parameters) { parameter -> val parameterName = Variables.rawPlaceholdersToResolvedValues(parameter.key, variables) when (parameter.parameterType) { ParameterType.FILES -> { runIfNotNull(fileUploadResult) { fileIndex++ val files = it.getFiles(fileIndex) runFor(files) { file -> fileParameter( name = "$parameterName[]", fileName = parameter.fileName.ifEmpty { file.fileName }, type = file.mimeType, data = contentResolver.openInputStream(file.data)!!, length = file.fileSize, ) } } } ParameterType.IMAGE, ParameterType.FILE, -> { runIfNotNull(fileUploadResult) { fileIndex++ runIfNotNull(it.getFile(fileIndex)) { file -> fileParameter( name = parameterName, fileName = parameter.fileName.ifEmpty { file.fileName }, type = file.mimeType, data = contentResolver.openInputStream(file.data)!!, length = file.fileSize, ) } } } ParameterType.STRING -> { parameter( name = parameterName, value = Variables.rawPlaceholdersToResolvedValues(parameter.value, variables), ) } } } } companion object { private fun prepareResponse(url: String, response: Response, contentFile: Uri?) = ShortcutResponse( url = url, headers = HttpHeaders.parse(response.headers), statusCode = response.code, contentFile = contentFile, timing = response.receivedResponseAtMillis - response.sentRequestAtMillis, ) private fun determineContentType(shortcut: ShortcutModel): String? = when (shortcut.bodyType) { RequestBodyType.FORM_DATA -> FORM_MULTIPART_CONTENT_TYPE RequestBodyType.X_WWW_FORM_URLENCODE -> FORM_URLENCODE_CONTENT_TYPE else -> shortcut.contentType.takeUnlessEmpty() } } }
mit
25e03060337016aea87c3e12f50b2d32
44.471545
132
0.574557
5.931071
false
false
false
false
dreampany/framework
frame/src/main/kotlin/com/dreampany/framework/misc/Constants.kt
1
4960
package com.dreampany.framework.misc import android.content.Context import com.dreampany.framework.util.AndroidUtil import com.google.common.base.Splitter import com.google.common.collect.Iterables import java.util.concurrent.TimeUnit /** * Created by Hawladar Roman on 24/2/19. * Dreampany Ltd * [email protected] */ class Constants { companion object { fun database(name: String): String { return Iterables.getLast(Splitter.on(Sep.DOT).trimResults().split(name)) + Database.POST_FIX } fun database(name: String, type: String): String { return Iterables.getLast(Splitter.on(Sep.DOT).trimResults().split(name)) + type + Database.POST_FIX } fun lastAppId(context: Context): String = AndroidUtil.getLastApplicationId(context)!! fun more(context: Context): String = lastAppId(context) + Sep.HYPHEN + Tag.MORE fun about(context: Context): String = lastAppId(context) + Sep.HYPHEN + Tag.ABOUT fun settings(context: Context): String = lastAppId(context) + Sep.HYPHEN + Tag.SETTINGS fun license(context: Context): String = lastAppId(context) + Sep.HYPHEN + Tag.LICENSE fun launch(context: Context): String = lastAppId(context) + Sep.HYPHEN + Tag.LAUNCH fun navigation(context: Context): String = lastAppId(context) + Sep.HYPHEN + Tag.NAVIGATION fun tools(context: Context): String = lastAppId(context) + Sep.HYPHEN + Tag.TOOLS fun web(context: Context): String = lastAppId(context) + Sep.HYPHEN + Tag.WEB } object Event { const val ERROR = "error" const val APPLICATION = "application" const val ACTIVITY = "activity" const val FRAGMENT = "fragment" const val NOTIFICATION = "notification" } object Param { const val PACKAGE_NAME = "package_name" const val VERSION_CODE = "version_code" const val VERSION_NAME = "version_name" const val SCREEN = "screen" const val ERROR_MESSAGE = "error_message" const val ERROR_DETAILS = "error_details" } object Tag { const val MORE = "more" const val ABOUT = "about" const val SETTINGS = "settings" const val LICENSE = "license" const val LAUNCH = "launch" const val NAVIGATION = "navigation" const val TOOLS = "tools" const val WEB = "web" const val NOTIFY_SERVICE = "notify_service" const val MORE_APPS = "more_apps" const val RATE_US = "rate_us" } object Ad { const val KEY = "ad-pref" const val BANNER = "banner" const val INTERSTITIAL = "interstitial" const val REWARDED = "rewarded" } object Pref { const val VERSION_CODE = "version_code" const val RANK = "rank" const val LEVEL = "level" } object AdTime { const val BANNER = "time-banner" const val INTERSTITIAL = "time-interstitial" const val REWARDED = "time-rewarded" } object Sep { const val DOT = "." const val COMMA = "," const val COMMA_SPACE = ", " const val SPACE = " " const val HYPHEN = "-" } object Database { const val TYPE_FRAME = "frame" const val TYPE_TRANSLATION = "translation" const val POST_FIX = Sep.HYPHEN + "db" } object Key { const val ID = "id" const val TIME = "time" const val TYPE = "type" const val SUBTYPE = "subtype" const val STATE = "state" } object Notify { const val DEFAULT_ID = 101 const val DEFAULT_CHANNEL_ID = "default_channel_id" } object Task { const val TASK = "task" } object Retrofit { const val CONNECTION_CLOSE = "Connection:close" } object Session { val EXPIRED_TIME = TimeUnit.MINUTES.toMillis(5) } object Link { const val ID = Key.ID const val REF = "ref" const val URL = "url" } object Parser { const val PATTERN_IMAGE_TAG = "img" const val BASE_URL = "baseUrl" const val HREF = "href" const val SOURCE = "src" const val ALTERNATE = "alt" const val WIDTH = "width" const val HEIGHT = "height" } object Default { val NULL = null const val BOOLEAN = false const val CHARACTER = 0.toChar() const val INT = 0 const val LONG = 0L const val FLOAT = 0f const val DOUBLE = 0.0 const val STRING = "" } object Network { const val HTTP = "http:" const val HTTPS = "https:" } object Pattern { const val PATTERN_IMAGE = "img[src~=(?i)\\\\.(png|jpe?g|gif)]" const val PATTERN_IMAGE_URL = "^https?://(?:[a-z0-9\\-]+\\.)+[a-z0-9]{2,6}(?:/[^/#?]+)+\\.(?:jpg|gif|png)\$" val IMAGE_PATTERN = java.util.regex.Pattern.compile(PATTERN_IMAGE_URL) } }
apache-2.0
49388cb9268fd08802e362a6e43d5b28
29.435583
116
0.592742
3.927158
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/activity/VectorWebViewActivity.kt
2
4829
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.activity import android.content.Context import android.content.Intent import android.os.Build import android.webkit.WebChromeClient import android.webkit.WebView import butterknife.BindView import im.vector.R import im.vector.webview.VectorWebViewClient import im.vector.webview.WebViewMode /** * This class is responsible for managing a WebView * It does also have a loading view and a toolbar * It relies on the VectorWebViewClient * This class shouldn't be extended. To add new behaviors, you might create a new WebViewMode and a new WebViewEventListener */ class VectorWebViewActivity : VectorAppCompatActivity() { /* ========================================================================================== * UI * ========================================================================================== */ @BindView(R.id.simple_webview) lateinit var webView: WebView /* =====================================================================@===================== * Life cycle * ========================================================================================== */ override fun getLayoutRes() = R.layout.activity_vector_web_view override fun initUiAndData() { configureToolbar() waitingView = findViewById(R.id.simple_webview_loader) webView.settings.apply { // Enable Javascript javaScriptEnabled = true // Use WideViewport and Zoom out if there is no viewport defined useWideViewPort = true loadWithOverviewMode = true // Enable pinch to zoom without the zoom buttons builtInZoomControls = true // Allow use of Local Storage domStorageEnabled = true allowFileAccessFromFileURLs = true allowUniversalAccessFromFileURLs = true displayZoomControls = false } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val cookieManager = android.webkit.CookieManager.getInstance() cookieManager.setAcceptThirdPartyCookies(webView, true) } val url = intent.extras.getString(EXTRA_URL) val title = intent.extras.getString(EXTRA_TITLE, USE_TITLE_FROM_WEB_PAGE) if (title != USE_TITLE_FROM_WEB_PAGE) { setTitle(title) } val webViewMode = intent.extras.getSerializable(EXTRA_MODE) as WebViewMode val eventListener = webViewMode.eventListener(this) webView.webViewClient = VectorWebViewClient(eventListener) webView.webChromeClient = object : WebChromeClient() { override fun onReceivedTitle(view: WebView, title: String) { if (title == USE_TITLE_FROM_WEB_PAGE) { setTitle(title) } } } webView.loadUrl(url) } /* ========================================================================================== * UI event * ========================================================================================== */ override fun onBackPressed() { if (webView.canGoBack()) { webView.goBack() } else { super.onBackPressed() } } /* ========================================================================================== * Companion * ========================================================================================== */ companion object { private const val EXTRA_URL = "EXTRA_URL" private const val EXTRA_TITLE = "EXTRA_TITLE" private const val EXTRA_MODE = "EXTRA_MODE" private const val USE_TITLE_FROM_WEB_PAGE = "" fun getIntent(context: Context, url: String, title: String = USE_TITLE_FROM_WEB_PAGE, mode: WebViewMode = WebViewMode.DEFAULT): Intent { return Intent(context, VectorWebViewActivity::class.java) .apply { putExtra(EXTRA_URL, url) putExtra(EXTRA_TITLE, title) putExtra(EXTRA_MODE, mode) } } } }
apache-2.0
9ae349e52aa83bf57aa76cad7e78f09d
34.77037
124
0.529716
5.431946
false
false
false
false
MaTriXy/gradle-play-publisher-1
common/validation/src/test/kotlin/com/github/triplet/gradle/common/validation/RuntimeValidatorTest.kt
1
2268
package com.github.triplet.gradle.common.validation import org.gradle.util.GradleVersion import org.gradle.util.VersionNumber import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows class RuntimeValidatorTest { @Test fun `Gradle version below minimum throws`() { val validator = newValidator( currentGradle = GradleVersion.version("0.0.0"), minGradle = GradleVersion.version("1.0.0") ) assertThrows<IllegalStateException> { validator.validate() } } @Test fun `Gradle version at minimum succeeds`() { val validator = newValidator( currentGradle = GradleVersion.version("1.0.0"), minGradle = GradleVersion.version("1.0.0") ) validator.validate() } @Test fun `Gradle version above minimum succeeds`() { val validator = newValidator( currentGradle = GradleVersion.version("2.0.0"), minGradle = GradleVersion.version("1.0.0") ) validator.validate() } @Test fun `Agp version below minimum throws`() { val validator = newValidator( currentAgp = VersionNumber.parse("0.0.0"), minAgp = VersionNumber.parse("1.0.0") ) assertThrows<IllegalStateException> { validator.validate() } } @Test fun `Agp version at minimum succeeds`() { val validator = newValidator( currentAgp = VersionNumber.parse("1.0.0"), minAgp = VersionNumber.parse("1.0.0") ) validator.validate() } @Test fun `Agp version above minimum succeeds`() { val validator = newValidator( currentAgp = VersionNumber.parse("2.0.0"), minAgp = VersionNumber.parse("1.0.0") ) validator.validate() } private fun newValidator( currentGradle: GradleVersion = GradleVersion.version("0.0.0"), minGradle: GradleVersion = GradleVersion.version("0.0.0"), currentAgp: VersionNumber = VersionNumber.parse("0.0.0"), minAgp: VersionNumber = VersionNumber.parse("0.0.0") ) = RuntimeValidator(currentGradle, minGradle, currentAgp, minAgp) }
mit
eb04eef51b8931f6c0f94fb505494286
29.24
74
0.60097
4.303605
false
true
false
false
hazuki0x0/YuzuBrowser
module/search/src/main/java/jp/hazuki/yuzubrowser/search/model/suggest/SuggestBing.kt
1
2045
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.search.model.suggest import com.squareup.moshi.JsonReader import jp.hazuki.yuzubrowser.search.model.SearchSuggestModel import java.io.IOException import java.net.URL import java.net.URLEncoder import java.util.* class SuggestBing : ISuggest { @Throws(IOException::class) override fun getUrl(query: String): URL { return URL(SUGGEST_URL.replace("{{LANG}}", Locale.getDefault().language).replace("{{TERMS}}", URLEncoder.encode(query, "UTF-8"))) } @Throws(IOException::class) override fun getSuggestions(reader: JsonReader): MutableList<SearchSuggestModel.SuggestModel> { val list = ArrayList<SearchSuggestModel.SuggestModel>() if (reader.peek() == JsonReader.Token.BEGIN_ARRAY) { reader.beginArray() while (reader.hasNext()) { if (reader.peek() == JsonReader.Token.BEGIN_ARRAY) { reader.beginArray() while (reader.hasNext()) { list.add(SearchSuggestModel.SuggestModel(reader.nextString())) } reader.endArray() } else { reader.skipValue() } } reader.endArray() } return list } companion object { private const val SUGGEST_URL = "https://api.bing.com/osjson.aspx?FORM=OPERAS&Market={{LANG}}&Query={{TERMS}}" } }
apache-2.0
a0eb4ebfef39f8bb515ad36c5777cde1
33.661017
137
0.641076
4.416847
false
false
false
false
duftler/clouddriver
clouddriver-sql/src/main/kotlin/com/netflix/spinnaker/clouddriver/sql/TaskMapper.kt
1
3483
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.clouddriver.sql import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spinnaker.clouddriver.data.task.DefaultTaskStatus import com.netflix.spinnaker.clouddriver.data.task.SagaId import com.netflix.spinnaker.clouddriver.data.task.Status import com.netflix.spinnaker.clouddriver.data.task.Task import com.netflix.spinnaker.clouddriver.data.task.TaskState import org.slf4j.LoggerFactory import java.io.IOException import java.lang.String.format import java.sql.ResultSet class TaskMapper( private val sqlTaskRepository: SqlTaskRepository, private val mapper: ObjectMapper ) { companion object { private val log = LoggerFactory.getLogger(TaskMapper::class.java) private val SAGA_IDS_TYPE = object : TypeReference<MutableSet<SagaId>>() {} } fun map(rs: ResultSet): Collection<Task> { val tasks = mutableMapOf<String, SqlTask>() val results = mutableMapOf<String, MutableList<Any>>() val history = mutableMapOf<String, MutableList<Status>>() while (rs.next()) { when { rs.getString("owner_id") != null -> SqlTask( rs.getString("task_id"), rs.getString("owner_id"), rs.getString("request_id"), rs.getLong("created_at"), sagaIds(rs.getString("saga_ids")), sqlTaskRepository ).let { tasks[it.id] = it } rs.getString("body") != null -> { try { if (!results.containsKey(rs.getString("task_id"))) { results[rs.getString("task_id")] = mutableListOf() } results[rs.getString("task_id")]!!.add(mapper.readValue(rs.getString("body"), Map::class.java)) } catch (e: IOException) { val id = rs.getString("id") val taskId = rs.getString("task_id") throw RuntimeException( format("Failed to convert result object body to map (id: %s, taskId: %s)", id, taskId), e ) } } rs.getString("state") != null -> { if (!history.containsKey(rs.getString("task_id"))) { history[rs.getString("task_id")] = mutableListOf() } history[rs.getString("task_id")]!!.add(DefaultTaskStatus.create( rs.getString("phase"), rs.getString("status"), TaskState.valueOf(rs.getString("state")) )) } } } return tasks.values.map { task -> task.hydrateResultObjects(results.getOrDefault(task.id, mutableListOf())) task.hydrateHistory(history.getOrDefault(task.id, mutableListOf())) task } } private fun sagaIds(sagaIdsValue: String?): MutableSet<SagaId> { if (sagaIdsValue == null) { return mutableSetOf() } return mapper.readValue(sagaIdsValue, SAGA_IDS_TYPE) } }
apache-2.0
59c8be6d6875c41fcb9a2fbef76065e0
34.181818
107
0.648866
4.151371
false
false
false
false
syrop/Wiktor-Navigator
navigator/src/main/kotlin/pl/org/seva/navigator/profile/LoginActivity.kt
1
7852
/* * Copyright (C) 2017 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.navigator.profile import android.app.ProgressDialog import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.auth.api.Auth import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuth.AuthStateListener import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.GoogleAuthProvider import pl.org.seva.navigator.main.NavigatorApplication import pl.org.seva.navigator.R import pl.org.seva.navigator.main.extension.start import pl.org.seva.navigator.main.data.fb.fbWriter fun Context.loginActivity(action: String) = start(LoginActivity::class.java) { putExtra(LoginActivity.ACTION, action) } class LoginActivity : AppCompatActivity(), GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks { private lateinit var firebaseAuth: FirebaseAuth private lateinit var authStateListener: AuthStateListener private lateinit var googleApiClient: GoogleApiClient private var progressDialog: ProgressDialog? = null private var performedAction: Boolean = false private var logoutWhenReady: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(DEFAULT_WEB_CLIENT_ID) .requestEmail() .build() googleApiClient = GoogleApiClient.Builder(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .addConnectionCallbacks(this) .build() firebaseAuth = FirebaseAuth.getInstance() authStateListener = AuthStateListener { auth -> val user = auth.currentUser if (user != null) { Log.d(TAG, "onAuthStateChanged:signed_in:" + user.uid) onUserLoggedIn(user) } else { Log.d(TAG, "onAuthStateChanged:signed_out") onUserLoggedOut() } } firebaseAuth.addAuthStateListener(authStateListener) when (intent.getStringExtra(ACTION)) { LOGOUT -> { logout() finish() return } LOGIN -> { login() } } } private fun login() { val signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient) startActivityForResult(signInIntent, SIGN_IN_REQUEST_ID) } private fun logout() { finishWhenStateChanges() logoutWhenReady = true firebaseAuth.signOut() (application as NavigatorApplication).logout() googleApiClient.connect() finish() } private fun onUserLoggedIn(user: FirebaseUser) { fbWriter login user (application as NavigatorApplication).login(user) if (performedAction) { finish() } } private fun onUserLoggedOut() { if (performedAction) { finish() } } public override fun onStop() { super.onStop() hideProgressDialog() } override fun onDestroy() { super.onDestroy() firebaseAuth.removeAuthStateListener(authStateListener) } override fun onBackPressed() { moveTaskToBack(true) finish() } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == SIGN_IN_REQUEST_ID) { finishWhenStateChanges() val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data) if (result?.isSuccess == true) { // Google Sign In was successful, authenticate with Firebase val account = checkNotNull(result.signInAccount) firebaseAuthWithGoogle(account) } else { signInFailed() } } } private fun finishWhenStateChanges() { performedAction = true } private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) { Log.d(TAG, "firebaseAuthWithGoogle:" + checkNotNull(acct.id)) showProgressDialog() val credential = GoogleAuthProvider.getCredential(acct.idToken, null) firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this) { Log.d(TAG, "signInWithCredential:onComplete:" + it.isSuccessful) hideProgressDialog() // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!it.isSuccessful) { signInFailed() } } } private fun signInFailed(message: String = "") { if (!message.isBlank()) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, R.string.login_authentication_failed, Toast.LENGTH_SHORT).show() } finish() } private fun showProgressDialog() { progressDialog = ProgressDialog(this) checkNotNull(progressDialog).setMessage(getString(R.string.login_loading)) checkNotNull(progressDialog).isIndeterminate = true checkNotNull(progressDialog).show() } private fun hideProgressDialog() { if (progressDialog != null && checkNotNull(progressDialog).isShowing) { checkNotNull(progressDialog).dismiss() } } override fun onConnectionFailed(connectionResult: ConnectionResult) { Log.d(TAG, "onConnectionFailed:$connectionResult") Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show() } override fun onConnected(bundle: Bundle?) { if (logoutWhenReady) { Auth.GoogleSignInApi.signOut(googleApiClient) } } override fun onConnectionSuspended(i: Int) = Unit companion object { const val DEFAULT_WEB_CLIENT_ID = "267180459782-548rckf296jcchkp8id9on17v57trcrf.apps.googleusercontent.com" const val ACTION = "action" const val LOGIN = "login" const val LOGOUT = "logout" private val TAG = LoginActivity::class.java.simpleName private const val SIGN_IN_REQUEST_ID = 9001 } }
gpl-3.0
e948b03abba5b01fa9ed4589d796ee48
32.271186
116
0.652318
4.883085
false
false
false
false
seventhroot/elysium
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/hide/CharacterHideRaceCommand.kt
1
2691
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.command.character.hide import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player /** * Character hide race command. * Hides character's race. */ class CharacterHideRaceCommand(private val plugin: RPKCharactersBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender is Player) { if (sender.hasPermission("rpkit.characters.command.character.hide.race")) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { character.isRaceHidden = true characterProvider.updateCharacter(character) sender.sendMessage(plugin.messages["character-hide-race-valid"]) character.showCharacterCard(minecraftProfile) } else { sender.sendMessage(plugin.messages["no-character"]) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["no-permission-character-hide-race"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } return true } }
apache-2.0
c76f2da4ad525722878a0de3a313c0cf
43.131148
128
0.673727
5.155172
false
false
false
false
Yorxxx/played-next-kotlin
app/src/main/java/com/piticlistudio/playednext/data/repository/datasource/room/company/RoomCompanyService.kt
1
1326
package com.piticlistudio.playednext.data.repository.datasource.room.company import android.arch.persistence.room.* import com.piticlistudio.playednext.data.entity.room.RoomCompany import com.piticlistudio.playednext.data.entity.room.RoomGameDeveloper import com.piticlistudio.playednext.data.entity.room.RoomGamePublisher import io.reactivex.Flowable import io.reactivex.Single @Dao interface RoomCompanyService { @Query("select * from company where id = :id") fun find(id: Long): Single<RoomCompany> @Insert(onConflict = OnConflictStrategy.IGNORE) fun insert(data: RoomCompany): Long @Query("select company.* from company " + "LEFT JOIN game_developer ON company.id = game_developer.companyId " + "WHERE game_developer.gameId = :id") fun findDeveloperForGame(id: Int): Flowable<List<RoomCompany>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertGameDeveloper(data: RoomGameDeveloper): Long @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertGamePublisher(data: RoomGamePublisher): Long @Query("select company.* from company " + "LEFT JOIN game_publisher ON company.id = game_publisher.companyId " + "WHERE game_publisher.gameId = :id") fun findPublishersForGame(id: Int): Flowable<List<RoomCompany>> }
mit
0578db0a6c41edfc17dd331901cee0a8
38.029412
82
0.744344
4.196203
false
false
false
false
Szewek/Minecraft-Flux
src/main/java/szewek/mcflux/compat/top/MCFluxTOPProvider.kt
1
3137
package szewek.mcflux.compat.top import mcjty.theoneprobe.api.* import net.minecraft.block.state.IBlockState import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.util.EnumFacing import net.minecraft.util.text.TextComponentTranslation import net.minecraft.world.World import szewek.fl.FLU import szewek.fl.energy.IEnergy import szewek.mcflux.MCFlux import szewek.mcflux.R import szewek.mcflux.U import szewek.mcflux.blocks.BlockEnergyMachine import szewek.mcflux.blocks.BlockWET import szewek.mcflux.config.MCFluxConfig import szewek.mcflux.fluxable.FluxableCapabilities import szewek.mcflux.fluxcompat.FluxCompat class MCFluxTOPProvider : IProbeInfoProvider, IProbeInfoEntityProvider { override fun addProbeEntityInfo(mode: ProbeMode, info: IProbeInfo, p: EntityPlayer, w: World, e: Entity, data: IProbeHitEntityData) { val ie = FLU.getEnergySafely(e, EnumFacing.UP) // <- SET TO null if (ie != null) { val en = ie.energy val ec = ie.energyCapacity if (ec == 1L) info.text(compat.unformattedText) else info.text(U.formatMF(ie)).progress(en, ec) } } override fun getID(): String { return ID } override fun addProbeInfo(mode: ProbeMode, info: IProbeInfo, p: EntityPlayer, w: World, ibs: IBlockState, data: IProbeHitData) { val bp = data.pos val b = ibs.block if (b === MCFlux.Resources.WET) { val m = ibs.getValue(BlockWET.MODE) info.text((if (m == 0) wetMode0 else wetMode1).unformattedText) } else if (b === MCFlux.Resources.ENERGY_MACHINE) { val `var` = ibs.getValue<BlockEnergyMachine.Variant>(BlockEnergyMachine.VARIANT) if (`var` == BlockEnergyMachine.Variant.ENERGY_DIST || `var` == BlockEnergyMachine.Variant.CHUNK_CHARGER) { val wce = w.getCapability(FluxableCapabilities.CAP_WCE, null) if (wce != null) displayMF(info, wce.getEnergyChunk(bp.x, bp.y, bp.z), p.isSneaking) } } else { val te = w.getTileEntity(bp) if (te != null) displayMF(info, FLU.getEnergySafely(te, data.sideHit), p.isSneaking) } } private fun displayMF(info: IProbeInfo, ie: IEnergy?, sneak: Boolean) { if (ie == null) return val en = ie.energy val ec = ie.energyCapacity val fcc = ie is FluxCompat.Convert if (MCFluxConfig.SHOW_FLUXCOMPAT || !fcc) info.text(U.formatMF(ie)).progress(en, ec, getFStyle(info)) if (sneak && fcc) info.text(mfConvert.unformattedText + ' '.toString() + (ie as FluxCompat.Convert).energyType) } companion object { private val compat = TextComponentTranslation("mcflux.mfcompatible") private val wetMode0 = TextComponentTranslation("mcflux.wet.mode0") private val wetMode1 = TextComponentTranslation("mcflux.wet.mode1") private val mfConvert = TextComponentTranslation("mcflux.convert") private val ID = R.MF_NAME + ":top_info" private var fStyle: IProgressStyle? = null private fun getFStyle(info: IProbeInfo): IProgressStyle { if (fStyle == null) fStyle = info.defaultProgressStyle().borderColor(-0x3f3f40).filledColor(-0x23e7e2).alternateFilledColor(-0x23e7e2).backgroundColor(-0xb3f7f2).height(6).showText(false) return fStyle!! } } }
mit
a506a4ade7e2038ccf138af360eb7c2b
35.905882
171
0.740835
3.130739
false
false
false
false
AlmasB/FXGL
fxgl-io/src/main/kotlin/com/almasb/fxgl/profile/SaveFile.kt
1
2458
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.profile import com.almasb.fxgl.core.serialization.Bundle import java.io.Serializable import java.time.LocalDateTime /** * @author Almas Baimagambetov ([email protected]) */ interface SaveLoadHandler { /** * Called to save game state into [data]. * This does not perform any IO. */ fun onSave(data: DataFile) /** * Called to load game state from [data]. * This does not perform any IO. */ fun onLoad(data: DataFile) } /** * Data structure for save files. * The actual data saved is in [DataFile]. */ data class SaveFile @JvmOverloads constructor( /** * Save file name, for example "file1.sav", or "myprofile/file1.sav". */ val name: String, /** * Date and time of the save. * By default, it is the moment this save file object was created. */ val dateTime: LocalDateTime = LocalDateTime.now(), /** * The save data. */ val data: DataFile = DataFile() ) : Serializable { /** * A comparator that sorts save files in chronological order with recent files first. */ companion object RECENT_FIRST : Comparator<SaveFile> { private val serialVersionUid: Long = 1 override fun compare(o1: SaveFile, o2: SaveFile) = o2.dateTime.compareTo(o1.dateTime) } override fun toString() = "SaveFile($name)" } /** * Carries the data that needs to be saved (serialized) using [Bundle]. */ class DataFile : Serializable { companion object { private val serialVersionUid: Long = 2 } /** * K - bundle name, V - bundle. */ private val bundles = hashMapOf<String, Bundle>() /** * Stores the given [bundle]. Bundles with same name are not allowed. */ fun putBundle(bundle: Bundle) { require(!bundles.containsKey(bundle.name)) { "Bundle \"" + bundle.name + "\" already exists!" } bundles[bundle.name] = bundle } /** * @return bundle by [name] or throws IAE if the bundle does not exist */ fun getBundle(name: String): Bundle { return bundles[name] ?: throw IllegalArgumentException("Bundle \"$name\" doesn't exist!") } override fun toString() = "DataFile($bundles)" }
mit
90850765147c6950995e46cefd18045f
23.107843
97
0.609439
4.138047
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/listener/InventoryCloseListener.kt
1
2724
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.economy.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.economy.bukkit.currency.RPKCurrencyName import com.rpkit.economy.bukkit.currency.RPKCurrencyService import com.rpkit.economy.bukkit.economy.RPKEconomyService import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.inventory.InventoryCloseEvent /** * Inventory close listener for wallets. */ class InventoryCloseListener : Listener { @EventHandler fun onInventoryClose(event: InventoryCloseEvent) { if (!event.view.title.lowercase().contains("wallet")) return val bukkitPlayer = event.player if (bukkitPlayer !is Player) return val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val characterService = Services[RPKCharacterService::class.java] ?: return val currencyService = Services[RPKCurrencyService::class.java] ?: return val economyService = Services[RPKEconomyService::class.java] ?: return val currency = currencyService.getCurrency(RPKCurrencyName(event.view.title.substringAfterLast("[").substringBeforeLast("]"))) ?: return val amount = event.inventory.contents .filter { item -> item != null && item.isSimilar(currency.item) } .sumOf { item -> item.amount } event.inventory.contents .filter { item -> item != null && !item.isSimilar(currency.item) } .forEach { item -> bukkitPlayer.world.dropItem(bukkitPlayer.location, item) } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer) ?: return val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return economyService.setBalance(character, currency, amount) } }
apache-2.0
f0ce9499b0b4009b7e2689322c05117f
42.238095
134
0.710352
4.821239
false
false
false
false
xfmax/BasePedo
app/src/main/java/com/base/basepedo/utils/CountDownTimer.kt
1
2855
package com.base.basepedo.utils import android.os.Handler import android.os.Message import android.os.SystemClock abstract class CountDownTimer /** * @param millisInFuture The number of millis in the future from the call * to [.start] until the countdown is done and [.onFinish] * is called. * @param countDownInterval The interval along the way to receive * [.onTick] callbacks. */( /** * Millis since epoch when alarm should stop. */ private val mMillisInFuture: Long, /** * The interval in millis that the user receives callbacks */ private val mCountdownInterval: Long) { private var mStopTimeInFuture: Long = 0 private var mCancelled = false /** * Cancel the countdown. * * Do not call it from inside CountDownTimer threads */ fun cancel() { mHandler.removeMessages(MSG) mCancelled = true } /** * Start the countdown. */ @Synchronized fun start(): CountDownTimer { if (mMillisInFuture <= 0) { onFinish() return this } mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture mHandler.sendMessage(mHandler.obtainMessage(MSG)) mCancelled = false return this } /** * Callback fired on regular interval. * @param millisUntilFinished The amount of time until finished. */ abstract fun onTick(millisUntilFinished: Long) /** * Callback fired when the time is up. */ abstract fun onFinish() // handles counting down private val mHandler: Handler = object : Handler() { override fun handleMessage(msg: Message) { synchronized(this@CountDownTimer) { val millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime() if (millisLeft <= 0) { onFinish() } else if (millisLeft < mCountdownInterval) { // no tick, just delay until done sendMessageDelayed(obtainMessage(MSG), millisLeft) } else { val lastTickStart = SystemClock.elapsedRealtime() onTick(millisLeft) // take into account user's onTick taking time to execute var delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime() // special case: user's onTick took more than interval to // complete, skip to next interval while (delay < 0) delay += mCountdownInterval if (!mCancelled) { sendMessageDelayed(obtainMessage(MSG), delay) }else{ } } } } } companion object { private const val MSG = 1 } }
apache-2.0
5870fb4142382883f8c8096c2f32d100
28.43299
98
0.579335
5.190909
false
false
false
false
darakeon/dfm
android/App/src/main/kotlin/com/darakeon/dfm/moves/MovesService.kt
1
798
package com.darakeon.dfm.moves import android.content.Context import com.darakeon.dfm.lib.api.Api import com.darakeon.dfm.lib.api.entities.moves.Move import com.darakeon.dfm.offlineFallback.Service import kotlin.reflect.KClass class MovesService: Service<MovesService, Move>(MovesService::class, Move::class) { override fun callApi( api: Api<*>, obj: Move, success: () -> Unit ) = api.saveMove(obj, success) companion object { private val typeObj: KClass<Move> get() = Move::class private val typeService: KClass<MovesService> get() = MovesService::class fun manager(context: Context) = manager(context, typeObj) fun start(context: Context, move: Move) = start(context, typeService, move) fun start(context: Context) = start(context, typeService, typeObj) } }
gpl-3.0
1c81a7f73a23d89cf71d3d036a2f4b6c
25.6
83
0.736842
3.338912
false
false
false
false
r-artworks/game-seed
android/src/com/rartworks/engine/android/services/integrations/inAppBilling/InAppBillingIntegration.kt
1
3652
package com.rartworks.engine.android.services.integrations.inAppBilling import android.app.Activity import android.content.Intent import com.badlogic.gdx.Gdx import com.rartworks.engine.android.services.integrations.Integration import com.rartworks.engine.android.services.util.IabHelper import com.rartworks.engine.android.utils.isDebuggable import com.rartworks.engine.android.utils.showError import com.rartworks.engine.apis.InAppBillingServices import java.util.* /** * Manages the integration with In App Billing. */ class InAppBillingIntegration(app: Activity, private val billingKey: String, private val availablePurchases: List<Purchase>) : Integration(app), InAppBillingServices { var iabHelper: IabHelper? = null companion object { private val RC_PURCHASE = 10001 } /** * Starts a [Purchase] by [sku]. */ override fun startPurchase(sku: String) { val requestedPurchase = this.findAvailablePurchaseBySku(sku) if (requestedPurchase.acceptIfDebug && this.app.isDebuggable) return requestedPurchase.accept() val purchaseFinishedListener = IabHelper.OnIabPurchaseFinishedListener { result, purchase -> if (purchase == null || this.iabHelper == null) return@OnIabPurchaseFinishedListener if (result.isFailure) { Gdx.app.log("[!] InAppBilling", "Error purchasing: " + result.message) this.app.showError("PurchaseFailureReason(" + result.message + ")") return@OnIabPurchaseFinishedListener } Gdx.app.log("[!] InAppBilling", "Purchase finished: " + purchase.sku) if (purchase.sku == requestedPurchase.sku) requestedPurchase.accept() } this.iabHelper!!.flagEndAsync() // hack for: Can't start async operation (refresh inventory) because another async operation(launchPurchaseFlow) is in progress this.iabHelper!!.launchPurchaseFlow( this.app, requestedPurchase.sku, RC_PURCHASE, purchaseFinishedListener, "HANDLE_PAYLOADS" ) } /** * Gets the inventory and accept the proper [Purchase]s. */ private fun checkPayments() { this.iabHelper!!.queryInventoryAsync(false, IabHelper.QueryInventoryFinishedListener { result, inventory -> if (this.iabHelper == null) return@QueryInventoryFinishedListener if (result.isFailure) { Gdx.app.log("[!] InAppBilling", "Can't get the inventory: " + result.message) return@QueryInventoryFinishedListener } Gdx.app.log("[!] InAppBilling", "The inventory is here!") this.availablePurchases .filter { inventory.getPurchase(it.sku) != null } .forEach { it.accept() } }) } /** * Returns an available [Purchase] by its [sku]. */ private fun findAvailablePurchaseBySku(sku: String): Purchase { try { return this.availablePurchases.single { it.sku == sku } } catch(e: NoSuchElementException) { throw RuntimeException("The sku ${sku} was not found.") } } // ------- // Events: // ------- /** * Creates the In App Billing helper. */ override fun onCreated() { this.iabHelper = IabHelper(this.app, this.billingKey) this.iabHelper!!.startSetup { result -> if (!result.isSuccess) Gdx.app.log("[!] InAppBilling", "Problem setting up In-app Billing: " + result) else { Gdx.app.log("[!] InAppBilling", "In-app Billing is fully set up: " + result) this.checkPayments() } } } override fun onDestroy() { try { if (this.iabHelper != null) this.iabHelper!!.dispose() } catch (e: Exception) { // yes, the IabHelper has bugs } this.iabHelper = null } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (this.iabHelper != null) this.iabHelper!!.handleActivityResult(requestCode, resultCode, data) } }
mit
6c64062c03fef5ee81bf70d5e7f1286d
29.433333
167
0.718784
3.659319
false
false
false
false
JayNewstrom/Concrete
concrete/src/main/java/com/jaynewstrom/concrete/ConcreteWall.kt
1
5062
package com.jaynewstrom.concrete import android.content.Context class ConcreteWall<out C> internal constructor( private val parentWall: ConcreteWall<*>?, private val block: ConcreteBlock<C> ) { private var destroyed: Boolean = false private val childrenWalls: MutableMap<String, ConcreteWall<*>> = LinkedHashMap() /** * Get the component associated with the wall. */ val component: C = block.createComponent() private val destructionActions: MutableSet<ConcreteWallDestructionAction<C>> = LinkedHashSet() /** * If a wall identified by the blocks name exists as a child, it will be returned. * If it doesn't exist it will be created, cached as a child, the initialization action will run, then the wall * will be returned. */ @JvmOverloads fun <ChildComponent> stack( block: ConcreteBlock<ChildComponent>, initializationAction: ((wall: ConcreteWall<ChildComponent>) -> Unit)? = null ): ConcreteWall<ChildComponent> { if (destroyed) { throw IllegalStateException("Concrete wall has been destroyed.") } @Suppress("UNCHECKED_CAST") val existingWall = childrenWalls[block.name()] as ConcreteWall<ChildComponent>? return if (existingWall != null) { existingWall } else { val childWall = createAndCacheChildWall(block) initializationAction?.invoke(childWall) childWall } } private fun <ChildComponent> createAndCacheChildWall( block: ConcreteBlock<ChildComponent> ): ConcreteWall<ChildComponent> { val wall = ConcreteWall(this, block) childrenWalls[block.name()] = wall return wall } /** * Marks this wall as destroyed. Destroying a wall destroys all of it's children, and removes it from its parent. */ fun destroy() { if (!destroyed) { val component = component destroyed = true if (childrenWalls.isNotEmpty()) { // We need to copy the collection, so we can iterate over all values and destroy them. // Calling destroy on the child, will remove it from our model, which is why we need the copy. for (child in ArrayList(childrenWalls.values)) { child.destroy() } } parentWall?.removeChildWall(this) for (destructionAction in destructionActions) { destructionAction(component) } } } private fun removeChildWall(wall: ConcreteWall<*>) { childrenWalls.remove(wall.block.name()) } /** * Creates a new Context based on the given base context and this wall. */ fun createContext(baseContext: Context): Context { if (destroyed) { throw IllegalStateException("Concrete wall has been destroyed.") } return ConcreteWallContext(baseContext, this) } /** * Add a [destructionAction] to the wall, to be called exactly once when the wall is destroyed. */ fun addDestructionAction(destructionAction: (component: C) -> Unit) { if (destroyed) { throw IllegalStateException("Concrete wall has been destroyed.") } destructionActions.add(destructionAction) } /** * Remove a [destructionAction] that may or may not have been previously added. */ fun removeDestructionAction(destructionAction: (component: C) -> Unit) { if (destroyed) { throw IllegalStateException("Concrete wall has been destroyed.") } destructionActions.remove(destructionAction) } /** * Returns this walls component if it implements the given type, or looks up the tree, into the parent walls to find * one that implements the given type. */ fun <T> componentOfTypeIncludingParents(type: Class<T>): T { return havingComponentTypeIncludingParents(type).component } /** * Returns this wall if its associated component implements the given type, or looks up the tree, into the parent * walls to find one that has a component that implements the given type. */ @Suppress("UNCHECKED_CAST") // Guarded by isInstance checks. fun <T> havingComponentTypeIncludingParents(type: Class<T>): ConcreteWall<T> { val component = component if (type.isInstance(component)) { return this as ConcreteWall<T> } var parentWall = parentWall while (parentWall != null) { val parentComponent = parentWall.component if (type.isInstance(parentComponent)) { return parentWall as ConcreteWall<T> } parentWall = parentWall.parentWall } val exceptionMessage = "context is not associated with a wall having a component implementing $type" throw IllegalArgumentException(exceptionMessage) } } private typealias ConcreteWallDestructionAction<C> = (component: C) -> Unit
apache-2.0
04c2ad0097befa08191c35f018dd0862
35.417266
120
0.640063
4.890821
false
false
false
false
vanniktech/Emoji
emoji/src/commonMain/kotlin/com/vanniktech/emoji/Emojis.kt
1
1597
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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("Emojis") package com.vanniktech.emoji private val SPACE_REMOVAL = Regex("[\\s]") /** Returns true when the string contains only emojis. Note that whitespace will be filtered out. */ fun CharSequence?.isOnlyEmojis(): Boolean { if (this != null && this.isNotEmpty()) { EmojiManager.verifyInstalled() val inputWithoutSpaces = replace(SPACE_REMOVAL, "") return EmojiManager.emojiRepetitivePattern!! .matches(inputWithoutSpaces) } return false } /** Returns the emojis that were found in the given text. */ fun CharSequence?.emojis(): List<EmojiRange> = EmojiManager.findAllEmojis(this) /** Returns the number of all emojis that were found in the given text. */ fun CharSequence?.emojisCount() = emojis().size /** Returns a class that contains all of the emoji information that was found in the given text. */ fun CharSequence?.emojiInformation(): EmojiInformation = EmojiInformation(isOnlyEmojis(), emojis())
apache-2.0
2e5d6bd07024140c461c664b3ebcf444
37.902439
100
0.737304
4.299191
false
false
false
false
wireapp/wire-android
app/src/main/kotlin/com/waz/zclient/core/network/di/NetworkModule.kt
1
4935
@file:Suppress("MatchingDeclarationName") package com.waz.zclient.core.network.di import com.waz.zclient.BuildConfig import com.waz.zclient.KotlinServices import com.waz.zclient.core.backend.BackendItem import com.waz.zclient.core.backend.datasources.remote.BackendApi import com.waz.zclient.core.network.NetworkClient import com.waz.zclient.core.network.NetworkHandler import com.waz.zclient.core.network.RetrofitClient import com.waz.zclient.core.network.accesstoken.AccessTokenAuthenticator import com.waz.zclient.core.network.accesstoken.AccessTokenInterceptor import com.waz.zclient.core.network.accesstoken.AccessTokenLocalDataSource import com.waz.zclient.core.network.accesstoken.AccessTokenMapper import com.waz.zclient.core.network.accesstoken.AccessTokenRemoteDataSource import com.waz.zclient.core.network.accesstoken.AccessTokenRepository import com.waz.zclient.core.network.accesstoken.RefreshTokenMapper import com.waz.zclient.core.network.api.token.TokenApi import com.waz.zclient.core.network.api.token.TokenService import com.waz.zclient.core.network.backend.CustomBackendInterceptor import com.waz.zclient.core.network.connection.ConnectionSpecsFactory import com.waz.zclient.core.network.di.NetworkDependencyProvider.createHttpClient import com.waz.zclient.core.network.di.NetworkDependencyProvider.createHttpClientForToken import com.waz.zclient.core.network.di.NetworkDependencyProvider.retrofit import com.waz.zclient.core.network.pinning.CertificatePinnerFactory import com.waz.zclient.core.network.useragent.UserAgentInterceptor import com.waz.zclient.storage.db.GlobalDatabase import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level import org.koin.android.ext.koin.androidContext import org.koin.core.module.Module import org.koin.core.qualifier.named import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object NetworkDependencyProvider { fun retrofit( okHttpClient: OkHttpClient, backendItem: BackendItem ): Retrofit = Retrofit.Builder() .baseUrl(backendItem.baseUrl) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build() @Suppress("LongParameterList") fun createHttpClient( accessTokenInterceptor: AccessTokenInterceptor, accessTokenAuthenticator: AccessTokenAuthenticator, userAgentInterceptor: UserAgentInterceptor, customBackendInterceptor: CustomBackendInterceptor, backendItem: BackendItem ): OkHttpClient = defaultHttpClient(backendItem, userAgentInterceptor) .addInterceptor(accessTokenInterceptor) .addInterceptor(customBackendInterceptor) .authenticator(accessTokenAuthenticator) .build() fun createHttpClientForToken( userAgentInterceptor: UserAgentInterceptor, backendItem: BackendItem ): OkHttpClient = defaultHttpClient(backendItem, userAgentInterceptor) .build() private fun defaultHttpClient( backendItem: BackendItem, userAgentInterceptor: UserAgentInterceptor ): OkHttpClient.Builder = OkHttpClient.Builder() .certificatePinner(CertificatePinnerFactory.create(backendItem.certificatePin())) .connectionSpecs(ConnectionSpecsFactory.create()) .addInterceptor(userAgentInterceptor) .proxy(KotlinServices.httpProxy) .addLoggingInterceptor() private fun OkHttpClient.Builder.addLoggingInterceptor() = this.apply { if (BuildConfig.DEBUG) { addInterceptor(HttpLoggingInterceptor().setLevel(Level.BODY)) } } } val networkModule: Module = module { single { NetworkHandler(androidContext()) } single { createHttpClient(get(), get(), get(), get(), get()) } single { retrofit(get(), get()) } single { AccessTokenRemoteDataSource(get()) } single { AccessTokenLocalDataSource(get(), get<GlobalDatabase>().activeAccountsDao()) } single { AccessTokenMapper() } single { RefreshTokenMapper() } single { UserAgentInterceptor() } single { CustomBackendInterceptor(get()) } single { AccessTokenRepository(get(), get(), get(), get()) } single { AccessTokenAuthenticator(get(), get()) } single { AccessTokenInterceptor(get()) } single<NetworkClient> { RetrofitClient(get()) } //Token manipulation val networkClientForToken = "NETWORK_CLIENT_FOR_TOKEN" single<NetworkClient>(named(networkClientForToken)) { RetrofitClient(retrofit(createHttpClientForToken(get(), get()), get())) } single { get<NetworkClient>(named(networkClientForToken)).create(TokenApi::class.java) } single { get<NetworkClient>(named(networkClientForToken)).create(BackendApi::class.java) } single { TokenService(get(), get()) } }
gpl-3.0
848046e4310007495b8f49774293fe37
42.672566
94
0.759271
4.691065
false
false
false
false
Ph1b/MaterialAudiobookPlayer
common/src/main/kotlin/voice/common/conductor/ViewBindingController.kt
1
1198
package voice.common.conductor import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewbinding.ViewBinding typealias InflateBinding <B> = (LayoutInflater, ViewGroup?, Boolean) -> B abstract class ViewBindingController<B : ViewBinding>( args: Bundle = Bundle(), private val inflateBinding: InflateBinding<B> ) : BaseController(args) { constructor(inflateBinding: InflateBinding<B>) : this(Bundle(), inflateBinding) private var _binding: B? = null val binding: B get() = _binding ?: error("No binding present.") final override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { return inflateBinding(inflater, container, false) .also { _binding = it it.onBindingCreated() } .root } final override fun onDestroyView(view: View) { super.onDestroyView(view) onDestroyView() _binding = null } open fun onDestroyView() {} open fun B.onBindingCreated() {} final override fun onAttach(view: View) { super.onAttach(view) binding.onAttach() } open fun B.onAttach() {} }
lgpl-3.0
aab005b8fd199b21770508c075f7f5e7
22.96
81
0.701169
4.248227
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/smartspace/BcSmartspaceView.kt
1
5998
package app.lawnchair.smartspace import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Context import android.util.AttributeSet import android.view.View import android.view.View.MeasureSpec.EXACTLY import android.view.View.MeasureSpec.makeMeasureSpec import android.view.ViewGroup import android.widget.FrameLayout import androidx.viewpager.widget.ViewPager import app.lawnchair.smartspace.model.SmartspaceTarget import app.lawnchair.smartspace.provider.SmartspaceProvider import app.lawnchair.util.repeatOnAttached import com.android.launcher3.R import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlin.math.roundToInt class BcSmartspaceView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, var previewMode: Boolean = false ) : FrameLayout(context, attrs) { private val provider = SmartspaceProvider.INSTANCE.get(context) private lateinit var viewPager: ViewPager private lateinit var indicator: PageIndicator private val adapter = CardPagerAdapter(context) private var scrollState = ViewPager.SCROLL_STATE_IDLE private var pendingTargets: List<SmartspaceTarget>? = null private var runningAnimation: Animator? = null override fun onFinishInflate() { super.onFinishInflate() viewPager = findViewById(R.id.smartspace_card_pager) viewPager.isSaveEnabled = false indicator = findViewById(R.id.smartspace_page_indicator) viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { indicator.setPageOffset(position, positionOffset) } override fun onPageSelected(position: Int) { } override fun onPageScrollStateChanged(state: Int) { scrollState = state if (state == 0) { pendingTargets?.let { pendingTargets = null onSmartspaceTargetsUpdate(it) } } } }) val targets = if (previewMode) provider.previewTargets else provider.targets repeatOnAttached { viewPager.adapter = adapter targets .onEach(::onSmartspaceTargetsUpdate) .launchIn(this) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val height = MeasureSpec.getSize(heightMeasureSpec) val smartspaceHeight = context.resources.getDimensionPixelSize(R.dimen.enhanced_smartspace_height) if (height <= 0 || height >= smartspaceHeight) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) scaleX = 1f scaleY = 1f return } val scale = height.toFloat() / smartspaceHeight.toFloat() val width = (MeasureSpec.getSize(widthMeasureSpec).toFloat() / scale).roundToInt() super.onMeasure( makeMeasureSpec(width, EXACTLY), makeMeasureSpec(smartspaceHeight, EXACTLY) ) scaleX = scale scaleY = scale pivotX = 0f pivotY = smartspaceHeight.toFloat() / 2f } override fun setOnLongClickListener(l: OnLongClickListener?) { viewPager.setOnLongClickListener(l) } private fun onSmartspaceTargetsUpdate(targets: List<SmartspaceTarget>) { if (adapter.count > 1 && scrollState != ViewPager.SCROLL_STATE_IDLE) { pendingTargets = targets return } val sortedTargets = targets.sortedByDescending { it.score }.toMutableList() val isRtl = layoutDirection == LAYOUT_DIRECTION_RTL val currentItem = viewPager.currentItem val index = if (isRtl) adapter.count - currentItem else currentItem if (isRtl) { sortedTargets.reverse() } val oldCard = adapter.getCardAtPosition(currentItem) adapter.setTargets(sortedTargets) val count = adapter.count if (isRtl) { viewPager.setCurrentItem((count - index).coerceIn(0 until count), false) } indicator.setNumPages(targets.size) oldCard?.let { animateSmartspaceUpdate(it) } adapter.notifyDataSetChanged() } private fun animateSmartspaceUpdate(oldCard: BcSmartspaceCard) { if (runningAnimation != null || oldCard.parent != null) return val animParent = viewPager.parent as ViewGroup oldCard.measure(makeMeasureSpec(viewPager.width, EXACTLY), makeMeasureSpec(viewPager.height, EXACTLY)) oldCard.layout(viewPager.left, viewPager.top, viewPager.right, viewPager.bottom) val shift = resources.getDimension(R.dimen.enhanced_smartspace_dismiss_margin) val animator = AnimatorSet() animator.play( ObjectAnimator.ofFloat( oldCard, View.TRANSLATION_Y, 0f, (-height).toFloat() - shift ) ) animator.play(ObjectAnimator.ofFloat(oldCard, View.ALPHA, 1f, 0f)) animator.play( ObjectAnimator.ofFloat( viewPager, View.TRANSLATION_Y, height.toFloat() + shift, 0f ) ) animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { animParent.overlay.add(oldCard) } override fun onAnimationEnd(animation: Animator) { animParent.overlay.remove(oldCard) runningAnimation = null } }) runningAnimation = animator animator.start() } }
gpl-3.0
66bf39db3e262c7ff4d1d7038558b9fa
35.351515
110
0.642881
5.220191
false
false
false
false
intrigus/chemie
core/src/main/kotlin/de/intrigus/chem/Reaction.kt
1
1393
/*Copyright 2015 Simon Gerst 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 de.intrigus.chem import java.util.* class Reaction { public var leftSide: MutableList<Term> = ArrayList() public val rightSide: MutableList<Term> = ArrayList() public fun addTermToRightSide(term: Term) { rightSide.add(term) } public fun addTermToLeftSide(term: Term) { leftSide.add(term) } override fun toString(): String { return "Leftside: $leftSide, Rightside: $rightSide" } /** * @return return the standard reaction enthalpy of this reaction, if data is available */ fun getEnthalpy(): Float { var productEnthalpy: Float = 0f var eductEnthalpy: Float = 0f rightSide.forEach { productEnthalpy += it.enthalpy } leftSide.forEach { eductEnthalpy += it.enthalpy } return productEnthalpy - eductEnthalpy } }
apache-2.0
53cb845cfc61c92d2b8dffdaf6337478
28.659574
91
0.707107
3.946176
false
false
false
false
albertoruibal/karballo
karballo-jvm/src/test/kotlin/karballo/BasicEloTest.kt
1
6587
package karballo import karballo.book.FileBook import karballo.search.SearchEngine import karballo.search.SearchParameters import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.experimental.categories.Category /** * Estimate program ELO, from: * http://www.chessmaniac.com/ELORating/ELO_Chess_Rating.shtml */ class BasicEloTest { lateinit internal var config: Config lateinit internal var search: SearchEngine @Before //@Throws(Exception::class) fun setUp() { config = Config() config.book = FileBook("/book_small.bin") search = SearchEngine(config) } @Test @Category(SlowTest::class) fun testElo() { var elo1 = 1000 val move1 = processPosition("r1b3k1/6p1/P1n1pr1p/q1p5/1b1P4/2N2N2/PP1QBPPP/R3K2R b") if ("f6f3" == move1) { elo1 = 2600 } if ("c5d4" == move1) { elo1 = 1900 } if ("c6d4" == move1) { elo1 = 1900 } if ("b4c3" == move1) { elo1 = 1400 } if ("c8a6" == move1) { elo1 = 1500 } if ("f6g6" == move1) { elo1 = 1400 } if ("e6e5" == move1) { elo1 = 1200 } if ("c8d7" == move1) { elo1 = 1600 } println(move1 + " Elo1 = " + elo1) var elo2 = 1000 val move2 = processPosition("2nq1nk1/5p1p/4p1pQ/pb1pP1NP/1p1P2P1/1P4N1/P4PB1/6K1 w") if ("g2e4" == move2) { elo2 = 2600 } if ("g5h7" == move2) { elo2 = 1950 } if ("h5g6" == move2) { elo2 = 1900 } if ("g2f1" == move2) { elo2 = 1400 } if ("g2d5" == move2) { elo2 = 1200 } if ("f2f4" == move2) { elo2 = 1400 } println(move2 + " Elo2 = " + elo2) var elo3 = 1000 val move3 = processPosition("8/3r2p1/pp1Bp1p1/1kP5/1n2K3/6R1/1P3P2/8 w") if ("c5c6" == move3) { elo3 = 2500 } if ("g3g6" == move3) { elo3 = 2000 } if ("e4e5" == move3) { elo3 = 1900 } if ("g3g5" == move3) { elo3 = 1700 } if ("e4d4" == move3) { elo3 = 1200 } if ("d6e5" == move3) { elo3 = 1200 } println(move3 + " Elo3 = " + elo3) var elo4 = 1000 val move4 = processPosition("8/4kb1p/2p3pP/1pP1P1P1/1P3K2/1B6/8/8 w") if ("e5e6" == move4) { elo4 = 2500 } if ("b3f7" == move4) { elo4 = 1600 } if ("b3c2" == move4) { elo4 = 1700 } if ("b3d1" == move4) { elo4 = 1800 } println(move4 + " Elo4 = " + elo4) var elo5 = 1000 val move5 = processPosition("b1R2nk1/5ppp/1p3n2/5N2/1b2p3/1P2BP2/q3BQPP/6K1 w") if ("e3c5" == move5) { elo5 = 2500 } if ("f5h6" == move5) { elo5 = 2100 } if ("e3h6" == move5) { elo5 = 1900 } if ("f5g7" == move5) { elo5 = 1500 } if ("f2g3" == move5) { elo5 = 1750 } if ("c8f8" == move5) { elo5 = 1200 } if ("f2h4" == move5) { elo5 = 1200 } if ("e3b6" == move5) { elo5 = 1750 } if ("e2c4" == move5) { elo5 = 1400 } println(move5 + " Elo5 = " + elo5) var elo6 = 1000 val move6 = processPosition("3rr1k1/pp3pbp/2bp1np1/q3p1B1/2B1P3/2N4P/PPPQ1PP1/3RR1K1 w") if ("g5f6" == move6) { elo6 = 2500 } if ("c3d5" == move6) { elo6 = 1700 } if ("c4b5" == move6) { elo6 = 1900 } if ("f2f4" == move6) { elo6 = 1700 } if ("a2a3" == move6) { elo6 = 1200 } if ("e1e3" == move6) { elo6 = 1200 } println(move6 + " Elo6 = " + elo6) var elo7 = 1000 val move7 = processPosition("r1b1qrk1/1ppn1pb1/p2p1npp/3Pp3/2P1P2B/2N5/PP1NBPPP/R2Q1RK1 b") if ("f6h7" == move7) { elo7 = 2500 } if ("f6e4" == move7) { elo7 = 1800 } if ("g6g5" == move7) { elo7 = 1700 } if ("a6a5" == move7) { elo7 = 1700 } if ("g8h7" == move7) { elo7 = 1500 } println(move7 + " Elo7 = " + elo7) var elo8 = 1000 val move8 = processPosition("2R1r3/5k2/pBP1n2p/6p1/8/5P1P/2P3P1/7K w") if ("b6d8" == move8) { elo8 = 2500 } if ("c8e8" == move8) { elo8 = 1600 } println(move8 + " Elo8 = " + elo8) var elo9 = 1000 val move9 = processPosition("2r2rk1/1p1R1pp1/p3p2p/8/4B3/3QB1P1/q1P3KP/8 w") if ("e3d4" == move9) { elo9 = 2500 } if ("e4g6" == move9) { elo9 = 1800 } if ("e4h7" == move9) { elo9 = 1800 } if ("e3h6" == move9) { elo9 = 1700 } if ("d7b7" == move9) { elo9 = 1400 } println(move9 + " Elo9 = " + elo9) var elo10 = 1000 val move10 = processPosition("r1bq1rk1/p4ppp/1pnp1n2/2p5/2PPpP2/1NP1P3/P3B1PP/R1BQ1RK1 b") if ("d8d7" == move10) { elo10 = 2000 } if ("f6e8" == move10) { elo10 = 2000 } if ("h7h5" == move10) { elo10 = 1800 } if ("c5d4" == move10) { elo10 = 1600 } if ("c8a6" == move10) { elo10 = 1800 } if ("a7a5" == move10) { elo10 = 1800 } if ("f8e8" == move10) { elo10 = 1400 } if ("d6d5" == move10) { elo10 = 1500 } println(move10 + " Elo10 = " + elo10) val elo = (elo1 + elo2 + elo3 + elo4 + elo5 + elo6 + elo7 + elo8 + elo9 + elo10) / 10 println("Calculated Elo = " + elo) assertTrue(elo > 2000) } private fun processPosition(fen: String): String { search.board.fen = fen search.go(SearchParameters[5 * 60000]) // five minutes val move = Move.toString(search.bestMove) println("result = " + move) return move } }
mit
e3195311081a9e2e73197704d6ff6a5e
24.241379
99
0.433126
2.949843
false
false
false
false
xfournet/intellij-community
uast/uast-common/src/org/jetbrains/uast/baseElements/UElement.kt
4
4435
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * The common interface for all Uast elements. */ interface UElement { /** * Returns the element parent. */ val uastParent: UElement? /** * Returns the PSI element underlying this element. Note that some UElements are synthetic and do not have * an underlying PSI element; this doesn't mean that they are invalid. * * **Node for implementors**: please implement both [sourcePsi] and [javaPsi] fields or make them return `null` explicitly * if implementing is not possible. Redirect `psi` to one of them keeping existing behavior, use [sourcePsi] if nothing else is specified. */ @Deprecated("ambiguous psi element, use `sourcePsi` or `javaPsi`", ReplaceWith("javaPsi")) val psi: PsiElement? /** * Returns the PSI element in original (physical) tree to which this UElement corresponds. * **Note**: that some UElements are synthetic and do not have an underlying PSI element; * this doesn't mean that they are invalid. */ val sourcePsi: PsiElement? get() = psi /** * Returns the element which try to mimic Java-api psi element: [com.intellij.psi.PsiClass], [com.intellij.psi.PsiMethod] or [com.intellij.psi.PsiAnnotation] etc. * Will return null if this UElement doesn't have Java representation or it is not implemented. */ val javaPsi: PsiElement? get() = psi /** * Returns true if this element is valid, false otherwise. */ val isPsiValid: Boolean get() = psi?.isValid ?: true /** * Returns the list of comments for this element. */ val comments: List<UComment> get() = emptyList() /** * Returns the log string (usually one line containing the class name and some additional information). * * Examples: * UWhileExpression * UBinaryExpression (>) * UCallExpression (println) * USimpleReferenceExpression (i) * ULiteralExpression (5) * * @return the expression tree for this element. * @see [UIfExpression] for example. */ fun asLogString(): String /** * Returns the string in pseudo-code. * * Output example (should be something like this): * while (i > 5) { * println("Hello, world") * i-- * } * * @return the rendered text. * @see [UIfExpression] for example. */ fun asRenderString(): String = asLogString() /** * Returns the string as written in the source file. * Use this String only for logging and diagnostic text messages. * * @return the original text. */ fun asSourceString(): String = asRenderString() /** * Passes the element to the specified visitor. * * @param visitor the visitor to pass the element to. */ fun accept(visitor: UastVisitor) { visitor.visitElement(this) visitor.afterVisitElement(this) } /** * Passes the element to the specified typed visitor. * * @param visitor the visitor to pass the element to. */ fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitElement(this, data) } @Deprecated("No use anymore, all declarations were moved to UElement. To be removed in 2018.2") interface JvmDeclarationUElement : UElement @get:ApiStatus.Experimental val UElement?.sourcePsiElement: PsiElement? get() = this?.sourcePsi @ApiStatus.Experimental @SuppressWarnings("unchecked") fun <T : PsiElement> UElement?.getAsJavaPsiElement(clazz: Class<T>): T? = this?.javaPsi?.takeIf { clazz.isAssignableFrom(it.javaClass) } as? T /** * Returns a sequence including this element and its containing elements. */ val UElement.withContainingElements: Sequence<UElement> get() = generateSequence(this, UElement::uastParent)
apache-2.0
9b9225a6b2945c4262a18aaa04b94488
30.232394
164
0.703269
4.244019
false
false
false
false
googlemaps/android-samples
ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/StreetViewPanoramaViewDemoActivity.kt
1
2843
// 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 // // 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.kotlindemos import android.os.Bundle import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.maps.StreetViewPanoramaOptions import com.google.android.gms.maps.StreetViewPanoramaView import com.google.android.gms.maps.model.LatLng /** * This shows how to create a simple activity with streetview */ class StreetViewPanoramaViewDemoActivity : AppCompatActivity() { private lateinit var streetViewPanoramaView: StreetViewPanoramaView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val options = StreetViewPanoramaOptions() savedInstanceState ?: options.position(SYDNEY) streetViewPanoramaView = StreetViewPanoramaView(this, options) addContentView( streetViewPanoramaView, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) // *** IMPORTANT *** // StreetViewPanoramaView requires that the Bundle you pass contain _ONLY_ // StreetViewPanoramaView SDK objects or sub-Bundles. streetViewPanoramaView.onCreate(savedInstanceState?.getBundle(STREETVIEW_BUNDLE_KEY)) } override fun onResume() { streetViewPanoramaView.onResume() super.onResume() } override fun onPause() { streetViewPanoramaView.onPause() super.onPause() } override fun onDestroy() { streetViewPanoramaView.onDestroy() super.onDestroy() } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) var streetViewBundle = outState.getBundle(STREETVIEW_BUNDLE_KEY) if (streetViewBundle == null) { streetViewBundle = Bundle() outState.putBundle( STREETVIEW_BUNDLE_KEY, streetViewBundle ) } streetViewPanoramaView.onSaveInstanceState(streetViewBundle) } companion object { // George St, Sydney private val SYDNEY = LatLng(-33.87365, 151.20689) private const val STREETVIEW_BUNDLE_KEY = "StreetViewBundleKey" } }
apache-2.0
17f5b47867b2bb48fce652ed310aa55c
34.111111
93
0.695392
5.216514
false
false
false
false
edvin/tornadofx-idea-plugin
src/main/kotlin/no/tornado/tornadofx/idea/intentions/ConvertAllPropertiesToFX.kt
1
2818
package no.tornado.tornadofx.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.facet.FacetManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import no.tornado.tornadofx.idea.FXTools import no.tornado.tornadofx.idea.FXTools.isJavaFXProperty import no.tornado.tornadofx.idea.facet.TornadoFXFacet import no.tornado.tornadofx.idea.facet.TornadoFXFacetType import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil.getDeclarationReturnType import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.idea.util.projectStructure.allModules import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtPropertyDelegate class ConvertAllPropertiesToFX: PsiElementBaseIntentionAction(), LowPriorityAction { override fun getText() = "Convert all properties to TornadoFX properties" override fun getFamilyName() = text override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { if (element.isWritable && element.language == KotlinLanguage.INSTANCE) { TornadoFXFacet.get(project) ?: return false val ktClass = if (element is KtClass) element else PsiTreeUtil.getParentOfType(element, KtClass::class.java) if (ktClass != null) { val psiFacade = JavaPsiFacade.getInstance(project) val psiClass = psiFacade.findClass(ktClass.fqName.toString(), project.allScope()) return psiClass != null && !FXTools.isTornadoFXType(psiClass) } } return false } override fun invoke(project: Project, editor: Editor?, element: PsiElement) { val ktClass = element as? KtClass ?: PsiTreeUtil.getParentOfType(element, KtClass::class.java)!! val converter = FXPropertyConverter() // Find all val or vars that are not JavaFX Properties val params = ktClass.primaryConstructorParameters .filter { it.hasValOrVar() && !it.isVarArg && it.name != null && !isJavaFXProperty(getDeclarationReturnType(it)) } // Filter properties that are not JavaFX Properties and not Property Delegates val props = ktClass.body?.properties ?.filter { it.name != null && !isJavaFXProperty(getDeclarationReturnType(it)) } ?.filter { it.children.find { psiElement -> psiElement is KtPropertyDelegate } == null} params.forEach { converter.addForParam(it, project, it) } props?.forEach { converter.addForProp(it, project, it) } } }
apache-2.0
374f2bcf310639048606e99a588edae4
46.762712
130
0.735983
4.681063
false
false
false
false
Kotlin/dokka
plugins/base/src/main/kotlin/renderers/preprocessors.kt
1
1586
package org.jetbrains.dokka.base.renderers import org.jetbrains.dokka.base.resolvers.shared.LinkFormat import org.jetbrains.dokka.pages.ModulePage import org.jetbrains.dokka.pages.RendererSpecificPage import org.jetbrains.dokka.pages.RendererSpecificResourcePage import org.jetbrains.dokka.pages.RendererSpecificRootPage import org.jetbrains.dokka.pages.RenderingStrategy import org.jetbrains.dokka.pages.RootPageNode import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.transformers.pages.PageTransformer object RootCreator : PageTransformer { override fun invoke(input: RootPageNode) = RendererSpecificRootPage("", listOf(input), RenderingStrategy.DoNothing) } class PackageListCreator( val context: DokkaContext, val format: LinkFormat, val outputFilesNames: List<String> = listOf("package-list") ) : PageTransformer { override fun invoke(input: RootPageNode) = input.transformPageNodeTree { pageNode -> pageNode.takeIf { it is ModulePage }?.let { it.modified(children = it.children + packageList(input, it as ModulePage)) } ?: pageNode } private fun packageList(rootPageNode: RootPageNode, module: ModulePage): List<RendererSpecificPage> { val content = PackageListService(context, rootPageNode).createPackageList( module, format ) return outputFilesNames.map { fileName -> RendererSpecificResourcePage( fileName, emptyList(), RenderingStrategy.Write(content) ) } } }
apache-2.0
b73365f58032d4b3432f30ea6a8acbbb
38.65
144
0.727617
4.748503
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/editor/resources/HljsHtmlCssProvider.kt
1
993
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.editor.resources import com.vladsch.md.nav.MdBundle import com.vladsch.md.nav.MdPlugin import com.vladsch.md.nav.editor.javafx.JavaFxHtmlPanelProvider import com.vladsch.md.nav.editor.util.HtmlCssResource import com.vladsch.md.nav.editor.util.HtmlCssResourceProvider object HljsHtmlCssProvider : HtmlCssResourceProvider() { val NAME = MdBundle.message("editor.hljs.html.css.provider.name") val ID = "com.vladsch.md.nav.editor.hljs.html.css" override val HAS_PARENT = true override val INFO = Info(ID, NAME) override val COMPATIBILITY = JavaFxHtmlPanelProvider.COMPATIBILITY override val cssResource: HtmlCssResource = HtmlCssResource(INFO , MdPlugin.PREVIEW_FX_HLJS_STYLESHEET_DARK , MdPlugin.PREVIEW_FX_HLJS_STYLESHEET_LIGHT , null) }
apache-2.0
8503cccecb6d8360389da64dd1d4846c
44.136364
177
0.7714
3.650735
false
false
false
false
rahulsom/grooves
grooves-example-pushstyle/src/main/kotlin/grooves/example/push/domains.kt
1
3704
package grooves.example.push import com.github.rahulsom.grooves.api.events.BaseEvent import com.github.rahulsom.grooves.api.events.RevertEvent import com.github.rahulsom.grooves.api.snapshots.Snapshot import grooves.example.pushstyle.tables.records.BalanceRecord import io.reactivex.Flowable import org.reactivestreams.Publisher import java.text.SimpleDateFormat import java.time.OffsetDateTime import java.time.ZoneId import java.util.Date import java.util.UUID data class Account(val id: String) sealed class Transaction( override val id: String, override var aggregate: Account?, override var timestamp: Date, override var position: Long ) : BaseEvent<Account, String, Transaction> { override fun getAggregateObservable(): Publisher<Account> = Flowable.fromIterable(listOfNotNull(aggregate)) override var revertedBy: RevertEvent<Account, String, Transaction>? get() = revertedBy set(value) { revertedBy = value } data class Deposit( override val id: String, override var aggregate: Account?, override var timestamp: Date, override var position: Long, val atmId: String, val amount: Long ) : Transaction(id, aggregate, timestamp, position) data class Withdraw( override val id: String, override var aggregate: Account?, override var timestamp: Date, override var position: Long, val atmId: String, val amount: Long ) : Transaction(id, aggregate, timestamp, position) } class Balance() : Snapshot<Account, String, String, Transaction> { override var id: String? = UUID.randomUUID().toString() internal var aggregate: Account? = null override var lastEventTimestamp: Date? = Date() override var lastEventPosition: Long = 0 var deprecates = mutableListOf<Account>() internal var deprecatedBy: Account? = null var balance: Long = 0 constructor( id: String?, aggregate: Account?, balance: Long, lastEventPosition: Long, lastEventTimestamp: Date ) : this() { this.id = id this.aggregate = aggregate this.balance = balance this.lastEventPosition = lastEventPosition this.lastEventTimestamp = lastEventTimestamp } constructor(balance: BalanceRecord) : this( balance.bId, Account(balance.bAccount), balance.balance, balance.bVersion, Date.from(balance.bTime.toInstant()) ) fun toBalanceRecord(): BalanceRecord { return BalanceRecord( id, lastEventPosition, OffsetDateTime.ofInstant(lastEventTimestamp?.toInstant(), ZoneId.systemDefault()), aggregate?.id, balance ) } override fun getAggregateObservable(): Publisher<Account> = Flowable.fromIterable(listOfNotNull(aggregate)) override fun getDeprecatesObservable() = Flowable.fromIterable(deprecates) override fun getDeprecatedByObservable(): Publisher<Account> = Flowable.fromIterable(listOfNotNull(deprecatedBy)) override fun setAggregate(aggregate: Account) { this.aggregate = aggregate } override fun setDeprecatedBy(deprecatingAggregate: Account) { deprecatedBy = deprecatingAggregate } override fun toString(): String { val idPart = id?.substring(24) val aggPart = aggregate?.id val ts = lastEventTimestamp.let { SimpleDateFormat("HH:mm:ss,SSS").format(it) } return "Balance(id=$idPart, aggregate=$aggPart, lastEventTimestamp=$ts, " + "version=$lastEventPosition, balance=$balance)" } }
apache-2.0
9a0818ea4ce28a2d9630d7b4ce53b5e9
30.398305
117
0.675756
4.567201
false
false
false
false
http4k/http4k
src/docs/blog/typesafe_websockets/example.kt
1
1711
package blog.typesafe_websockets import org.http4k.core.HttpHandler import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.format.Jackson.auto import org.http4k.lens.Path import org.http4k.routing.bind import org.http4k.routing.websockets import org.http4k.server.Jetty import org.http4k.server.PolyHandler import org.http4k.server.asServer import org.http4k.websocket.Websocket import org.http4k.websocket.WsHandler import org.http4k.websocket.WsMessage // in json, this looks like: {"value": 123, "currency: "EUR" } data class Money(val value: Int, val currency: String) fun main() { // we use the Lens API to convert between the WsMessage and the Money instance, and to // dynamically bind the "name" from the path val moneyLens = WsMessage.auto<Money>().toLens() val nameLens = Path.of("name") // the routing API is virtually identical to the standard http4k http routing API. // on connection, the bound WsConsumer is called with the Websocket instance val ws: WsHandler = websockets( "/hello" bind websockets( "/{name}" bind { ws: Websocket -> val name = nameLens(ws.upgradeRequest) ws.onMessage { val received = moneyLens(it) ws.send(moneyLens(received)) } ws.onClose { println("closed") } ws.send(WsMessage("hello $name")) } ) ) val http: HttpHandler = { _: Request -> Response(OK).body("hiya world") } // the poly-handler can serve both http and ws protocols. PolyHandler(http, ws).asServer(Jetty(9000)).start().block() }
apache-2.0
d413409609b02dc111138f1d11ad8746
34.645833
90
0.672122
3.802222
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/androidTest/java/org/wordpress/android/fluxc/release/ReleaseStack_PostListTestXMLRPC.kt
2
4005
package org.wordpress.android.fluxc.release import androidx.arch.core.executor.testing.InstantTaskExecutorRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters import org.wordpress.android.fluxc.model.list.ListOrder import org.wordpress.android.fluxc.model.list.PagedListWrapper import org.wordpress.android.fluxc.model.list.PostListDescriptor.PostListDescriptorForXmlRpcSite import org.wordpress.android.fluxc.model.list.PostListOrderBy import org.wordpress.android.fluxc.model.post.PostStatus import org.wordpress.android.fluxc.model.post.PostStatus.DRAFT import org.wordpress.android.fluxc.model.post.PostStatus.SCHEDULED import org.wordpress.android.fluxc.model.post.PostStatus.TRASHED import org.wordpress.android.fluxc.release.utils.ListStoreConnectedTestHelper import org.wordpress.android.fluxc.release.utils.ListStoreConnectedTestMode import org.wordpress.android.fluxc.release.utils.ListStoreConnectedTestMode.SinglePage import org.wordpress.android.fluxc.release.utils.TEST_LIST_CONFIG import org.wordpress.android.fluxc.release.utils.TestPostListDataSource import org.wordpress.android.fluxc.release.utils.TestPostUIItem import org.wordpress.android.fluxc.store.ListStore import org.wordpress.android.fluxc.store.PostStore import org.wordpress.android.fluxc.store.PostStore.DEFAULT_POST_STATUS_LIST import javax.inject.Inject private const val TEST_POST_LIST_SEARCH_QUERY = "a" internal class XmlRpcPostListTestCase( val statusList: List<PostStatus> = DEFAULT_POST_STATUS_LIST, val order: ListOrder = ListOrder.DESC, val orderBy: PostListOrderBy = PostListOrderBy.DATE, val searchQuery: String? = null, val testMode: ListStoreConnectedTestMode = SinglePage(false) ) @RunWith(Parameterized::class) internal class ReleaseStack_PostListTestXMLRPC( private val testCase: XmlRpcPostListTestCase ) : ReleaseStack_XMLRPCBase() { @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @Inject internal lateinit var listStore: ListStore @Inject internal lateinit var postStore: PostStore companion object { @JvmStatic @Parameters fun testCases(): List<XmlRpcPostListTestCase> = listOf( /* These test cases are specifically picked to be non-demanding so that it can run without much setup. They are very easy to extend on, so if we start running them on an account with pre-setup, they can made to be a lot more demanding by ensuring that each post list type returns some data. */ XmlRpcPostListTestCase(), XmlRpcPostListTestCase(statusList = listOf(DRAFT)), XmlRpcPostListTestCase(statusList = listOf(SCHEDULED)), XmlRpcPostListTestCase(statusList = listOf(TRASHED)), XmlRpcPostListTestCase(order = ListOrder.ASC), XmlRpcPostListTestCase(orderBy = PostListOrderBy.ID), XmlRpcPostListTestCase(searchQuery = TEST_POST_LIST_SEARCH_QUERY) ) } private val listStoreConnectedTestHelper by lazy { ListStoreConnectedTestHelper(listStore) } override fun setUp() { super.setUp() mReleaseStackAppComponent.inject(this) } @Test fun test() { listStoreConnectedTestHelper.runTest(testCase.testMode, this::createPagedListWrapper) } private fun createPagedListWrapper(): PagedListWrapper<TestPostUIItem> { val descriptor = PostListDescriptorForXmlRpcSite( site = sSite, statusList = testCase.statusList, order = testCase.order, orderBy = testCase.orderBy, searchQuery = testCase.searchQuery, config = TEST_LIST_CONFIG ) return listStoreConnectedTestHelper.getList(descriptor, TestPostListDataSource(mDispatcher)) } }
gpl-2.0
114365c1329d66a00362b5a33ea50564
42.532609
116
0.740075
4.47486
false
true
false
false
androidx/androidx-ci-action
AndroidXCI/lib/src/test/kotlin/dev/androidx/ci/fake/FakeFirebaseTestLabApi.kt
1
4080
/* * 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 dev.androidx.ci.fake import com.squareup.moshi.Moshi import dev.androidx.ci.firebase.FirebaseTestLabApi import dev.androidx.ci.firebase.dto.EnvironmentType import dev.androidx.ci.generated.ftl.ApkDetail import dev.androidx.ci.generated.ftl.ApkManifest import dev.androidx.ci.generated.ftl.FileReference import dev.androidx.ci.generated.ftl.GetApkDetailsResponse import dev.androidx.ci.generated.ftl.TestEnvironmentCatalog import dev.androidx.ci.generated.ftl.TestMatrix import dev.zacsweers.moshix.reflect.MetadataKotlinJsonAdapterFactory import okio.buffer import okio.source import java.util.UUID internal class FakeFirebaseTestLabApi( /** * Invoked when a new test is created */ private val onTestCreated: ((FakeFirebaseTestLabApi, TestMatrix) -> Unit)? = null ) : FirebaseTestLabApi { private val testMatrices = mutableMapOf<String, TestMatrix>() private var environmentCatalog: TestEnvironmentCatalog? = null private val apkToPkgMap = mutableMapOf<String, String>() /** * Read the catalog from a recorded request */ private val realEnvironmentCatalog by lazy { FakeFirebaseTestLabApi::class.java.classLoader .getResourceAsStream("env_catalog.json")!!.use { val moshi = Moshi.Builder() .add(MetadataKotlinJsonAdapterFactory()) .build() moshi.adapter(TestEnvironmentCatalog::class.java).lenient() .fromJson(it.source().buffer())!! } } fun setTestEnvironmentCatalog( environmentCatalog: TestEnvironmentCatalog ) { this.environmentCatalog = environmentCatalog } fun setTestMatrix( testMatrix: TestMatrix ) { check(testMatrix.testMatrixId != null) testMatrices[testMatrix.testMatrixId!!] = testMatrix } fun getTestMatrices() = testMatrices.values.toList() override suspend fun getTestMatrix(projectId: String, testMatrixId: String): TestMatrix { val testMatrix = testMatrices[testMatrixId] ?: throwNotFound<TestMatrix>() check(testMatrix.projectId == projectId) return testMatrix } fun deleteTestMatrix(testMatrixId: String) { testMatrices.remove(testMatrixId) } override suspend fun createTestMatrix( projectId: String, requestId: String, testMatrix: TestMatrix ): TestMatrix { val id = UUID.randomUUID().toString() check(projectId == testMatrix.projectId) testMatrices[id] = testMatrix.copy( testMatrixId = id, state = TestMatrix.State.PENDING ) onTestCreated?.invoke(this, testMatrices[id]!!) return testMatrices[id]!! } override suspend fun getTestEnvironmentCatalog( environmentType: EnvironmentType, projectId: String ): TestEnvironmentCatalog { return environmentCatalog ?: realEnvironmentCatalog } override suspend fun getApkDetails(fileReference: FileReference): GetApkDetailsResponse { val packageName = apkToPkgMap.getOrPut(fileReference.gcsPath!!) { "$FAKE_PKG_PREFIX${apkToPkgMap.size}" } return GetApkDetailsResponse( apkDetail = ApkDetail( apkManifest = ApkManifest( packageName = packageName ) ) ) } companion object { const val FAKE_PKG_PREFIX = "androidx.fake.pkg" } }
apache-2.0
2aa167e85feb145c65e99d0d6298bbd7
33
93
0.68701
4.568869
false
true
false
false
andersonlucasg3/SpriteKit-Android
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/SKView.kt
1
2631
package br.com.insanitech.spritekit import android.content.Context import android.opengl.GLSurfaceView import android.util.AttributeSet import android.view.ViewGroup import br.com.insanitech.spritekit.engine.SKEngine import br.com.insanitech.spritekit.graphics.SKPoint import br.com.insanitech.spritekit.graphics.SKSize class SKView : GLSurfaceView { private val engine = SKEngine.instance val size: SKSize = SKSize() var scene: SKScene? get() = this.engine.sceneToBePresented private set(value) { this.engine.sceneToBePresented = value } var isPaused: Boolean get() = this.engine.isPaused set(value) { this.engine.isPaused = value if (!value) { this.presentScene() } } constructor(context: Context) : super(context) { this.engine.start(this) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { this.engine.start(this) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() this.engine.stop() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) this.size.width = w.toFloat() this.size.height = h.toFloat() } fun removeFromSuperView() { (this.parent as ViewGroup).removeView(this) } fun presentScene(scene: SKScene?) { if (this.scene != scene) { this.scene?.willMove(this) this.scene?.view = null } this.scene = scene this.scene?.view = this this.scene?.didMove(this) this.presentScene() } private fun presentScene() { this.engine.tryRender(this) } open fun convertTo(point: SKPoint, scene: SKScene): SKPoint { // The point needs to be converted to the scene scale, because the scene may be smaller than the view. val realPoint = SKPoint((point.x * scene.size.width) / this.size.width, (point.y * scene.size.height) / this.size.height) val newX = realPoint.x - scene.position.x val newY = scene.size.height - realPoint.y - scene.position.y return SKPoint(newX, newY) } open fun convertFrom(point: SKPoint, scene: SKScene): SKPoint { val realPoint = SKPoint((point.x * this.size.width) / scene.size.width, (point.y * this.size.height) / scene.size.height) val newX = realPoint.x + scene.position.x val newY = this.size.height - realPoint.y + scene.position.y return SKPoint(newX, newY) } }
bsd-3-clause
c905ee0278830cde4786cf6e308ab75d
28.897727
110
0.629038
3.95045
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/world/chunk/Chunks.kt
1
5403
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:Suppress("NOTHING_TO_INLINE") package org.lanternpowered.server.world.chunk import org.lanternpowered.api.world.chunk.ChunkColumnPosition import org.lanternpowered.api.world.chunk.ChunkPosition import org.spongepowered.math.vector.Vector3i internal object Chunks { /** * The amount of bits used by a chunk. */ const val Bits = 4 /** * The 1D size of a chunk. (x, y and z) */ const val Size = 1 shl Bits /** * The mask and maximum index of [Size]. */ const val Mask = Size - 1 /** * Half of [Size]. */ const val HalfSize = Size / 2 /** * The 2D area of a single chunk. (x * z) */ const val Area = Size * Size /** * The 3D volume of a single chunk. (x * y * z) */ const val Volume = Size * Size * Size const val LocalIndexBits = Bits * 3 const val LocalIndexMax = (1 shl LocalIndexBits) - 1 /** * The minimum chunk x and z coordinate. */ const val MinXZ = -1875000 /** * The maximum chunk x and z coordinate. */ const val MaxXZ = 1875000 /** * The minimum chunk y coordinate. */ const val MinY = 0 /** * The maximum chunk y coordinate. */ const val MaxY = 15 /** * The range of chunk y coordinates. */ val RangeY = MinY..MaxY const val MinBlockXZ = MinXZ shl Bits const val MaxBlockXZ = MaxXZ shl Bits - 1 const val MinBlockY = MinY shl Bits const val MaxBlockY = MaxY shl Bits - 1 val LocalRange = 0 until Size /** * Converts the x, y or z component to a chunk component coordinate. */ inline fun toChunk(component: Int): Int = component shr Bits /** * Converts the x, y, z components to chunk coordinates. */ inline fun toChunk(x: Int, y: Int, z: Int): ChunkPosition = ChunkPosition(this.toChunk(x), this.toChunk(y), this.toChunk(z)) /** * Converts the x, y, z components to chunk coordinates. */ fun toChunk(position: Vector3i): ChunkPosition = this.toChunk(position.x, position.y, position.z) /** * Converts the x, y or z component to chunk column coordinates. */ inline fun toChunkColumn(x: Int, z: Int): ChunkColumnPosition = ChunkColumnPosition(this.toChunk(x), this.toChunk(z)) /** * Converts the x, y or z component to a local component coordinate. */ inline fun toLocal(component: Int): Int = component and Mask /** * Converts the x, y, z components to local coordinates. */ fun toLocal(x: Int, y: Int, z: Int): LocalPosition = LocalPosition(this.toLocal(x), this.toLocal(y), this.toLocal(z)) /** * Converts the x, y, z components to local coordinates. */ fun toLocal(position: Vector3i): LocalPosition = this.toLocal(position.x, position.y, position.z) /** * Converts the x, y or z component to a global component coordinate. */ inline fun toGlobal(chunkComponent: Int, localComponent: Int): Int = (chunkComponent shl Bits) or localComponent /** * Converts the x, y or z component to a global component coordinate. */ inline fun toGlobal(chunkComponent: Int): Int = chunkComponent shl Bits /** * Converts the x, y, z to global coordinates. */ fun toGlobal(chunk: ChunkPosition): Vector3i = this.toGlobal(chunk.x, chunk.y, chunk.z) /** * Converts the x, y, z to global coordinates. */ fun toGlobal(chunkX: Int, chunkY: Int, chunkZ: Int): Vector3i { val x = this.toGlobal(chunkX) val y = this.toGlobal(chunkY) val z = this.toGlobal(chunkZ) return Vector3i(x, y, z) } /** * Converts the x, y, z to global coordinates. */ fun toGlobal(chunk: ChunkPosition, local: LocalPosition): Vector3i = this.toGlobal(chunk.x, chunk.y, chunk.z, local.x, local.y, local.z) /** * Converts the x, y, z to global coordinates. */ fun toGlobal(chunk: ChunkPosition, localX: Int, localY: Int, localZ: Int): Vector3i = this.toGlobal(chunk.x, chunk.y, chunk.z, localX, localY, localZ) /** * Converts the x, y, z to global coordinates. */ fun toGlobal(chunkX: Int, chunkY: Int, chunkZ: Int, localX: Int, localY: Int, localZ: Int): Vector3i { val x = this.toGlobal(chunkX, localX) val y = this.toGlobal(chunkY, localY) val z = this.toGlobal(chunkZ, localZ) return Vector3i(x, y, z) } /** * Converts the local x, y and z components into a index (4 bits per component, so 12 bits). Therefore * the value ranges between 0 and (1 shl 12) - 1. */ fun localIndex(localX: Int, localY: Int, localZ: Int): Int = (localY shl 8) or (localZ shl 4) or localX /** * Performs the given [function] for each [LocalPosition] of a chunk. */ inline fun forEachLocalPosition(function: (LocalPosition) -> Unit) { for (i in 0 until Volume) function(LocalPosition(i)) } }
mit
a30e3d1d52f1b863d210ce9b37dddc91
27.893048
116
0.613178
3.713402
false
false
false
false
ursjoss/scipamato
core/core-entity/src/test/kotlin/ch/difty/scipamato/core/entity/keyword/KeywordDefinitionTest.kt
1
6466
package ch.difty.scipamato.core.entity.keyword import org.amshove.kluent.shouldBeEmpty import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeNull import org.amshove.kluent.shouldContainSame import org.amshove.kluent.shouldNotBeNull import org.junit.jupiter.api.Test @Suppress("PrivatePropertyName", "PrivatePropertyName", "SpellCheckingInspection", "VariableNaming") internal class KeywordDefinitionTest { private val kw_de = KeywordTranslation(10, "de", "stichwort2", 1) private val kw_de2 = KeywordTranslation(10, "de", "stichwort2foo", 1) private val kw_en = KeywordTranslation(11, "en", "keyword2", 1) private val kw_fr = KeywordTranslation(12, "fr", "motdeclef2", 1) @Test fun withNoTranslations_unableToEstablishMainName() { val kd = KeywordDefinition(1, "de", 1) kd.id shouldBeEqualTo 1 kd.name shouldBeEqualTo "n.a." kd.searchOverride.shouldBeNull() kd.displayValue shouldBeEqualTo "n.a." kd.getTranslations().shouldBeEmpty() } @Test fun withSearchOverride() { val kd = KeywordDefinition(1, "de", "so", 1) kd.id shouldBeEqualTo 1 kd.name shouldBeEqualTo "n.a." kd.searchOverride shouldBeEqualTo "so" kd.displayValue shouldBeEqualTo "n.a." kd.getTranslations().shouldBeEmpty() } @Test fun withTranslations_onePerLanguage() { val kd = KeywordDefinition(2, "de", "sooo", 1, kw_de, kw_en, kw_fr) kd.id shouldBeEqualTo 2 kd.name shouldBeEqualTo "stichwort2" kd.searchOverride shouldBeEqualTo "sooo" kd.displayValue shouldBeEqualTo "stichwort2" val trs = kd.getTranslations() trs.map { it.name } shouldContainSame listOf("stichwort2", "keyword2", "motdeclef2") for (tr in trs) tr.lastModified.shouldBeNull() } @Test fun canGetTranslationsAsString_withTranslationsIncludingMainTranslation() { val kd = KeywordDefinition(2, "de", 1, kw_de, kw_en, kw_fr) kd.translationsAsString shouldBeEqualTo "DE: 'stichwort2'; EN: 'keyword2'; FR: 'motdeclef2'" } @Test fun canGetTranslationsAsString_withTranslationsIncludingMainTranslation_withPartialTranslation() { val kd = KeywordDefinition( 2, "de", 1, kw_de, kw_en, KeywordTranslation(12, "fr", null, 1) ) kd.translationsAsString shouldBeEqualTo "DE: 'stichwort2'; EN: 'keyword2'; FR: n.a." } @Test fun canGetTranslationsAsString_withNoTranslations() { val kd = KeywordDefinition(2, "de", 1) kd.translationsAsString.shouldBeNull() } @Test fun modifyTransl_withMainLangTranslModified_changesMainName_translName_andSetsModifiedTimestamp() { val kd = KeywordDefinition(2, "de", 1, kw_de, kw_en, kw_fr) kd.setNameInLanguage("de", "KEYWORD 2") kd.name shouldBeEqualTo "KEYWORD 2" assertTranslatedName(kd, "de", 0, "KEYWORD 2") assertLastModifiedIsNotNull(kd, "de", 0) assertLastModifiedIsNull(kd, "en", 0) assertLastModifiedIsNull(kd, "fr", 0) } private fun assertTranslatedName(kd: KeywordDefinition, lc: String, index: Int, value: String) { kd.getTranslations(lc)[index]?.name shouldBeEqualTo value } @Suppress("SameParameterValue") private fun assertLastModifiedIsNotNull(kd: KeywordDefinition, lc: String, index: Int) { kd.getTranslations(lc)[index]?.lastModified.shouldNotBeNull() } private fun assertLastModifiedIsNull(kd: KeywordDefinition, lc: String, index: Int) { kd.getTranslations(lc)[index]?.lastModified.shouldBeNull() } @Test fun modifyTransl_withNonMainLangTranslModified_keepsMainName_changesTranslationName_andSetsModifiedTimestamp() { val kd = KeywordDefinition(2, "de", 1, kw_de, kw_en, kw_fr) kd.setNameInLanguage("fr", "bar") kd.name shouldBeEqualTo "stichwort2" assertTranslatedName(kd, "fr", 0, "bar") kd.getTranslations("de")[0]?.lastModified.shouldBeNull() kd.getTranslations("en")[0]?.lastModified.shouldBeNull() assertLastModifiedIsNotNull(kd, "fr", 0) } @Test fun gettingNameInLanguage_withValidLanguages_returnsNames() { val kd = KeywordDefinition(2, "de", 1, kw_de, kw_en, kw_fr) kd.getNameInLanguage("de") shouldBeEqualTo "stichwort2" kd.getNameInLanguage("en") shouldBeEqualTo "keyword2" kd.getNameInLanguage("fr") shouldBeEqualTo "motdeclef2" } @Test fun gettingNameInLanguage_withInvalidLanguage_returnsNames() { KeywordDefinition(2, "de", 1).getNameInLanguage("de").shouldBeNull() } @Test fun withTranslations_moreThanOnePerLanguage() { val kd = KeywordDefinition(2, "de", 1, kw_de, kw_de2, kw_en, kw_fr) kd.id shouldBeEqualTo 2 kd.name shouldBeEqualTo "stichwort2" kd.displayValue shouldBeEqualTo "stichwort2" val trs = kd.getTranslations() trs.map { it.name } shouldContainSame listOf("stichwort2", "stichwort2foo", "keyword2", "motdeclef2") for (tr in trs) tr.lastModified.shouldBeNull() } @Test fun canGetTranslationsAsString_withTranslationsIncludingMainTranslation_withMultipleTranslations() { val kd = KeywordDefinition(2, "de", 1, kw_de, kw_de2, kw_en, kw_fr) kd.translationsAsString shouldBeEqualTo "DE: 'stichwort2','stichwort2foo'; EN: 'keyword2'; FR: 'motdeclef2'" } @Test fun modifyTransl_withMainLangTranslModified_changesMainName_translName_andSetsModTimestamp_multipleTranslPerLang() { val kd = KeywordDefinition(2, "de", 1, kw_de, kw_en, kw_fr, kw_de2) kd.setNameInLanguage("de", "Stichwort 2") kd.name shouldBeEqualTo "Stichwort 2" assertTranslatedName(kd, "de", 0, "Stichwort 2") assertTranslatedName(kd, "de", 1, "stichwort2foo") assertLastModifiedIsNotNull(kd, "de", 0) assertLastModifiedIsNull(kd, "de", 1) assertLastModifiedIsNull(kd, "en", 0) assertLastModifiedIsNull(kd, "fr", 0) } @Test fun gettingNullSafeId_withIdPresent() { val kd = KeywordDefinition(2, "de", 1, kw_de, kw_en, kw_fr, kw_de2) kd.nullSafeId shouldBeEqualTo 2 } @Test fun gettingNullSafeId_withNoIdPresent() { val kd = KeywordDefinition(null, "de", 1, kw_de, kw_en, kw_fr, kw_de2) kd.nullSafeId shouldBeEqualTo 0 } }
bsd-3-clause
77a6a77c46fd9a3b41ac7dc6a0e91489
38.91358
120
0.673059
3.819256
false
true
false
false
ageery/kwicket
kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/link/KLink.kt
1
1270
package org.kwicket.wicket.core.markup.html.link import org.apache.wicket.WicketRuntimeException import org.apache.wicket.behavior.Behavior import org.apache.wicket.markup.html.link.Link import org.apache.wicket.model.IModel import org.kwicket.NonAjaxHandler import org.kwicket.component.init /** * [Link] with named and default constructor arguments. */ open class KLink<T>( id: String, model: IModel<T>? = null, private val onClick: NonAjaxHandler? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, visible: Boolean? = null, enabled: Boolean? = null, renderBodyOnly: Boolean? = null, escapeModelStrings: Boolean? = null, behaviors: List<Behavior>? = null ) : Link<T>(id, model) { init { init( outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, visible = visible, enabled = enabled, escapeModelStrings = escapeModelStrings, renderBodyOnly = renderBodyOnly, behaviors = behaviors ) } override fun onClick() = onClick?.invoke() ?: throw WicketRuntimeException("No onClick handler defined for ${javaClass.name} with id=$id") }
apache-2.0
7593e1dfd3e37251de74458f2443c169
30
107
0.677165
4.551971
false
false
false
false
FHannes/intellij-community
java/java-impl/src/com/intellij/codeInsight/hints/JavaInlayParameterHintsProvider.kt
2
3981
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.hints import com.intellij.codeInsight.hints.HintInfo.MethodInfo import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiCallExpression import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod class JavaInlayParameterHintsProvider : InlayParameterHintsProvider { companion object { fun getInstance() = InlayParameterHintsExtension.forLanguage(JavaLanguage.INSTANCE) as JavaInlayParameterHintsProvider } override fun getHintInfo(element: PsiElement): MethodInfo? { if (element is PsiCallExpression) { val resolvedElement = element.resolveMethodGenerics().element if (resolvedElement is PsiMethod) { return getMethodInfo(resolvedElement) } } return null } override fun getParameterHints(element: PsiElement): List<InlayInfo> { if (element is PsiCallExpression) { return JavaInlayHintsProvider.hints(element).toList() } return emptyList() } fun getMethodInfo(method: PsiMethod): MethodInfo? { val containingClass = method.containingClass ?: return null val fullMethodName = StringUtil.getQualifiedName(containingClass.qualifiedName, method.name) val paramNames: List<String> = method.parameterList.parameters.map { it.name ?: "" } return MethodInfo(fullMethodName, paramNames) } override fun getDefaultBlackList() = defaultBlackList private val defaultBlackList = setOf( "(begin*, end*)", "(start*, end*)", "(first*, last*)", "(first*, second*)", "(from*, to*)", "(min*, max*)", "(key, value)", "(format, arg*)", "(message)", "(message, error)", "*Exception", "*.set*(*)", "*.add(*)", "*.set(*,*)", "*.get(*)", "*.create(*)", "*.getProperty(*)", "*.setProperty(*,*)", "*.print(*)", "*.println(*)", "*.append(*)", "*.charAt(*)", "*.indexOf(*)", "*.contains(*)", "*.startsWith(*)", "*.endsWith(*)", "*.equals(*)", "*.equal(*)", "java.lang.Math.*", "org.slf4j.Logger.*", "*.singleton(*)", "*.singletonList(*)", "*.Set.of", "*.ImmutableList.of", "*.ImmutableMultiset.of", "*.ImmutableSortedMultiset.of", "*.ImmutableSortedSet.of", "*.Arrays.asList" ) val isDoNotShowIfMethodNameContainsParameterName = Option("java.method.name.contains.parameter.name", "Do not show if method name contains parameter name", true) val isShowForParamsWithSameType = Option("java.multiple.params.same.type", "Show for non-literals in case of multiple params with the same type", false) val isDoNotShowForBuilderLikeMethods = Option("java.build.like.method", "Do not show for builder-like methods", true) override fun getSupportedOptions(): List<Option> { return listOf( isDoNotShowIfMethodNameContainsParameterName, isShowForParamsWithSameType, isDoNotShowForBuilderLikeMethods ) } }
apache-2.0
49e049ba745c67c39026c6d8cd1b7a29
31.373984
122
0.612158
5.013854
false
false
false
false
misaochan/apps-android-commons
app/src/main/java/fr/free/nrw/commons/utils/DialogUtil.kt
2
4769
package fr.free.nrw.commons.utils import android.app.Activity import android.app.AlertDialog import android.app.Dialog import android.view.View import fr.free.nrw.commons.R import timber.log.Timber object DialogUtil { /** * Shows a dialog safely. * @param activity the activity * @param dialog the dialog to be shown */ private fun showSafely(activity: Activity?, dialog: Dialog?) { if (activity == null || dialog == null) { Timber.d("Show called with null activity / dialog. Ignoring.") return } if (activity.isFinishing || activity.isDestroyed) { Timber.e("Activity is not running. Could not show dialog. ") return } try { dialog.show() } catch (e: IllegalStateException) { Timber.e(e, "Could not show dialog.") } } @JvmStatic fun showAlertDialog( activity: Activity, title: String, message: String, onPositiveBtnClick: Runnable?, onNegativeBtnClick: Runnable? ) { createAndShowDialogSafely( activity = activity, title = title, message = message, positiveButtonText = activity.getString(R.string.yes), negativeButtonText = activity.getString(R.string.no), onPositiveBtnClick = onPositiveBtnClick, onNegativeBtnClick = onNegativeBtnClick ) } @JvmStatic fun showAlertDialog( activity: Activity, title: String, message: String, positiveButtonText: String?, negativeButtonText: String?, onPositiveBtnClick: Runnable?, onNegativeBtnClick: Runnable? ) { createAndShowDialogSafely( activity = activity, title = title, message = message, positiveButtonText = positiveButtonText, negativeButtonText = negativeButtonText, onPositiveBtnClick = onPositiveBtnClick, onNegativeBtnClick = onNegativeBtnClick ) } @JvmStatic fun showAlertDialog( activity: Activity, title: String, message: String, onPositiveBtnClick: Runnable?, onNegativeBtnClick: Runnable?, customView: View?, cancelable: Boolean ) { createAndShowDialogSafely( activity = activity, title = title, message = message, positiveButtonText = activity.getString(R.string.yes), negativeButtonText = activity.getString(R.string.no), onPositiveBtnClick = onPositiveBtnClick, onNegativeBtnClick = onNegativeBtnClick, customView = customView, cancelable = cancelable ) } @JvmStatic fun showAlertDialog( activity: Activity, title: String, message: String, positiveButtonText: String?, onPositiveBtnClick: Runnable?, cancelable: Boolean ) { createAndShowDialogSafely( activity = activity, title = title, message = message, positiveButtonText = positiveButtonText, onPositiveBtnClick = onPositiveBtnClick, cancelable = cancelable ) } /** * show a dialog * @param activity * @param title * @param message * @param positiveButtonText * @param negativeButtonText * @param onPositiveBtnClick * @param onNegativeBtnClick * @param customView * @param cancelable */ private fun createAndShowDialogSafely( activity: Activity, title: String, message: String, positiveButtonText: String? = null, negativeButtonText: String? = null, onPositiveBtnClick: Runnable? = null, onNegativeBtnClick: Runnable? = null, customView: View? = null, cancelable: Boolean = true ) { /* If the custom view already has a parent, there is already a dialog showing with the view * This happens for on resume - return to avoid creating a second dialog - the first one * will still show */ if (customView?.parent != null) { return } showSafely(activity, AlertDialog.Builder(activity).apply { setTitle(title) setMessage(message) setView(customView) setCancelable(cancelable) positiveButtonText?.let { setPositiveButton(it) { _, _ -> onPositiveBtnClick?.run() } } negativeButtonText?.let { setNegativeButton(it) { _, _ -> onNegativeBtnClick?.run() } } }.create()) } }
apache-2.0
b01fb2edca60da35e83dc3e073d210cc
28.621118
99
0.584399
5.252203
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/api/IdListFilter.kt
1
1506
package com.todoroo.astrid.api import android.os.Parcel import android.os.Parcelable import com.google.common.primitives.Longs import com.todoroo.andlib.sql.Join.Companion.left import com.todoroo.andlib.sql.QueryTemplate import com.todoroo.astrid.data.Task import org.tasks.data.Tag class IdListFilter : Filter { private var ids: List<Long?>? = null constructor(ids: List<Long?>) : super("", getQueryTemplate(ids)) { this.ids = ids } private constructor(source: Parcel) { readFromParcel(source) } override fun writeToParcel(dest: Parcel, flags: Int) { super.writeToParcel(dest, flags) dest.writeLongArray(Longs.toArray(ids!!)) } override fun readFromParcel(source: Parcel) { super.readFromParcel(source) val ids = LongArray(source.readInt()) source.setDataPosition(source.dataPosition() - 1) source.readLongArray(ids) this.ids = Longs.asList(*ids) } companion object { @JvmField val CREATOR: Parcelable.Creator<IdListFilter> = object : Parcelable.Creator<IdListFilter> { override fun createFromParcel(source: Parcel) = IdListFilter(source) override fun newArray(size: Int): Array<IdListFilter?> = arrayOfNulls(size) } private fun getQueryTemplate(ids: List<Long?>): QueryTemplate { return QueryTemplate() .join(left(Tag.TABLE, Tag.TASK.eq(Task.ID))) .where(Task.ID.`in`(ids)) } } }
gpl-3.0
69d6bae6071ebb1bbdbf58abe5d93cb3
30.395833
109
0.662019
4.092391
false
false
false
false
didi/DoraemonKit
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/ability/DoKitMcModuleProcessor.kt
1
4124
package com.didichuxing.doraemonkit.kit.mc.ability import android.view.View import com.didichuxing.doraemonkit.DoKit import com.didichuxing.doraemonkit.kit.core.DokitAbility import com.didichuxing.doraemonkit.kit.test.event.monitor.LifecycleEventMonitor import com.didichuxing.doraemonkit.kit.mc.oldui.DoKitMcManager import com.didichuxing.doraemonkit.kit.mc.MultiControlConfig import com.didichuxing.doraemonkit.kit.mc.oldui.client.ClientDoKitView import com.didichuxing.doraemonkit.kit.test.mock.http.DoKitMockInterceptor import com.didichuxing.doraemonkit.kit.mc.oldui.host.HostDoKitView import com.didichuxing.doraemonkit.kit.mc.oldui.record.RecordingDoKitView import com.didichuxing.doraemonkit.kit.test.DoKitTestManager import com.didichuxing.doraemonkit.kit.test.event.monitor.CustomEventMonitor import com.didichuxing.doraemonkit.kit.test.mock.http.DoKitProxyMockInterceptor import com.didichuxing.doraemonkit.kit.test.utils.XposedHookUtil import com.didichuxing.doraemonkit.util.LogHelper import com.didichuxing.doraemonkit.util.SPUtils /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2021/6/7-19:50 * 描 述: * 修订历史: * ================================================ */ class DoKitMcModuleProcessor : DokitAbility.DokitModuleProcessor { override fun values(): Map<String, Any> { return mapOf( "okhttp_interceptor" to DoKitMockInterceptor(), "okhttp_proxy_interceptor" to DoKitProxyMockInterceptor(), "lifecycle" to LifecycleEventMonitor() ) } override fun proceed(actions: Map<String, Any?>?): Map<String, Any> { try { actions?.let { when (actions["action"]) { "launch_host_view" -> { DoKit.launchFloating(HostDoKitView::class) } "launch_client_view" -> { DoKit.launchFloating(ClientDoKitView::class) } "launch_recoding_view" -> { if (DoKitMcManager.IS_MC_RECODING || SPUtils.getInstance() .getBoolean(DoKitMcManager.MC_CASE_RECODING_KEY, false) ) { DoKit.launchFloating(RecordingDoKitView::class) DoKitMcManager.IS_MC_RECODING = true DoKitMcManager.MC_CASE_ID = SPUtils.getInstance().getString(DoKitMcManager.MC_CASE_ID_KEY) } else { } } "mc_mode" -> { val mode = if (DoKitTestManager.isHostMode()) { "host" } else if (DoKitTestManager.isClientMode()) { "client" } else { "unknown" } return mapOf(Pair("mode", mode)) } "mc_custom_event" -> { CustomEventMonitor.onCustomEvent( actions["eventType"] as String, actions["view"] as View?, actions["param"] as Map<String, String>? ) } "global_hook" -> { XposedHookUtil.globalHook() } "dokit_mc_connect_url" -> { val map = mutableMapOf<String, String>() val history = MultiControlConfig.currentConnectHistory map["url"] = history?.url ?: "" } else -> { LogHelper.e("DokitMcModuleProcessor", "not action ${actions["action"]}") } } } } catch (e: Exception) { e.printStackTrace() } return mapOf() } }
apache-2.0
384f44bc9c469aa91db998b0ed7001b7
39.78
96
0.513242
5.040791
false
true
false
false
arturbosch/detekt
detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseCheckNotNullSpec.kt
1
1596
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import org.assertj.core.api.Assertions.assertThat import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object UseCheckNotNullSpec : Spek({ setupKotlinEnvironment() val env: KotlinCoreEnvironment by memoized() val subject by memoized { UseCheckNotNull() } describe("UseCheckNotNull rule") { it("reports `check` calls with a non-null check") { val code = """ fun test(i: Int?) { check(i != null) } """ val actual = subject.compileAndLintWithContext(env, code) assertThat(actual).hasSize(1) } it("reports `check` calls with a non-null check that has `null` on the left side") { val code = """ fun test(i: Int?) { check(null != i) } """ val actual = subject.compileAndLintWithContext(env, code) assertThat(actual).hasSize(1) } it("does not report a `check` call without a non-null check") { val code = """ fun test(i: Int) { check(i > 0) } """ val actual = subject.compileAndLintWithContext(env, code) assertThat(actual).isEmpty() } } })
apache-2.0
ec939e97116954c6eb6d69b7a09151e5
32.957447
92
0.582707
4.680352
false
true
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/GrepTool.kt
1
3898
/* 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.tools import uk.co.nickthecoder.paratask.TaskParser import uk.co.nickthecoder.paratask.gui.DragFilesHelper import uk.co.nickthecoder.paratask.misc.FileTest import uk.co.nickthecoder.paratask.project.Header import uk.co.nickthecoder.paratask.project.HeaderRow import uk.co.nickthecoder.paratask.table.Column import uk.co.nickthecoder.paratask.table.FileNameColumn import uk.co.nickthecoder.paratask.table.NumberColumn import uk.co.nickthecoder.paratask.table.TableResults import uk.co.nickthecoder.paratask.table.filter.RowFilter import uk.co.nickthecoder.paratask.tools.GrepTool.GrepRow import uk.co.nickthecoder.paratask.util.HasDirectory import uk.co.nickthecoder.paratask.util.Stoppable import java.io.File /** * Converts the text output from GrepTask's into a List, so that the results can be displayed as a table. */ class GrepTool : AbstractCommandTool<GrepRow>(), Stoppable, HasDirectory { val grepTask = GrepTask() override val taskD = grepTask.taskD override val directory: File? get() = grepTask.filesP.value.firstOrNull { it?.isDirectory == true } override val rowFilter = RowFilter(this, columns, GrepRow(File(""), 0, "")) init { grepTask.contextLinesP.hidden = true grepTask.additionalOptionsP.hidden = true columns.add(FileNameColumn<GrepRow>("name") { it.file }) columns.add(NumberColumn<GrepRow, Int>("lineNumber", label = "#") { it.lineNumber }) columns.add(Column<GrepRow, String>("line", getter = { it.line })) } override fun createHeader(): Header? { val row1 = HeaderRow() row1.add(grepTask.filesP) val row2 = HeaderRow() row2.add(grepTask.patternsP) row2.add(grepTask.typeP) row2.add(grepTask.matchCaseP) return Header(this, row1, row2) } override fun createCommand() = grepTask.createCommand() override fun processLine(line: String) { val colon1 = line.indexOf(':') val colon2 = line.indexOf(':', colon1 + 1) try { if (colon2 > 0) { val file = File(line.substring(0, colon1)) val lineNumber = parseIntSafely(line.substring(colon1 + 1, colon2)) ?: 0 val matchedLine = line.substring(colon2 + 1) list.add(GrepRow(file, lineNumber, matchedLine)) } } catch (e: Exception) { // Ignore errors from binary matches. // The version of grep I'm using seems to ignore the -I option when recursing. Grr. } } private fun parseIntSafely(str: String): Int? { try { return Integer.parseInt(str) } catch(e: Exception) { return null } } override fun check() { grepTask.check() } override fun createTableResults(): TableResults<GrepRow> { val results = super.createTableResults() results.dragHelper = DragFilesHelper { results.selectedRows().map { it.file } } return results } data class GrepRow(override val file: File, var lineNumber: Int, var line: String) : FileTest } fun main(args: Array<String>) { TaskParser(GrepTool()).go(args) }
gpl-3.0
c829857702a150d9e15b555ad83a9431
32.316239
105
0.682145
3.96945
false
false
false
false
kozalosev/DeskChan-Launcher
src/javafx/kotlin/info/deskchan/launcher/javafx/Logging.kt
1
639
package info.deskchan.launcher.javafx import info.deskchan.launcher.env private object Logger { private val file = env.rootDirPath.resolve("$LAUNCHER_FILENAME.log").toFile() init { // Clears the file at startup. if (file.exists()) { file.writeText("") } } fun log(str: String) = file.appendText("$str${System.lineSeparator()}") } internal fun log(message: String, vararg vars: Any) = Logger.log(message.localize(*vars)) internal fun log(error: Throwable) = Logger.log("! $error") internal fun log(obj: Any?) = Logger.log(obj.toString())
lgpl-3.0
f5cb1028ad6030fe7021602857d45606
25.625
89
0.615023
4.044304
false
false
false
false
nemerosa/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/BranchFavouriteServiceImpl.kt
1
1963
package net.nemerosa.ontrack.service import net.nemerosa.ontrack.model.security.ProjectView import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.Branch import net.nemerosa.ontrack.model.structure.BranchFavouriteService import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.StructureService import net.nemerosa.ontrack.repository.BranchFavouriteRepository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class BranchFavouriteServiceImpl( private val repository: BranchFavouriteRepository, private val securityService: SecurityService, private val structureService: StructureService ) : BranchFavouriteService { override fun getFavouriteBranches(): List<Branch> { val accountId = securityService.currentAccount?.account?.id() return if (accountId != null) { val branches = securityService.asAdmin { repository.getFavouriteBranches(accountId) .map { id -> structureService.getBranch(ID.of(id)) } } branches.filter { securityService.isProjectFunctionGranted(it, ProjectView::class.java) } } else { emptyList() } } override fun isBranchFavourite(branch: Branch): Boolean { val user = securityService.currentAccount return user != null && user.isGranted(branch.projectId(), ProjectView::class.java) && repository.isBranchFavourite(user.account.id(), branch.id()) } override fun setBranchFavourite(branch: Branch, favourite: Boolean) { val user = securityService.currentAccount if (user != null && user.isGranted(branch.projectId(), ProjectView::class.java)) { repository.setBranchFavourite(user.account.id(), branch.id(), favourite) } } }
mit
bc9bcc66efb200f60a460b1377e5cc3d
40.765957
101
0.712175
5.033333
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/ui/adapter/SitemapAdapter.kt
1
7887
package treehou.se.habit.ui.adapter import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import java.util.ArrayList import java.util.HashMap import se.treehou.ng.ohcommunicator.connector.models.OHServer import se.treehou.ng.ohcommunicator.connector.models.OHSitemap import treehou.se.habit.R class SitemapAdapter : RecyclerView.Adapter<SitemapAdapter.SitemapBaseHolder>() { private val items = HashMap<OHServer, SitemapItem>() private var selectorListener: OnSitemapSelectListener? = null class SitemapItem(var server: OHServer) { var state = STATE_LOADING var sitemaps: MutableList<OHSitemap> = ArrayList() fun addItem(sitemap: OHSitemap) { sitemaps.add(sitemap) state = STATE_SUCCESS } companion object { val STATE_SUCCESS = 0 val STATE_LOADING = 1 val STATE_ERROR = 2 } } open inner class SitemapBaseHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var lblServer: TextView init { lblServer = itemView.findViewById<View>(R.id.lbl_server) as TextView } } inner class SitemapHolder(view: View) : SitemapBaseHolder(view) { var lblName: TextView init { lblName = itemView.findViewById<View>(R.id.lbl_sitemap) as TextView } } inner class SitemapErrorHolder(view: View) : SitemapBaseHolder(view) inner class SitemapLoadHolder(view: View) : SitemapBaseHolder(view) inner class GetResult(var item: SitemapItem, var sitemap: OHSitemap?) override fun onCreateViewHolder(parent: ViewGroup, type: Int): SitemapBaseHolder { val inflater = LayoutInflater.from(parent.context) if (SitemapItem.STATE_SUCCESS == type) { val itemView = inflater.inflate(R.layout.item_sitemap, parent, false) return SitemapHolder(itemView) } else if (SitemapItem.STATE_LOADING == type) { val itemView = inflater.inflate(R.layout.item_sitemap_load, parent, false) return SitemapLoadHolder(itemView) } else { val serverLoadFail = inflater.inflate(R.layout.item_sitemap_failed, parent, false) return SitemapErrorHolder(serverLoadFail) } } override fun onBindViewHolder(sitemapHolder: SitemapBaseHolder, position: Int) { val type = getItemViewType(position) val item = getItem(position) if (SitemapItem.STATE_SUCCESS == type) { val holder = sitemapHolder as SitemapHolder val sitemap = item!!.sitemap holder.lblName.text = item.sitemap?.label holder.lblServer.text = item.sitemap?.server?.name sitemapHolder.itemView.setOnClickListener { selectorListener!!.onSitemapSelect(sitemap!!) } } else if (SitemapItem.STATE_LOADING == type) { val holder = sitemapHolder as SitemapLoadHolder holder.lblServer.text = item!!.item.server.name } else if (SitemapItem.STATE_ERROR == type) { val holder = sitemapHolder as SitemapErrorHolder holder.lblServer.text = item!!.item.server.name holder.itemView.setOnClickListener { selectorListener!!.onErrorClicked(item.item.server) } } } interface OnSitemapSelectListener { fun onSitemapSelect(sitemap: OHSitemap) fun onErrorClicked(server: OHServer) } private inner class DummySelectListener : OnSitemapSelectListener { override fun onSitemapSelect(sitemap: OHSitemap) {} override fun onErrorClicked(server: OHServer) {} } override fun getItemViewType(position: Int): Int { var count = 0 for (item in items.values) { if (SitemapItem.STATE_SUCCESS == item.state) { if (position >= count && position < count + item.sitemaps.size) { return SitemapItem.STATE_SUCCESS } count += item.sitemaps.size } else if (SitemapItem.STATE_ERROR == item.state) { if (count == position) { return SitemapItem.STATE_ERROR } count++ } else if (SitemapItem.STATE_LOADING == item.state) { if (count == position) { return SitemapItem.STATE_LOADING } count++ } } return SitemapItem.STATE_LOADING } override fun getItemCount(): Int { var count = 0 for (item in items.values) { if (item.state == SitemapItem.STATE_SUCCESS) { count += item.sitemaps.size } else { count++ } } return count } fun getItem(position: Int): GetResult? { var result: GetResult? = null var count = 0 for (item in items.values) { if (SitemapItem.STATE_SUCCESS == item.state) { for (sitemap in item.sitemaps) { if (count == position) { result = GetResult(item, sitemap) return result } count++ } } else { if (count == position) { result = GetResult(item, null) break } count++ } } return result } fun addAll(sitemaps: List<OHSitemap>) { for (sitemap in sitemaps) { add(sitemap) } } fun add(sitemap: OHSitemap) { var item: SitemapItem? = items[sitemap.server] if (item == null) { item = SitemapItem(sitemap.server) items.put(item.server, item) } val count = itemCount item.addItem(sitemap) Log.d(TAG, "Added sitemap " + sitemap.server.name + " " + sitemap.name + " precount: " + count + " postcount: " + itemCount + " items: " + items.size) notifyDataSetChanged() } fun remove(sitemap: OHSitemap) { val pos = findPosition(sitemap) remove(sitemap, pos) } fun remove(sitemap: OHSitemap, position: Int) { val item = items[sitemap.server] ?: return item.sitemaps.remove(sitemap) notifyItemRemoved(position) } private fun findPosition(pSitemap: OHSitemap): Int { var count = 0 for (item in items.values) { if (SitemapItem.STATE_SUCCESS == item.state) { for (sitemap in item.sitemaps) { if (sitemap === pSitemap) { return count } count++ } } else { count++ } } return -1 } fun setSelectorListener(selectorListener: OnSitemapSelectListener?) { var selectorListener = selectorListener if (selectorListener == null) selectorListener = DummySelectListener() this.selectorListener = selectorListener } fun setServerState(server: OHServer, state: Int) { var item: SitemapItem? = items[server] if (item == null) { item = SitemapItem(server) items.put(server, item) } item.state = state notifyDataSetChanged() } operator fun contains(sitemap: OHSitemap): Boolean { return items.containsKey(sitemap.server) && items[sitemap.server]?.sitemaps!!.contains(sitemap) } fun clear() { val last = items.size - 1 items.clear() notifyItemRangeRemoved(0, last) } companion object { private val TAG = SitemapAdapter::class.java.simpleName } }
epl-1.0
eafbe56e046e0813daaa8d24d03c39a0
30.173913
158
0.582477
4.683492
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/inspections/RsWrongLifetimeParametersNumberInspection.kt
1
1808
package org.rust.ide.inspections import com.intellij.codeInspection.ProblemsHolder import org.rust.lang.core.psi.RsBaseType import org.rust.lang.core.psi.RsRefLikeType import org.rust.lang.core.psi.RsVisitor import org.rust.lang.core.psi.ext.RsGenericDeclaration import org.rust.lang.core.types.lifetimeElidable class RsWrongLifetimeParametersNumberInspection : RsLocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() { override fun visitBaseType(type: RsBaseType) { // Don't apply generic declaration checks to Fn-traits and `Self` if (type.path?.valueParameterList != null) return if (type.path?.cself != null) return val paramsDecl = type.path?.reference?.resolve() as? RsGenericDeclaration ?: return val expectedLifetimes = paramsDecl.typeParameterList?.lifetimeParameterList?.size ?: 0 val actualLifetimes = type.path?.typeArgumentList?.lifetimeList?.size ?: 0 if (expectedLifetimes == actualLifetimes) return if (actualLifetimes == 0 && !type.lifetimeElidable) { holder.registerProblem(type, "Missing lifetime specifier [E0106]") } else if (actualLifetimes > 0) { holder.registerProblem(type, "Wrong number of lifetime parameters: expected $expectedLifetimes, found $actualLifetimes [E0107]") } } override fun visitRefLikeType(type: RsRefLikeType) { if (type.mul == null && !type.lifetimeElidable && type.lifetime == null) { holder.registerProblem(type.and ?: type, "Missing lifetime specifier [E0106]") } } } }
mit
029897db4b4910245ac61c076b5b7b9d
47.864865
148
0.647124
4.795756
false
false
false
false
pushtorefresh/storio
storio-sqlite-annotations-processor/src/main/kotlin/com/pushtorefresh/storio3/sqlite/annotations/processor/generate/PutResolverGenerator.kt
3
5086
package com.pushtorefresh.storio3.sqlite.annotations.processor.generate import com.pushtorefresh.storio3.common.annotations.processor.generate.Common.INDENT import com.pushtorefresh.storio3.common.annotations.processor.generate.Generator import com.pushtorefresh.storio3.sqlite.annotations.processor.introspection.StorIOSQLiteTypeMeta import com.squareup.javapoet.* import javax.lang.model.element.Modifier.PUBLIC private const val SUFFIX = "StorIOSQLitePutResolver" object PutResolverGenerator : Generator<StorIOSQLiteTypeMeta> { override fun generateJavaFile(typeMeta: StorIOSQLiteTypeMeta): JavaFile { val className = ClassName.get(typeMeta.packageName, typeMeta.simpleName) val putResolver = TypeSpec.classBuilder(generateName(typeMeta)) .addJavadoc("Generated resolver for Put Operation.\n") .addModifiers(PUBLIC) .superclass(ParameterizedTypeName.get(ClassName.get("com.pushtorefresh.storio3.sqlite.operations.put", "DefaultPutResolver"), className)) .addMethod(createMapToInsertQueryMethodSpec(typeMeta, className)) .addMethod(createMapToUpdateQueryMethodSpec(typeMeta, className)) .addMethod(createMapToContentValuesMethodSpec(typeMeta, className)) .build() return JavaFile .builder(typeMeta.packageName, putResolver) .indent(INDENT) .build() } private fun createMapToInsertQueryMethodSpec(typeMeta: StorIOSQLiteTypeMeta, className: ClassName): MethodSpec { return MethodSpec.methodBuilder("mapToInsertQuery") .addJavadoc("{@inheritDoc}\n") .addAnnotation(Override::class.java) .addAnnotation(typeMeta.nonNullAnnotationClass) .addModifiers(PUBLIC) .returns(ClassName.get("com.pushtorefresh.storio3.sqlite.queries", "InsertQuery")) .addParameter(ParameterSpec.builder(className, "object") .addAnnotation(typeMeta.nonNullAnnotationClass) .build()) .addCode("""return InsertQuery.builder() $INDENT.table(${"$"}S) $INDENT.build(); """.trimIndent(), typeMeta.storIOType.table) .build() } private fun createMapToUpdateQueryMethodSpec(typeMeta: StorIOSQLiteTypeMeta, className: ClassName): MethodSpec { val where = QueryGenerator.createWhere(typeMeta, "object") return MethodSpec.methodBuilder("mapToUpdateQuery") .addJavadoc("{@inheritDoc}\n") .addAnnotation(Override::class.java) .addAnnotation(typeMeta.nonNullAnnotationClass) .addModifiers(PUBLIC) .returns(ClassName.get("com.pushtorefresh.storio3.sqlite.queries", "UpdateQuery")) .addParameter(ParameterSpec.builder(className, "object") .addAnnotation(typeMeta.nonNullAnnotationClass) .build()) .addCode("""return UpdateQuery.builder() $INDENT.table(${"$"}S) $INDENT.where(${"$"}S) $INDENT.whereArgs(${"$"}L) $INDENT.build(); """.trimIndent(), typeMeta.storIOType.table, where[QueryGenerator.WHERE_CLAUSE], where[QueryGenerator.WHERE_ARGS]) .build() } private fun createMapToContentValuesMethodSpec(typeMeta: StorIOSQLiteTypeMeta, className: ClassName): MethodSpec { val builder = MethodSpec.methodBuilder("mapToContentValues") .addJavadoc("{@inheritDoc}\n") .addAnnotation(Override::class.java) .addAnnotation(typeMeta.nonNullAnnotationClass) .addModifiers(PUBLIC) .returns(ClassName.get("android.content", "ContentValues")) .addParameter(ParameterSpec.builder(className, "object") .addAnnotation(typeMeta.nonNullAnnotationClass) .build()) .addStatement("ContentValues contentValues = new ContentValues(\$L)", typeMeta.columns.size) .addCode("\n") typeMeta.columns.values.forEach { columnMeta -> val ignoreNull = columnMeta.storIOColumn.ignoreNull if (ignoreNull) { builder.beginControlFlow("if (object.\$L != null)", columnMeta.contextAwareName) } builder.addStatement("contentValues.put(\$S, object.\$L)", columnMeta.storIOColumn.name, columnMeta.contextAwareName) if (ignoreNull) builder.endControlFlow() } return builder .addCode("\n") .addStatement("return contentValues") .build() } fun generateName(typeMeta: StorIOSQLiteTypeMeta) = "${typeMeta.simpleName}$SUFFIX" }
apache-2.0
d3ad5860f8e64d8d0b39c7237b0fe929
48.862745
153
0.611679
5.445396
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/person/DeathFragment.kt
1
2067
package ffc.app.person import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import ffc.app.R import ffc.app.util.datetime.toBuddistString import ffc.entity.Lang import ffc.entity.Person import ffc.entity.healthcare.Disease import ffc.entity.healthcare.Icd10 import kotlinx.android.synthetic.main.person_death_info_fragment.personDeathCause import kotlinx.android.synthetic.main.person_death_info_fragment.personDeathDate class DeathFragment : Fragment() { var death: Person.Death? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.person_death_info_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) death?.let { personDeathDate.text = it.date.toBuddistString() with(personDeathCause) { adapter = DeathCauseAdapter(it.causes) layoutManager = LinearLayoutManager(context!!) addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) } } } class DeathCauseAdapter(private val cause: List<Disease>) : RecyclerView.Adapter<LookupViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, type: Int) = LookupViewHolder(parent) override fun getItemCount(): Int = cause.size override fun onBindViewHolder(holder: LookupViewHolder, position: Int) { val icd10 = cause[position] as Icd10 val anotherLang = icd10.translation[Lang.en] ?: icd10.translation[Lang.th] holder.bind(icd10.icd10, icd10.name, anotherLang, if (position == 0) "สาเหตุหลัก" else null) } } }
apache-2.0
8f1b5cf6a7857e4b0ca49c0ed0a1e605
38.365385
116
0.731803
4.135354
false
false
false
false
varpeti/Suli
Android/work/varpe8/homeworks/07/HF07/app/src/main/java/ml/varpeti/hf07/MyCamera.kt
1
1877
package ml.varpeti.hf07 import android.hardware.camera2.CameraCaptureSession import android.hardware.camera2.CameraDevice import android.util.Log import android.view.Surface import android.view.TextureView class MyCamera(private val textureView: TextureView, private val width: Int, private val height: Int) : CameraDevice.StateCallback() { var myCameraDevice : CameraDevice? = null override fun onOpened(camera: CameraDevice) { myCameraDevice = camera // Lementem hogy le tudjam zárni egy függvény hívással val surfaceTexture = textureView.surfaceTexture surfaceTexture.setDefaultBufferSize(width, height) val surface = Surface(surfaceTexture) val captureRequest = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) captureRequest.addTarget(surface) camera.createCaptureSession( listOf(surface), object : CameraCaptureSession.StateCallback() { override fun onConfigureFailed(session: CameraCaptureSession) { Log.i("|||", "onConfigureFailed") } override fun onConfigured(session: CameraCaptureSession) { session.setRepeatingRequest(captureRequest.build(), null, null) } }, null ) } // Hiba vagy kilépés esetén bezárjuk a kamerát override fun onDisconnected(camera: CameraDevice) { camera.close() Log.i("|||", "onDisconnected") } override fun onError(camera: CameraDevice, error: Int) { camera.close() Log.i("|||", "onError") } // onPause fogja hívni. fun close() { if (myCameraDevice!= null) { myCameraDevice!!.close() myCameraDevice = null } } }
unlicense
87993a052a47b8dbdd766ba80a10c622
28.171875
132
0.620043
4.665
false
false
false
false
hummatli/MAHAndroidUpdater
android-app-updater/src/main/java/com/mobapphome/androidappupdater/tools/Updater.kt
1
3326
package com.mobapphome.androidappupdater.tools import android.app.Activity import android.util.Log import com.google.gson.Gson import com.mobapphome.androidappupdater.R import java.io.IOException class Updater { internal var updaterListiner: UpdaterListener? = null var loading = false fun updateProgramList(act: Activity) { Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, "Update info called") Thread(Runnable { synchronized(Updater::class.java) { if (loading) { Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, "Accept_3") Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, "Loading") return@Runnable } loading = true try { Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, "Service requested") var programInfo: ProgramInfo? = null if (AAUpdaterController.urlService != null) { programInfo = HttpTools.requestProgramInfo(AAUpdaterController.urlService) } else if (AAUpdaterController.updateInfoResolver != null) { programInfo = AAUpdaterController.updateInfoResolver?.resolveInfo() } Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, "Program info name = " + programInfo) val gson = Gson() val json = gson.toJson(programInfo) AAUpdaterController.sharedPref!!.edit().putString(Constants.MAH_UPD_PROGRAM_INFO, json).apply() if (updaterListiner != null) { Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, "UpdateListener = $updaterListiner") updaterListiner!!.onResponse(programInfo) } loading = false } catch (e: IOException) { Log.i(Constants.MAH_ANDROID_UPDATER_LOG_TAG, "Accept_6") if (AAUpdaterController.urlService != null) { Log.d(Constants.MAH_ANDROID_UPDATER_LOG_TAG, " " + e.message + "URL = " + AAUpdaterController.urlService, e) } else if (AAUpdaterController.updateInfoResolver != null) { Log.d(Constants.MAH_ANDROID_UPDATER_LOG_TAG, " " + e.message + "updateInfoResolver = " + AAUpdaterController.updateInfoResolver?.javaClass?.simpleName, e) } val resultError = StringBuilder() resultError.append(act.resources.getString( R.string.android_app_upd_internet_update_error)) if (updaterListiner != null) { val gson = Gson() val json = AAUpdaterController.sharedPref?.getString(Constants.MAH_UPD_PROGRAM_INFO, null) val programInfo = gson.fromJson(json, ProgramInfo::class.java) //Bura bax "?: ProgramInfo()" yazmisham. Onun yerinde bashqa shey ola biler. test ucn qoyusham updaterListiner!!.onResponse(programInfo ?: ProgramInfo(), resultError.toString()) } loading = false } } }).start() } }
apache-2.0
42f13d04164fbbcc88283100c9eba325
42.763158
179
0.554119
4.645251
false
false
false
false
fobid/linkable-text-android
linkable-text/src/main/java/com/github/fobid/linkabletext/text/method/LinkableMovementMethod.kt
1
3814
package com.github.fobid.linkabletext.text.method import android.text.Selection import android.text.Spannable import android.text.method.LinkMovementMethod import android.text.style.URLSpan import android.util.Patterns import android.view.MotionEvent import android.widget.TextView import com.github.fobid.linkabletext.view.LinkableCallback import com.github.fobid.linkabletext.widget.LinkableTextView class LinkableMovementMethod( private var linkableCallback: LinkableCallback? = null ) : LinkMovementMethod() { init { if (linkableCallback == null) { linkableCallback = object : LinkableCallback { override fun onMatch(type: Int, value: String) { } } } } override fun onTouchEvent(widget: TextView?, buffer: Spannable?, event: MotionEvent?): Boolean { if (widget == null || buffer == null || event == null) { return super.onTouchEvent(widget, buffer, event) } if (event.action == MotionEvent.ACTION_UP) { var x = event.x.toInt() var y = event.y.toInt() x -= widget.totalPaddingLeft y -= widget.totalPaddingTop x += widget.scrollX y += widget.scrollY val layout = widget.layout val line = layout?.getLineForVertical(y) ?: 0 val off = layout?.getOffsetForHorizontal(line, x.toFloat()) ?: 0 val link = buffer.getSpans(off, off, URLSpan::class.java) if (link.isNotEmpty()) { link.firstOrNull()?.url?.let { url -> handleLink(url) } // Remove selected background Selection.removeSelection(buffer) return true } } return super.onTouchEvent(widget, buffer, event) } private fun handleLink(link: String) { when { link.startsWith(LINKABLE_HASHTAG_SCHEME) -> link.replaceFirst(LINKABLE_HASHTAG_SCHEME, "") .replaceFirst(".*#".toRegex(), "") .let { hashtag -> linkableCallback?.onMatch(LinkableTextView.Link.HASH_TAG, hashtag) } link.startsWith(LINKABLE_MENTION_SCHEME) -> link.replaceFirst(LINKABLE_MENTION_SCHEME, "") .replaceFirst(".*@".toRegex(), "") .let { mention -> linkableCallback?.onMatch(LinkableTextView.Link.MENTION, mention) } link.startsWith(LINKABLE_IP_ADDRESS_SCHEME) -> link.replaceFirst(LINKABLE_IP_ADDRESS_SCHEME, "") .replaceFirst(".".toRegex(), "") .let { ip -> linkableCallback?.onMatch(LinkableTextView.Link.IP_ADDRESS, ip) } Patterns.EMAIL_ADDRESS.matcher(link).matches() -> linkableCallback?.onMatch(LinkableTextView.Link.EMAIL_ADDRESS, link) Patterns.IP_ADDRESS.matcher(link).matches() or Patterns.DOMAIN_NAME.matcher(link).matches() or Patterns.WEB_URL.matcher(link).matches() -> linkableCallback?.onMatch(LinkableTextView.Link.WEB_URL, link) Patterns.PHONE.matcher(link).matches() -> linkableCallback?.onMatch(LinkableTextView.Link.PHONE, link) } } companion object { private const val LINKABLE_BASE_SCHEME = "https://github.com/fobidlim/linkable-text-android" const val LINKABLE_HASHTAG_SCHEME = "$LINKABLE_BASE_SCHEME/hashtag" const val LINKABLE_MENTION_SCHEME = "$LINKABLE_BASE_SCHEME/mention" const val LINKABLE_IP_ADDRESS_SCHEME = "$LINKABLE_BASE_SCHEME/ip" } }
apache-2.0
3836c3875bb9fe746c2ec2e8b5d3f346
36.772277
100
0.581017
4.708642
false
false
false
false
stripe/stripe-android
paymentsheet/src/main/java/com/stripe/android/paymentsheet/flowcontroller/DefaultFlowController.kt
1
25126
package com.stripe.android.paymentsheet.flowcontroller import android.app.Activity import android.content.Context import android.os.Parcelable import androidx.activity.result.ActivityResultCaller import androidx.activity.result.ActivityResultLauncher import androidx.annotation.VisibleForTesting import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelStoreOwner import com.stripe.android.PaymentConfiguration import com.stripe.android.core.injection.ENABLE_LOGGING import com.stripe.android.core.injection.Injectable import com.stripe.android.core.injection.InjectorKey import com.stripe.android.core.injection.NonFallbackInjector import com.stripe.android.core.injection.UIContext import com.stripe.android.core.injection.WeakMapInjectorRegistry import com.stripe.android.googlepaylauncher.GooglePayEnvironment import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncher import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncherContract import com.stripe.android.googlepaylauncher.injection.GooglePayPaymentMethodLauncherFactory import com.stripe.android.link.LinkActivityContract import com.stripe.android.link.LinkActivityResult import com.stripe.android.link.LinkPaymentLauncher import com.stripe.android.link.model.AccountStatus import com.stripe.android.model.ConfirmPaymentIntentParams import com.stripe.android.model.ConfirmSetupIntentParams import com.stripe.android.model.PaymentIntent import com.stripe.android.payments.core.injection.PRODUCT_USAGE import com.stripe.android.payments.paymentlauncher.PaymentLauncherContract import com.stripe.android.payments.paymentlauncher.PaymentResult import com.stripe.android.payments.paymentlauncher.StripePaymentLauncher import com.stripe.android.payments.paymentlauncher.StripePaymentLauncherAssistedFactory import com.stripe.android.paymentsheet.PaymentOptionCallback import com.stripe.android.paymentsheet.PaymentOptionContract import com.stripe.android.paymentsheet.PaymentOptionResult import com.stripe.android.paymentsheet.PaymentOptionsViewModel import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetResult import com.stripe.android.paymentsheet.PaymentSheetResultCallback import com.stripe.android.paymentsheet.addresselement.AddressDetails import com.stripe.android.paymentsheet.addresselement.toConfirmPaymentIntentShipping import com.stripe.android.paymentsheet.addresselement.toIdentifierMap import com.stripe.android.paymentsheet.analytics.EventReporter import com.stripe.android.paymentsheet.extensions.registerPollingAuthenticator import com.stripe.android.paymentsheet.extensions.unregisterPollingAuthenticator import com.stripe.android.paymentsheet.forms.FormViewModel import com.stripe.android.paymentsheet.injection.DaggerFlowControllerComponent import com.stripe.android.paymentsheet.injection.FlowControllerComponent import com.stripe.android.paymentsheet.model.ClientSecret import com.stripe.android.paymentsheet.model.ConfirmStripeIntentParamsFactory import com.stripe.android.paymentsheet.model.PaymentIntentClientSecret import com.stripe.android.paymentsheet.model.PaymentOption import com.stripe.android.paymentsheet.model.PaymentOptionFactory import com.stripe.android.paymentsheet.model.PaymentSelection import com.stripe.android.paymentsheet.model.SavedSelection import com.stripe.android.paymentsheet.model.SetupIntentClientSecret import com.stripe.android.paymentsheet.repositories.CustomerApiRepository import com.stripe.android.paymentsheet.validate import com.stripe.android.ui.core.address.AddressRepository import com.stripe.android.ui.core.forms.resources.LpmRepository import com.stripe.android.ui.core.forms.resources.ResourceRepository import dagger.Lazy import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.first import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.parcelize.Parcelize import java.security.InvalidParameterException import javax.inject.Inject import javax.inject.Named import javax.inject.Provider import javax.inject.Singleton import kotlin.coroutines.CoroutineContext @FlowPreview @Singleton internal class DefaultFlowController @Inject internal constructor( // Properties provided through FlowControllerComponent.Builder private val lifecycleScope: CoroutineScope, lifecycleOwner: LifecycleOwner, private val statusBarColor: () -> Int?, private val paymentOptionFactory: PaymentOptionFactory, private val paymentOptionCallback: PaymentOptionCallback, private val paymentResultCallback: PaymentSheetResultCallback, activityResultCaller: ActivityResultCaller, @InjectorKey private val injectorKey: String, // Properties provided through injection private val flowControllerInitializer: FlowControllerInitializer, private val customerApiRepository: CustomerApiRepository, private val eventReporter: EventReporter, private val viewModel: FlowControllerViewModel, private val paymentLauncherFactory: StripePaymentLauncherAssistedFactory, // even though unused this forces Dagger to initialize it here. private val lpmResourceRepository: ResourceRepository<LpmRepository>, private val addressResourceRepository: ResourceRepository<AddressRepository>, /** * [PaymentConfiguration] is [Lazy] because the client might set publishableKey and * stripeAccountId after creating a [DefaultFlowController]. */ private val lazyPaymentConfiguration: Provider<PaymentConfiguration>, @UIContext private val uiContext: CoroutineContext, @Named(ENABLE_LOGGING) private val enableLogging: Boolean, @Named(PRODUCT_USAGE) private val productUsage: Set<String>, private val googlePayPaymentMethodLauncherFactory: GooglePayPaymentMethodLauncherFactory, private val linkLauncher: LinkPaymentLauncher ) : PaymentSheet.FlowController, NonFallbackInjector { private val paymentOptionActivityLauncher: ActivityResultLauncher<PaymentOptionContract.Args> private val googlePayActivityLauncher: ActivityResultLauncher<GooglePayPaymentMethodLauncherContract.Args> private val linkActivityResultLauncher: ActivityResultLauncher<LinkActivityContract.Args> /** * [FlowControllerComponent] is hold to inject into [Activity]s and created * after [DefaultFlowController]. */ lateinit var flowControllerComponent: FlowControllerComponent private var paymentLauncher: StripePaymentLauncher? = null private val resourceRepositories = listOf(lpmResourceRepository, addressResourceRepository) override var shippingDetails: AddressDetails? get() = viewModel.initData.config?.shippingDetails set(value) { viewModel.initData = viewModel.initData.copy( config = viewModel.initData.config?.copy( shippingDetails = value ) ) } override fun inject(injectable: Injectable<*>) { when (injectable) { is PaymentOptionsViewModel.Factory -> { flowControllerComponent.inject(injectable) } is FormViewModel.Factory -> { flowControllerComponent.inject(injectable) } else -> { throw IllegalArgumentException("invalid Injectable $injectable requested in $this") } } } init { lifecycleOwner.lifecycle.addObserver( object : DefaultLifecycleObserver { override fun onCreate(owner: LifecycleOwner) { paymentLauncher = paymentLauncherFactory.create( { lazyPaymentConfiguration.get().publishableKey }, { lazyPaymentConfiguration.get().stripeAccountId }, activityResultCaller.registerForActivityResult( PaymentLauncherContract(), ::onPaymentResult ) ).also { it.registerPollingAuthenticator() } } override fun onDestroy(owner: LifecycleOwner) { paymentLauncher?.unregisterPollingAuthenticator() paymentLauncher = null } } ) paymentOptionActivityLauncher = activityResultCaller.registerForActivityResult( PaymentOptionContract(), ::onPaymentOptionResult ) googlePayActivityLauncher = activityResultCaller.registerForActivityResult( GooglePayPaymentMethodLauncherContract(), ::onGooglePayResult ) linkActivityResultLauncher = activityResultCaller.registerForActivityResult( LinkActivityContract(), ::onLinkActivityResult ) } override fun configureWithPaymentIntent( paymentIntentClientSecret: String, configuration: PaymentSheet.Configuration?, callback: PaymentSheet.FlowController.ConfigCallback ) { configureInternal( PaymentIntentClientSecret(paymentIntentClientSecret), configuration, callback ) } override fun configureWithSetupIntent( setupIntentClientSecret: String, configuration: PaymentSheet.Configuration?, callback: PaymentSheet.FlowController.ConfigCallback ) { configureInternal( SetupIntentClientSecret(setupIntentClientSecret), configuration, callback ) } private fun configureInternal( clientSecret: ClientSecret, configuration: PaymentSheet.Configuration?, callback: PaymentSheet.FlowController.ConfigCallback ) { try { configuration?.validate() clientSecret.validate() } catch (e: InvalidParameterException) { callback.onConfigured(success = false, e) return } lifecycleScope.launch { val result = flowControllerInitializer.init( clientSecret, configuration ) // Wait until all required resources are loaded before completing initialization. resourceRepositories.forEach { it.waitUntilLoaded() } if (isActive) { dispatchResult(result, callback) } else { callback.onConfigured(false, null) } } } override fun getPaymentOption(): PaymentOption? { return viewModel.paymentSelection?.let { paymentOptionFactory.create(it) } } override fun presentPaymentOptions() { val initData = runCatching { viewModel.initData }.getOrElse { error( "FlowController must be successfully initialized using " + "configureWithPaymentIntent() or configureWithSetupIntent() " + "before calling presentPaymentOptions()" ) } paymentOptionActivityLauncher.launch( PaymentOptionContract.Args( stripeIntent = initData.stripeIntent, paymentMethods = initData.paymentMethods, config = initData.config, isGooglePayReady = initData.isGooglePayReady, newLpm = viewModel.paymentSelection as? PaymentSelection.New, statusBarColor = statusBarColor(), injectorKey = injectorKey, enableLogging = enableLogging, productUsage = productUsage ) ) } override fun confirm() { val initData = runCatching { viewModel.initData }.getOrElse { error( "FlowController must be successfully initialized using " + "configureWithPaymentIntent() or configureWithSetupIntent() " + "before calling confirm()" ) } when (val paymentSelection = viewModel.paymentSelection) { PaymentSelection.GooglePay -> launchGooglePay(initData) PaymentSelection.Link, is PaymentSelection.New.LinkInline -> confirmLink(paymentSelection, initData) else -> confirmPaymentSelection(paymentSelection, initData) } } @VisibleForTesting fun confirmPaymentSelection( paymentSelection: PaymentSelection?, initData: InitData ) { val confirmParamsFactory = ConfirmStripeIntentParamsFactory.createFactory( initData.clientSecret, initData.config?.shippingDetails?.toConfirmPaymentIntentShipping() ) when (paymentSelection) { is PaymentSelection.Saved -> { confirmParamsFactory.create(paymentSelection) } is PaymentSelection.New -> { confirmParamsFactory.create(paymentSelection) } else -> null }?.let { confirmParams -> lifecycleScope.launch { when (confirmParams) { is ConfirmPaymentIntentParams -> { paymentLauncher?.confirm(confirmParams) } is ConfirmSetupIntentParams -> { paymentLauncher?.confirm(confirmParams) } } } } } internal fun onGooglePayResult( googlePayResult: GooglePayPaymentMethodLauncher.Result ) { when (googlePayResult) { is GooglePayPaymentMethodLauncher.Result.Completed -> { runCatching { viewModel.initData }.fold( onSuccess = { initData -> val paymentSelection = PaymentSelection.Saved( googlePayResult.paymentMethod, isGooglePay = true ) viewModel.paymentSelection = paymentSelection confirmPaymentSelection( paymentSelection, initData ) }, onFailure = { eventReporter.onPaymentFailure(PaymentSelection.GooglePay) paymentResultCallback.onPaymentSheetResult( PaymentSheetResult.Failed(it) ) } ) } is GooglePayPaymentMethodLauncher.Result.Failed -> { eventReporter.onPaymentFailure(PaymentSelection.GooglePay) paymentResultCallback.onPaymentSheetResult( PaymentSheetResult.Failed( GooglePayException( googlePayResult.error ) ) ) } is GooglePayPaymentMethodLauncher.Result.Canceled -> { // don't log cancellations as failures paymentResultCallback.onPaymentSheetResult(PaymentSheetResult.Canceled) } } } private fun onLinkActivityResult(result: LinkActivityResult) = onPaymentResult(result.convertToPaymentResult()) private suspend fun dispatchResult( result: FlowControllerInitializer.InitResult, callback: PaymentSheet.FlowController.ConfigCallback ) = withContext(uiContext) { when (result) { is FlowControllerInitializer.InitResult.Success -> { onInitSuccess(result.initData, callback) } is FlowControllerInitializer.InitResult.Failure -> { callback.onConfigured(false, result.throwable) } } } private fun onInitSuccess( initData: InitData, callback: PaymentSheet.FlowController.ConfigCallback ) { eventReporter.onInit(initData.config) when (val savedString = initData.savedSelection) { SavedSelection.GooglePay -> PaymentSelection.GooglePay SavedSelection.Link -> PaymentSelection.Link is SavedSelection.PaymentMethod -> initData.paymentMethods.firstOrNull { it.id == savedString.id }?.let { PaymentSelection.Saved(it) } else -> null }.let { viewModel.paymentSelection = it } viewModel.initData = initData callback.onConfigured(true, null) } @JvmSynthetic internal fun onPaymentOptionResult( paymentOptionResult: PaymentOptionResult? ) { paymentOptionResult?.paymentMethods?.let { viewModel.initData = viewModel.initData.copy(paymentMethods = it) } when (paymentOptionResult) { is PaymentOptionResult.Succeeded -> { val paymentSelection = paymentOptionResult.paymentSelection viewModel.paymentSelection = paymentSelection paymentOptionCallback.onPaymentOption( paymentOptionFactory.create( paymentSelection ) ) } is PaymentOptionResult.Failed, is PaymentOptionResult.Canceled -> { paymentOptionCallback.onPaymentOption( viewModel.paymentSelection?.let { paymentOptionFactory.create(it) } ) } else -> { viewModel.paymentSelection = null paymentOptionCallback.onPaymentOption(null) } } } internal fun onPaymentResult(paymentResult: PaymentResult) { logPaymentResult(paymentResult) lifecycleScope.launch { paymentResultCallback.onPaymentSheetResult( paymentResult.convertToPaymentSheetResult() ) } } private fun logPaymentResult(paymentResult: PaymentResult?) { when (paymentResult) { is PaymentResult.Completed -> { if ((viewModel.paymentSelection as? PaymentSelection.Saved)?.isGooglePay == true) { // Google Pay is treated as a saved PM after confirmation eventReporter.onPaymentSuccess(PaymentSelection.GooglePay) } else { eventReporter.onPaymentSuccess(viewModel.paymentSelection) } } is PaymentResult.Failed -> eventReporter.onPaymentFailure(viewModel.paymentSelection) else -> {} } } private fun confirmLink( paymentSelection: PaymentSelection, initData: InitData ) { val config = requireNotNull(initData.config) lifecycleScope.launch { val shippingDetails: AddressDetails? = config.shippingDetails val customerPhone = if (shippingDetails?.isCheckboxSelected == true) { shippingDetails.phoneNumber } else { config.defaultBillingDetails?.phone } val shippingAddress = if (shippingDetails?.isCheckboxSelected == true) { shippingDetails.toIdentifierMap(config.defaultBillingDetails) } else { null } val customerEmail = config.defaultBillingDetails?.email ?: config.customer?.let { customerApiRepository.retrieveCustomer( it.id, it.ephemeralKeySecret )?.email } val linkConfig = LinkPaymentLauncher.Configuration( stripeIntent = initData.stripeIntent, merchantName = config.merchantDisplayName, customerEmail = customerEmail, customerPhone = customerPhone, customerName = config.defaultBillingDetails?.name, customerBillingCountryCode = config.defaultBillingDetails?.address?.country, shippingValues = shippingAddress ) val accountStatus = linkLauncher.getAccountStatusFlow(linkConfig).first() // If a returning user is paying with a new card inline, launch Link to complete payment (paymentSelection as? PaymentSelection.New.LinkInline)?.takeIf { accountStatus == AccountStatus.Verified }?.linkPaymentDetails?.originalParams?.let { linkLauncher.present(linkConfig, linkActivityResultLauncher, it) } ?: run { if (paymentSelection is PaymentSelection.Link) { // User selected Link as the payment method, not inline linkLauncher.present(linkConfig, linkActivityResultLauncher) } else { // New user paying inline, complete without launching Link confirmPaymentSelection(paymentSelection, initData) } } } } private fun launchGooglePay(initData: InitData) { // initData.config.googlePay is guaranteed not to be null or GooglePay would be disabled val config = requireNotNull(initData.config) val googlePayConfig = requireNotNull(config.googlePay) val googlePayPaymentLauncherConfig = GooglePayPaymentMethodLauncher.Config( environment = when (googlePayConfig.environment) { PaymentSheet.GooglePayConfiguration.Environment.Production -> GooglePayEnvironment.Production else -> GooglePayEnvironment.Test }, merchantCountryCode = googlePayConfig.countryCode, merchantName = config.merchantDisplayName ) googlePayPaymentMethodLauncherFactory.create( lifecycleScope = lifecycleScope, config = googlePayPaymentLauncherConfig, readyCallback = {}, activityResultLauncher = googlePayActivityLauncher, skipReadyCheck = true ).present( currencyCode = (initData.stripeIntent as? PaymentIntent)?.currency ?: googlePayConfig.currencyCode.orEmpty(), amount = (initData.stripeIntent as? PaymentIntent)?.amount?.toInt() ?: 0, transactionId = initData.stripeIntent.id ) } private fun PaymentResult.convertToPaymentSheetResult() = when (this) { is PaymentResult.Completed -> PaymentSheetResult.Completed is PaymentResult.Canceled -> PaymentSheetResult.Canceled is PaymentResult.Failed -> PaymentSheetResult.Failed(throwable) } private fun LinkActivityResult.convertToPaymentResult() = when (this) { is LinkActivityResult.Completed -> PaymentResult.Completed is LinkActivityResult.Canceled -> PaymentResult.Canceled is LinkActivityResult.Failed -> PaymentResult.Failed(error) } class GooglePayException( val throwable: Throwable ) : Exception(throwable) @Parcelize data class Args( val clientSecret: String, val config: PaymentSheet.Configuration? ) : Parcelable companion object { fun getInstance( appContext: Context, viewModelStoreOwner: ViewModelStoreOwner, lifecycleScope: CoroutineScope, lifecycleOwner: LifecycleOwner, activityResultCaller: ActivityResultCaller, statusBarColor: () -> Int?, paymentOptionFactory: PaymentOptionFactory, paymentOptionCallback: PaymentOptionCallback, paymentResultCallback: PaymentSheetResultCallback ): PaymentSheet.FlowController { val injectorKey = WeakMapInjectorRegistry.nextKey( requireNotNull(PaymentSheet.FlowController::class.simpleName) ) val flowControllerComponent = DaggerFlowControllerComponent.builder() .appContext(appContext) .viewModelStoreOwner(viewModelStoreOwner) .lifecycleScope(lifecycleScope) .lifeCycleOwner(lifecycleOwner) .activityResultCaller(activityResultCaller) .statusBarColor(statusBarColor) .paymentOptionFactory(paymentOptionFactory) .paymentOptionCallback(paymentOptionCallback) .paymentResultCallback(paymentResultCallback) .injectorKey(injectorKey) .build() val flowController = flowControllerComponent.flowController flowController.flowControllerComponent = flowControllerComponent WeakMapInjectorRegistry.register(flowController, injectorKey) return flowController } } }
mit
e130347f1a107c979583a081022e92e4
40.530579
100
0.653944
6.231647
false
true
false
false
TeamWizardry/LibrarianLib
buildSrc/src/main/kotlin/com/teamwizardry/gradle/ModuleInfo.kt
1
1175
package com.teamwizardry.gradle import org.gradle.api.Project import org.gradle.api.provider.Property import com.teamwizardry.gradle.util.DslContext import org.gradle.api.tasks.SourceSet import org.gradle.api.tasks.SourceSetContainer import org.gradle.kotlin.dsl.the import com.teamwizardry.gradle.util.LiveCollection open class ModuleInfo(val name: String, private val ctx: DslContext) { val path: String = ":$name" val project: Project = ctx.project.project(":$name") /** * The direct dependencies of this module. (this is populated by the module plugin) */ val dependencies: LiveCollection<ModuleInfo> = LiveCollection(mutableSetOf()) /** * The direct and transitive dependencies of this module */ val allDependencies: LiveCollection<ModuleInfo> = LiveCollection(mutableSetOf()) val modid: String = "liblib-$name" init { dependencies { dep -> // add direct dependencies allDependencies.add(dep) // add all of those dependencies' direct and transitive dependencies dep.allDependencies { allDependencies.add(it) } } } }
lgpl-3.0
8577e45170846b5865d5fe239f8dc68e
30.756757
87
0.685957
4.589844
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/pastry/layers/PastryCheckbox.kt
1
1109
package com.teamwizardry.librarianlib.facade.pastry.layers import com.teamwizardry.librarianlib.facade.layers.SpriteLayer import com.teamwizardry.librarianlib.facade.pastry.PastryTexture import com.teamwizardry.librarianlib.math.Easing import kotlin.math.abs public class PastryCheckbox(posX: Int, posY: Int, radioStyle: Boolean): PastryToggle(posX, posY, 7, 7) { public constructor(posX: Int, posY: Int): this(posX, posY, false) private val sprite = if (radioStyle) PastryTexture.radioButton else PastryTexture.checkbox private val background = SpriteLayer(sprite, 0, 0, 7, 7) override fun visualStateChanged(visualState: Boolean) { val current = background.animationFrame val toggleDuration = 2f val maxFrame = sprite.frameCount - 1 val progress = current.toFloat() / maxFrame if (visualState) { background.animationFrame_im.animate(maxFrame, (1-progress) * toggleDuration) } else { background.animationFrame_im.animate(0, progress * toggleDuration) } } init { this.add(background) } }
lgpl-3.0
6f3b71853534de0e0c6e59f32cfd7b76
36
104
0.713255
4.21673
false
false
false
false
colesadam/hill-lists
app/src/main/java/uk/colessoft/android/hilllist/domain/HillDetail.kt
1
733
package uk.colessoft.android.hilllist.domain import androidx.room.Embedded import androidx.room.Relation import uk.colessoft.android.hilllist.domain.entity.Bagging import uk.colessoft.android.hilllist.domain.entity.Hill import uk.colessoft.android.hilllist.domain.entity.TypeLink data class HillDetail ( @Embedded val hill: Hill ){ @Relation(parentColumn = "h_id", entityColumn = "b_id", entity = Bagging::class) var bagging: List<Bagging>? = null @Relation(parentColumn = "h_id", entityColumn = "hill_id", entity = TypeLink::class, projection = arrayOf("type_Id")) var types: List<Long>? = null }
mit
4abc5fef72482d76176269637a8cd35d
25.178571
59
0.633015
4.005464
false
false
false
false
McGars/basekitk
basekitk/src/main/kotlin/com/mcgars/basekitk/features/base/BaseViewController.kt
1
9927
package com.mcgars.basekitk.features.base import android.content.SharedPreferences import android.content.res.Configuration import android.graphics.drawable.Drawable import android.os.Build import android.os.Bundle import androidx.annotation.CallSuper import androidx.annotation.DrawableRes import androidx.annotation.LayoutRes import androidx.annotation.StringRes import com.google.android.material.appbar.AppBarLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.tabs.TabLayout import androidx.core.view.ViewCompat import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.mcgars.basekitk.R import com.mcgars.basekitk.features.decorators.DecoratorListener import com.mcgars.basekitk.tools.LoaderController import com.mcgars.basekitk.tools.colorAttr import com.mcgars.basekitk.tools.find import com.mcgars.basekitk.tools.hideKeyboard import com.mcgars.basekitk.tools.pagecontroller.PageController import com.mcgars.basekitk.tools.visible /** * Created by gars on 29.12.2016. */ abstract class BaseViewController(args: Bundle? = null) : Controller(args) { val decorators = mutableListOf<DecoratorListener>() /** * Disable call [ViewCompat.setFitsSystemWindows] */ var isFitSystem = true /** * Если в разметке есть тулбар то автоматически подхватится * по умолчанию id=R.id.toolbar * но можно переопределить id с помощью метода getToolbarId() * @return [Toolbar] */ var toolbar: Toolbar? = null get() { if (field != null) return field if (parentController != null) { return (parentController as BaseViewController).toolbar } return null } private set(value) { field = value if (value != null) { (activity as AppCompatActivity).setSupportActionBar(value) } } /** * Если в разметке есть табы то автоматически подхватится * по умолчанию id=R.id.tabs * но можно переопределить id с помощью метода getToolbarId() */ var tabs: TabLayout? = null private set get() { field?.visible() return field } /** * Run page in new Activity without create new Activity */ val pageController: PageController get() = (activity as BaseKitActivity).pageController /** * Loader blocking ui when show */ val loader: LoaderController by lazy { LoaderController(view as? ViewGroup) } /** * Settings for all app */ val settings: SharedPreferences get() = (activity as BaseKitActivity).settings /** * If is false then [getLayoutId] wraps by [CoordinatorLayout] * and added[getToolbarLayout] */ open var isCustomLayout = false /* * trigger when page ready to work */ private val readyDecorator = object : DecoratorListener() { override fun postCreateView(controller: Controller, view: View) { setTitle() onReady(view) } } init { // find toolbar and tabs addDecorator(object : DecoratorListener() { override fun onViewCreated(view: View) { if (getContainerLayout() != 0) { toolbar = view.find<Toolbar>(R.id.toolbar) } tabs = view.find(R.id.tablayout) } }) } /** * Layout of the page */ @LayoutRes protected abstract fun getLayoutId(): Int /** * Call when view is ready to work */ protected abstract fun onReady(view: View) /** * Set title manually */ fun setTitle(title: String) { activity?.title = title } /** * Title from resources */ @StringRes protected open fun getTitleInt() = 0 /** * Show page to user */ open fun loadPage(viewController: Controller, backStack: Boolean = true) { (activity as BaseKitActivity).loadPage(viewController, backStack) } open fun checkPermission(permission: String, listener: ((allow: Boolean) -> Unit)) { (activity as BaseKitActivity).checkPermission(permission, listener) } /** * Add extention decorator who modified current page's view */ fun <D : DecoratorListener> addDecorator(decoratorListener: D): D { addLifecycleListener(decoratorListener) decorators.add(decoratorListener) return decoratorListener } /** * Show home arrow in toolbar * by default if backstack > 2 then back arrow show automatically * but you can disable auto set arrow just change [BaseKitActivity.alwaysArrow] */ open fun setHomeArrow(arrow: Boolean) { var parentController = parentController while (parentController != null) { if (parentController.parentController == null) break parentController = parentController.parentController } (parentController as? BaseViewController)?.setHomeArrow(arrow) } /** * Change home up indicator in toolbar */ open fun setUpIndicator(@DrawableRes drawable: Int) { if (activity is AppCompatActivity) { (activity as AppCompatActivity).supportActionBar?.setHomeAsUpIndicator(drawable) } } /** * Change home up indicator in toolbar */ open fun setUpIndicator(drawable: Drawable) { if (activity is AppCompatActivity) { (activity as AppCompatActivity).supportActionBar?.setHomeAsUpIndicator(drawable) } } /** * Layout with toolbar */ @LayoutRes protected open fun getContainerLayout() = R.layout.basekit_view_container final override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val v: View = if (isCustomLayout) { inflater.inflate(getLayoutId(), container, false) } else { buildView(inflater, container) } decorators.forEach { it.onViewCreated(v) } addDecorator(readyDecorator) return v } /** * Set title from [getTitleInt] or [getTitle] */ protected open fun setTitle() { var parentController = parentController while (parentController != null) { if (parentController is BaseViewController && (parentController.getTitle() != null || parentController.getTitleInt() != 0)) { return } parentController = parentController.parentController } // set title getTitle()?.let { title -> activity?.title = title } ?: getTitleInt().let { title -> if (title != 0) activity?.setTitle(title) } } /** * Custom title */ protected open fun getTitle(): String? = null override fun onChangeStarted(changeHandler: ControllerChangeHandler, changeType: ControllerChangeType) { // if use ControllerChangeHandler.removesFromViewOnPush() == false // then onCreateOptionMenu fired in page with which user carried out // and in toolbar falls into not needed items // so when change started we hide menu and when change ended show menu // if in setHasOptionsMenu() setted true setOptionsMenuHidden(true) if (changeType == ControllerChangeType.PUSH_EXIT) { activity.hideKeyboard() } } @CallSuper override fun onChangeEnded(changeHandler: ControllerChangeHandler, changeType: ControllerChangeType) { if (changeType == ControllerChangeType.PUSH_ENTER || changeType == ControllerChangeType.POP_ENTER) { // show menu if in setHasOptionsMenu() setted true setOptionsMenuHidden(false) } } open fun onConfigurationChanged(newConfig: Configuration) { childRouters.forEach { childRouter -> childRouter.backstack.forEach { transition -> val controller = transition.controller() if (controller is BaseViewController) { controller.onConfigurationChanged(newConfig) } } } } override fun onDestroy() { super.onDestroy() decorators.clear() } private fun buildView(inflater: LayoutInflater, container: ViewGroup): View { val coordinator = inflater.inflate(getContainerLayout(), container, false) as ViewGroup // add content view val layoutView = inflater.inflate(getLayoutId(), coordinator, false) fillBackgroundColor(layoutView) coordinator.addView(layoutView) // attach scroll behavior for app bar (layoutView.layoutParams as CoordinatorLayout.LayoutParams).let { layoutParams -> if (layoutParams.behavior == null) layoutParams.behavior = AppBarLayout.ScrollingViewBehavior() } if (isFitSystem && Build.VERSION.SDK_INT >= 21) { coordinator.fitsSystemWindows = true } return coordinator } private fun fillBackgroundColor(v: View) { if (v.background != null) return val backgroundColor = v.context.colorAttr(android.R.attr.windowBackground) if (backgroundColor != 0) { v.setBackgroundColor(backgroundColor) } } }
apache-2.0
933282d3a3a1c9c2c02f984b6708ee57
29.920635
108
0.640004
4.898893
false
false
false
false
Soya93/Extract-Refactoring
plugins/settings-repository/src/IcsManager.kt
1
10212
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.configurationStore.StateStorageManagerImpl import com.intellij.configurationStore.StreamProvider import com.intellij.ide.ApplicationLoadListener import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectLifecycleListener import com.intellij.openapi.util.AtomicNotNullLazyValue import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SingleAlarm import com.intellij.util.SystemProperties import com.intellij.util.exists import com.intellij.util.move import org.jetbrains.keychain.CredentialsStore import org.jetbrains.keychain.FileCredentialsStore import org.jetbrains.keychain.OsXCredentialsStore import org.jetbrains.keychain.isOSXCredentialsStoreSupported import org.jetbrains.settingsRepository.git.GitRepositoryManager import org.jetbrains.settingsRepository.git.GitRepositoryService import org.jetbrains.settingsRepository.git.processChildren import java.io.InputStream import java.nio.file.Path import java.nio.file.Paths import kotlin.properties.Delegates internal const val PLUGIN_NAME: String = "Settings Repository" internal val LOG: Logger = Logger.getInstance(IcsManager::class.java) val icsManager by lazy(LazyThreadSafetyMode.NONE) { ApplicationLoadListener.EP_NAME.findExtension(IcsApplicationLoadListener::class.java).icsManager } class IcsManager(dir: Path) { val credentialsStore = object : AtomicNotNullLazyValue<CredentialsStore>() { override fun compute(): CredentialsStore { if (isOSXCredentialsStoreSupported && SystemProperties.getBooleanProperty("ics.use.osx.keychain", true)) { try { return OsXCredentialsStore("IntelliJ Platform Settings Repository") } catch (e: Throwable) { LOG.error(e) } } return FileCredentialsStore(dir.resolve(".git_auth")) } } val settingsFile = dir.resolve("config.json") val settings: IcsSettings val repositoryManager: RepositoryManager = GitRepositoryManager(credentialsStore, dir.resolve("repository")) init { try { settings = loadSettings(settingsFile) } catch (e: Exception) { settings = IcsSettings() LOG.error(e) } } val readOnlySourcesManager = ReadOnlySourcesManager(settings, dir) val repositoryService: RepositoryService = GitRepositoryService() private val commitAlarm = SingleAlarm(Runnable { ProgressManager.getInstance().run(object : Task.Backgroundable(null, icsMessage("task.commit.title")) { override fun run(indicator: ProgressIndicator) { try { repositoryManager.commit(indicator, fixStateIfCannotCommit = false) } catch (e: Throwable) { LOG.error(e) } } }) }, settings.commitDelay) private @Volatile var autoCommitEnabled = true @Volatile var repositoryActive = false internal val autoSyncManager = AutoSyncManager(this) private val syncManager = SyncManager(this, autoSyncManager) private fun scheduleCommit() { if (autoCommitEnabled && !ApplicationManager.getApplication()!!.isUnitTestMode) { commitAlarm.cancelAndRequest() } } inner class ApplicationLevelProvider : IcsStreamProvider(null) { override fun delete(fileSpec: String, roamingType: RoamingType) { if (syncManager.writeAndDeleteProhibited) { throw IllegalStateException("Delete is prohibited now") } repositoryManager.delete(toRepositoryPath(fileSpec, roamingType)) scheduleCommit() } } // private inner class ProjectLevelProvider(projectId: String) : IcsStreamProvider(projectId) { // override fun isAutoCommit(fileSpec: String, roamingType: RoamingType) = !isProjectOrModuleFile(fileSpec) // // override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean { // if (isProjectOrModuleFile(fileSpec)) { // // applicable only if file was committed to Settings Server explicitly // return repositoryManager.has(buildPath(fileSpec, roamingType, this.projectId)) // } // return settings.shareProjectWorkspace || fileSpec != StoragePathMacros.WORKSPACE_FILE // } // } fun sync(syncType: SyncType, project: Project? = null, localRepositoryInitializer: (() -> Unit)? = null) = syncManager.sync(syncType, project, localRepositoryInitializer) private fun cancelAndDisableAutoCommit() { if (autoCommitEnabled) { autoCommitEnabled = false commitAlarm.cancel() } } fun runInAutoCommitDisabledMode(task: ()->Unit) { cancelAndDisableAutoCommit() try { task() } finally { autoCommitEnabled = true repositoryActive = repositoryManager.isRepositoryExists() } } fun beforeApplicationLoaded(application: Application) { repositoryActive = repositoryManager.isRepositoryExists() (application.stateStore.stateStorageManager as StateStorageManagerImpl).streamProvider = ApplicationLevelProvider() autoSyncManager.registerListeners(application) application.messageBus.connect().subscribe(ProjectLifecycleListener.TOPIC, object : ProjectLifecycleListener.Adapter() { override fun beforeProjectLoaded(project: Project) { if (project.isDefault) { return } //registerProjectLevelProviders(project) autoSyncManager.registerListeners(project) } override fun afterProjectClosed(project: Project) { autoSyncManager.autoSync() } }) } open inner class IcsStreamProvider(protected val projectId: String?) : StreamProvider { override val enabled: Boolean get() = repositoryActive override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) { val fullPath = toRepositoryPath(path, roamingType, null) // first of all we must load read-only schemes - scheme could be overridden if bundled or read-only, so, such schemes must be loaded first for (repository in readOnlySourcesManager.repositories) { repository.processChildren(fullPath, filter, { name, input -> processor(name, input, true) }) } repositoryManager.processChildren(fullPath, filter, { name, input -> processor(name, input, false) }) } override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { if (syncManager.writeAndDeleteProhibited) { throw IllegalStateException("Save is prohibited now") } if (doSave(fileSpec, content, size, roamingType) && isAutoCommit(fileSpec, roamingType)) { scheduleCommit() } } fun doSave(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) = repositoryManager.write(toRepositoryPath(fileSpec, roamingType, projectId), content, size) protected open fun isAutoCommit(fileSpec: String, roamingType: RoamingType): Boolean = true override fun read(fileSpec: String, roamingType: RoamingType): InputStream? { return repositoryManager.read(toRepositoryPath(fileSpec, roamingType, projectId)) } override fun delete(fileSpec: String, roamingType: RoamingType) { } } } class IcsApplicationLoadListener : ApplicationLoadListener { var icsManager: IcsManager by Delegates.notNull() private set override fun beforeApplicationLoaded(application: Application, configPath: String) { if (application.isUnitTestMode) { return } val customPath = System.getProperty("ics.settingsRepository") val pluginSystemDir = if (customPath == null) Paths.get(configPath, "settingsRepository") else Paths.get(FileUtil.expandUserHome(customPath)) icsManager = IcsManager(pluginSystemDir) if (!pluginSystemDir.exists()) { try { val oldPluginDir = Paths.get(PathManager.getSystemPath(), "settingsRepository") if (oldPluginDir.exists()) { oldPluginDir.move(pluginSystemDir) } } catch (e: Throwable) { LOG.error(e) } } val repositoryManager = icsManager.repositoryManager if (repositoryManager.isRepositoryExists() && repositoryManager is GitRepositoryManager) { if (repositoryManager.renameDirectory(linkedMapOf( Pair("\$ROOT_CONFIG$", null), Pair("_mac/\$ROOT_CONFIG$", "_mac"), Pair("_windows/\$ROOT_CONFIG$", "_windows"), Pair("_linux/\$ROOT_CONFIG$", "_linux"), Pair("_freebsd/\$ROOT_CONFIG$", "_freebsd"), Pair("_unix/\$ROOT_CONFIG$", "_unix"), Pair("_unknown/\$ROOT_CONFIG$", "_unknown"), Pair("\$APP_CONFIG$", null), Pair("_mac/\$APP_CONFIG$", "_mac"), Pair("_windows/\$APP_CONFIG$", "_windows"), Pair("_linux/\$APP_CONFIG$", "_linux"), Pair("_freebsd/\$APP_CONFIG$", "_freebsd"), Pair("_unix/\$APP_CONFIG$", "_unix"), Pair("_unknown/\$APP_CONFIG$", "_unknown") ))) { // schedule push to avoid merge conflicts application.invokeLater({ icsManager.autoSyncManager.autoSync(force = true) }) } } icsManager.beforeApplicationLoaded(application) } }
apache-2.0
44f437ca7e71f4675ab280fcccd8cf4d
36.410256
186
0.723756
4.812441
false
true
false
false
robohorse/RoboPOJOGenerator
core/src/main/kotlin/com/robohorse/robopojogenerator/delegates/EnvironmentDelegate.kt
1
1821
package com.robohorse.robopojogenerator.delegates import com.intellij.ide.projectView.ProjectView import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.robohorse.robopojogenerator.errors.PathException import com.robohorse.robopojogenerator.models.ProjectModel interface EnvironmentDelegate { fun obtainProjectModel(event: AnActionEvent): ProjectModel fun refreshProject(projectModel: ProjectModel) } internal class EnvironmentDelegateImpl : EnvironmentDelegate { override fun obtainProjectModel(event: AnActionEvent): ProjectModel { val directory = checkPath(event) val project = event.project as Project val virtualFolder = event.getData(LangDataKeys.VIRTUAL_FILE) as VirtualFile val packageName = ProjectRootManager .getInstance(project) .fileIndex .getPackageNameByDirectory(virtualFolder) return ProjectModel( directory = directory, packageName = packageName, project = project, virtualFolder = virtualFolder ) } override fun refreshProject(projectModel: ProjectModel) { ProjectView.getInstance(projectModel.project).refresh() projectModel.virtualFolder.refresh(false, true) } private fun checkPath(event: AnActionEvent): PsiDirectory { val pathItem = event.getData(CommonDataKeys.NAVIGATABLE) return when (pathItem) { is PsiDirectory -> pathItem else -> throw PathException() } } }
mit
efc0d8d26fd176c9a97577bf52fd4f89
36.163265
83
0.737507
5.419643
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/translations/lang/LangRenameInputValidator.kt
1
971
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.lang import com.demonwav.mcdev.translations.lang.gen.psi.LangEntry import com.intellij.openapi.project.Project import com.intellij.patterns.ElementPattern import com.intellij.patterns.PlatformPatterns import com.intellij.psi.PsiElement import com.intellij.refactoring.rename.RenameInputValidatorEx import com.intellij.util.ProcessingContext class LangRenameInputValidator : RenameInputValidatorEx { override fun isInputValid(newName: String, element: PsiElement, context: ProcessingContext) = !newName.contains('=') override fun getPattern(): ElementPattern<out PsiElement> = PlatformPatterns.psiElement(LangEntry::class.java) override fun getErrorMessage(newName: String, project: Project) = if (newName.contains('=')) "Key must not contain separator character ('=')" else null }
mit
a4e5474e69ebefa29dcd1cb6fa273602
33.678571
120
0.783728
4.413636
false
false
false
false
inorichi/tachiyomi-extensions
src/all/batoto/src/eu/kanade/tachiyomi/extension/all/batoto/BatoTo.kt
1
34158
package eu.kanade.tachiyomi.extension.all.batoto import com.squareup.duktape.Duktape import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonPrimitive import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import uy.kohesive.injekt.injectLazy import java.util.Calendar import java.util.concurrent.TimeUnit open class BatoTo( override val lang: String, private val siteLang: String ) : ParsedHttpSource() { override val name: String = "Bato.to" override val baseUrl: String = "https://bato.to" override val supportsLatest = true private val json: Json by injectLazy() override val client: OkHttpClient = network.cloudflareClient.newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build() override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/browse?langs=$siteLang&sort=update&page=$page") } override fun latestUpdatesSelector(): String { return when (siteLang) { "" -> "div#series-list div.col" "en" -> "div#series-list div.col.no-flag" else -> "div#series-list div.col:has([data-lang=\"$siteLang\"])" } } override fun latestUpdatesFromElement(element: Element): SManga { val manga = SManga.create() val item = element.select("a.item-cover") val imgurl = item.select("img").attr("abs:src") manga.setUrlWithoutDomain(item.attr("href")) manga.title = element.select("a.item-title").text() manga.thumbnail_url = imgurl return manga } override fun latestUpdatesNextPageSelector() = "div#mainer nav.d-none .pagination .page-item:last-of-type:not(.disabled)" override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/browse?langs=$siteLang&sort=views_w&page=$page") } override fun popularMangaSelector() = latestUpdatesSelector() override fun popularMangaFromElement(element: Element) = latestUpdatesFromElement(element) override fun popularMangaNextPageSelector() = latestUpdatesNextPageSelector() override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return when { query.startsWith("ID:") -> { val id = query.substringAfter("ID:") client.newCall(GET("$baseUrl/series/$id", headers)).asObservableSuccess() .map { response -> queryIDParse(response, id) } } query.isNotBlank() -> { val url = "$baseUrl/search?word=$query&page=$page" client.newCall(GET(url, headers)).asObservableSuccess() .map { response -> queryParse(response) } } else -> { val sortFilter = filters.findInstance<SortFilter>()!! val reverseSortFilter = filters.findInstance<ReverseSortFilter>()!! val statusFilter = filters.findInstance<StatusFilter>()!! val langFilter = filters.findInstance<LangGroupFilter>()!! val originFilter = filters.findInstance<OriginGroupFilter>()!! val genreFilter = filters.findInstance<GenreGroupFilter>()!! val minChapterFilter = filters.findInstance<MinChapterTextFilter>()!! val maxChapterFilter = filters.findInstance<MaxChapterTextFilter>()!! val url = "$baseUrl/browse".toHttpUrlOrNull()!!.newBuilder() url.addQueryParameter("page", page.toString()) with(langFilter) { if (this.selected.isEmpty()) { url.addQueryParameter("langs", siteLang) } else { val selection = "${this.selected.joinToString(",")},$siteLang" url.addQueryParameter("langs", selection) } } with(genreFilter) { url.addQueryParameter( "genres", included.joinToString(",") + "|" + excluded.joinToString(",") ) } with(statusFilter) { url.addQueryParameter("release", this.selected) } with(sortFilter) { if (reverseSortFilter.state) { url.addQueryParameter("sort", "${this.selected}.az") } else { url.addQueryParameter("sort", "${this.selected}.za") } } if (originFilter.selected.isNotEmpty()) { url.addQueryParameter("origs", originFilter.selected.joinToString(",")) } if (maxChapterFilter.state.isNotEmpty() or minChapterFilter.state.isNotEmpty()) { url.addQueryParameter("chapters", minChapterFilter.state + "-" + maxChapterFilter.state) } client.newCall(GET(url.build().toString(), headers)).asObservableSuccess() .map { response -> queryParse(response) } } } } private fun queryIDParse(response: Response, id: String): MangasPage { val document = response.asJsoup() val infoElement = document.select("div#mainer div.container-fluid") val manga = SManga.create() manga.title = infoElement.select("h3").text() manga.thumbnail_url = document.select("div.attr-cover img") .attr("abs:src") manga.url = infoElement.select("h3 a").attr("abs:href") return MangasPage(listOf(manga), false) } private fun queryParse(response: Response): MangasPage { val mangas = mutableListOf<SManga>() val document = response.asJsoup() document.select(latestUpdatesSelector()).forEach { element -> mangas.add(latestUpdatesFromElement(element)) } val nextPage = document.select(latestUpdatesNextPageSelector()).first() != null return MangasPage(mangas, nextPage) } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw UnsupportedOperationException("Not used") override fun searchMangaSelector() = throw UnsupportedOperationException("Not used") override fun searchMangaFromElement(element: Element) = throw UnsupportedOperationException("Not used") override fun searchMangaNextPageSelector() = throw UnsupportedOperationException("Not used") override fun mangaDetailsRequest(manga: SManga): Request { if (manga.url.startsWith("http")) { return GET(manga.url, headers) } return super.mangaDetailsRequest(manga) } override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div#mainer div.container-fluid") val manga = SManga.create() val genres = mutableListOf<String>() val status = infoElement.select("div.attr-item:contains(status) span").text() infoElement.select("div.attr-item:contains(genres) span").text().split( " / " .toRegex() ).forEach { element -> genres.add(element) } manga.title = infoElement.select("h3").text() manga.author = infoElement.select("div.attr-item:contains(author) a:first-child").text() manga.artist = infoElement.select("div.attr-item:contains(author) a:last-child").text() manga.status = parseStatus(status) manga.genre = infoElement.select(".attr-item b:contains(genres) + span ").joinToString { it.text() } manga.description = infoElement.select("h5:contains(summary) + pre").text() manga.thumbnail_url = document.select("div.attr-cover img") .attr("abs:src") return manga } private fun parseStatus(status: String?) = when { status == null -> SManga.UNKNOWN status.contains("Ongoing") -> SManga.ONGOING status.contains("Completed") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListRequest(manga: SManga): Request { if (manga.url.startsWith("http")) { return GET(manga.url, headers) } return super.chapterListRequest(manga) } override fun chapterListSelector() = "div.main div.p-2" override fun chapterFromElement(element: Element): SChapter { val chapter = SChapter.create() val urlElement = element.select("a.chapt") val group = element.select("div.extra > a:not(.ps-3)").text() val time = element.select("div.extra > i.ps-3").text() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.text() if (group != "") { chapter.scanlator = group } if (time != "") { chapter.date_upload = parseChapterDate(time) } return chapter } private fun parseChapterDate(date: String): Long { val value = date.split(' ')[0].toInt() return when { "secs" in date -> Calendar.getInstance().apply { add(Calendar.SECOND, value * -1) }.timeInMillis "mins" in date -> Calendar.getInstance().apply { add(Calendar.MINUTE, value * -1) }.timeInMillis "hours" in date -> Calendar.getInstance().apply { add(Calendar.HOUR_OF_DAY, value * -1) }.timeInMillis "days" in date -> Calendar.getInstance().apply { add(Calendar.DATE, value * -1) }.timeInMillis "weeks" in date -> Calendar.getInstance().apply { add(Calendar.DATE, value * 7 * -1) }.timeInMillis "months" in date -> Calendar.getInstance().apply { add(Calendar.MONTH, value * -1) }.timeInMillis "years" in date -> Calendar.getInstance().apply { add(Calendar.YEAR, value * -1) }.timeInMillis "sec" in date -> Calendar.getInstance().apply { add(Calendar.SECOND, value * -1) }.timeInMillis "min" in date -> Calendar.getInstance().apply { add(Calendar.MINUTE, value * -1) }.timeInMillis "hour" in date -> Calendar.getInstance().apply { add(Calendar.HOUR_OF_DAY, value * -1) }.timeInMillis "day" in date -> Calendar.getInstance().apply { add(Calendar.DATE, value * -1) }.timeInMillis "week" in date -> Calendar.getInstance().apply { add(Calendar.DATE, value * 7 * -1) }.timeInMillis "month" in date -> Calendar.getInstance().apply { add(Calendar.MONTH, value * -1) }.timeInMillis "year" in date -> Calendar.getInstance().apply { add(Calendar.YEAR, value * -1) }.timeInMillis else -> { return 0 } } } override fun pageListRequest(chapter: SChapter): Request { if (chapter.url.startsWith("http")) { return GET(chapter.url, headers) } return super.pageListRequest(chapter) } override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() val script = document.select("script").html() if (script.contains("var images =")) { /* * During kotlinx.serialization migration, the pre-existing code seemed to not work * Could not find a case where code would run in practice, so it was commented out. */ throw RuntimeException("Unexpected Branch: Please File A Bug Report describing this issue") // val imgJson = json.parseToJsonElement(script.substringAfter("var images = ").substringBefore(";")).jsonObject // imgJson.keys.forEachIndexed { i, s -> pages.add(Page(i, imageUrl = imgJson[s]!!.jsonPrimitive.content)) } } else if (script.contains("const server =")) { // bato.to val duktape = Duktape.create() val encryptedServer = script.substringAfter("const server = ").substringBefore(";") val batojs = duktape.evaluate(script.substringAfter("const batojs = ").substringBefore(";")).toString() val decryptScript = cryptoJS + "CryptoJS.AES.decrypt($encryptedServer, \"$batojs\").toString(CryptoJS.enc.Utf8);" val server = duktape.evaluate(decryptScript).toString().replace("\"", "") duktape.close() json.parseToJsonElement(script.substringAfter("const images = ").substringBefore(";")).jsonArray .forEachIndexed { i, it -> val imgUrl = it.jsonPrimitive.content if (script.contains("bato.to/images")) { pages.add(Page(i, imageUrl = imgUrl)) } else { pages.add(Page(i, imageUrl = if (server.startsWith("http")) "${server}$imgUrl" else "https:${server}$imgUrl")) } } } return pages } private val cryptoJS by lazy { client.newCall( GET( "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js", headers ) ).execute().body!!.string() } override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used") override fun getFilterList() = FilterList( // LetterFilter(), Filter.Header("NOTE: Ignored if using text search!"), Filter.Separator(), SortFilter(getSortFilter(), 5), StatusFilter(getStatusFilter(), 0), GenreGroupFilter(getGenreFilter()), OriginGroupFilter(getOrginFilter()), LangGroupFilter(getLangFilter()), MinChapterTextFilter(), MaxChapterTextFilter(), ReverseSortFilter(), ) class SelectFilterOption(val name: String, val value: String) class CheckboxFilterOption(val value: String, name: String, default: Boolean = false) : Filter.CheckBox(name, default) class TriStateFilterOption(val value: String, name: String, default: Int = 0) : Filter.TriState(name, default) abstract class SelectFilter(name: String, private val options: List<SelectFilterOption>, default: Int = 0) : Filter.Select<String>(name, options.map { it.name }.toTypedArray(), default) { val selected: String get() = options[state].value } abstract class CheckboxGroupFilter(name: String, options: List<CheckboxFilterOption>) : Filter.Group<CheckboxFilterOption>(name, options) { val selected: List<String> get() = state.filter { it.state }.map { it.value } } abstract class TriStateGroupFilter(name: String, options: List<TriStateFilterOption>) : Filter.Group<TriStateFilterOption>(name, options) { val included: List<String> get() = state.filter { it.isIncluded() }.map { it.value } val excluded: List<String> get() = state.filter { it.isExcluded() }.map { it.value } } abstract class TextFilter(name: String) : Filter.Text(name) class SortFilter(options: List<SelectFilterOption>, default: Int) : SelectFilter("Sort By", options, default) class ReverseSortFilter(default: Boolean = false) : Filter.CheckBox("Revers Sort", default) class StatusFilter(options: List<SelectFilterOption>, default: Int) : SelectFilter("Status", options, default) class OriginGroupFilter(options: List<CheckboxFilterOption>) : CheckboxGroupFilter("Origin", options) class GenreGroupFilter(options: List<TriStateFilterOption>) : TriStateGroupFilter("Genre", options) class MinChapterTextFilter : TextFilter("Min. Chapters") class MaxChapterTextFilter : TextFilter("Max. Chapters") class LangGroupFilter(options: List<CheckboxFilterOption>) : CheckboxGroupFilter("Languages", options) class LetterFilter(default: Boolean = false) : Filter.CheckBox("Letter matching mode (Slow)", default) private fun getSortFilter() = listOf( SelectFilterOption("Z-A", "title"), SelectFilterOption("Last Updated", "update"), SelectFilterOption("Newest Added", "create"), SelectFilterOption("Most Views Totally", "views_a"), SelectFilterOption("Most Views 365 days", "views_y"), SelectFilterOption("Most Views 30 days", "views_m"), SelectFilterOption("Most Views 7 days", "views_w"), SelectFilterOption("Most Views 24 hours", "views_d"), SelectFilterOption("Most Views 60 minutes", "views_h"), ) private fun getStatusFilter() = listOf( SelectFilterOption("All", ""), SelectFilterOption("Pending", "pending"), SelectFilterOption("Ongoing", "ongoing"), SelectFilterOption("Completed", "completed"), SelectFilterOption("Hiatus", "hiatus"), SelectFilterOption("Cancelled", "cancelled"), ) private fun getOrginFilter() = listOf( // Values exported from publish.bato.to CheckboxFilterOption("zh", "Chinese"), CheckboxFilterOption("en", "English"), CheckboxFilterOption("ja", "Japanese"), CheckboxFilterOption("ko", "Korean"), CheckboxFilterOption("af", "Afrikaans"), CheckboxFilterOption("sq", "Albanian"), CheckboxFilterOption("am", "Amharic"), CheckboxFilterOption("ar", "Arabic"), CheckboxFilterOption("hy", "Armenian"), CheckboxFilterOption("az", "Azerbaijani"), CheckboxFilterOption("be", "Belarusian"), CheckboxFilterOption("bn", "Bengali"), CheckboxFilterOption("bs", "Bosnian"), CheckboxFilterOption("bg", "Bulgarian"), CheckboxFilterOption("my", "Burmese"), CheckboxFilterOption("km", "Cambodian"), CheckboxFilterOption("ca", "Catalan"), CheckboxFilterOption("ceb", "Cebuano"), CheckboxFilterOption("zh_hk", "Chinese (Cantonese)"), CheckboxFilterOption("zh_tw", "Chinese (Traditional)"), CheckboxFilterOption("hr", "Croatian"), CheckboxFilterOption("cs", "Czech"), CheckboxFilterOption("da", "Danish"), CheckboxFilterOption("nl", "Dutch"), CheckboxFilterOption("en_us", "English (United States)"), CheckboxFilterOption("eo", "Esperanto"), CheckboxFilterOption("et", "Estonian"), CheckboxFilterOption("fo", "Faroese"), CheckboxFilterOption("fil", "Filipino"), CheckboxFilterOption("fi", "Finnish"), CheckboxFilterOption("fr", "French"), CheckboxFilterOption("ka", "Georgian"), CheckboxFilterOption("de", "German"), CheckboxFilterOption("el", "Greek"), CheckboxFilterOption("gn", "Guarani"), CheckboxFilterOption("gu", "Gujarati"), CheckboxFilterOption("ht", "Haitian Creole"), CheckboxFilterOption("ha", "Hausa"), CheckboxFilterOption("he", "Hebrew"), CheckboxFilterOption("hi", "Hindi"), CheckboxFilterOption("hu", "Hungarian"), CheckboxFilterOption("is", "Icelandic"), CheckboxFilterOption("ig", "Igbo"), CheckboxFilterOption("id", "Indonesian"), CheckboxFilterOption("ga", "Irish"), CheckboxFilterOption("it", "Italian"), CheckboxFilterOption("jv", "Javanese"), CheckboxFilterOption("kn", "Kannada"), CheckboxFilterOption("kk", "Kazakh"), CheckboxFilterOption("ku", "Kurdish"), CheckboxFilterOption("ky", "Kyrgyz"), CheckboxFilterOption("lo", "Laothian"), CheckboxFilterOption("lv", "Latvian"), CheckboxFilterOption("lt", "Lithuanian"), CheckboxFilterOption("lb", "Luxembourgish"), CheckboxFilterOption("mk", "Macedonian"), CheckboxFilterOption("mg", "Malagasy"), CheckboxFilterOption("ms", "Malay"), CheckboxFilterOption("ml", "Malayalam"), CheckboxFilterOption("mt", "Maltese"), CheckboxFilterOption("mi", "Maori"), CheckboxFilterOption("mr", "Marathi"), CheckboxFilterOption("mo", "Moldavian"), CheckboxFilterOption("mn", "Mongolian"), CheckboxFilterOption("ne", "Nepali"), CheckboxFilterOption("no", "Norwegian"), CheckboxFilterOption("ny", "Nyanja"), CheckboxFilterOption("ps", "Pashto"), CheckboxFilterOption("fa", "Persian"), CheckboxFilterOption("pl", "Polish"), CheckboxFilterOption("pt", "Portuguese"), CheckboxFilterOption("pt_br", "Portuguese (Brazil)"), CheckboxFilterOption("ro", "Romanian"), CheckboxFilterOption("rm", "Romansh"), CheckboxFilterOption("ru", "Russian"), CheckboxFilterOption("sm", "Samoan"), CheckboxFilterOption("sr", "Serbian"), CheckboxFilterOption("sh", "Serbo-Croatian"), CheckboxFilterOption("st", "Sesotho"), CheckboxFilterOption("sn", "Shona"), CheckboxFilterOption("sd", "Sindhi"), CheckboxFilterOption("si", "Sinhalese"), CheckboxFilterOption("sk", "Slovak"), CheckboxFilterOption("sl", "Slovenian"), CheckboxFilterOption("so", "Somali"), CheckboxFilterOption("es", "Spanish"), CheckboxFilterOption("es_419", "Spanish (Latin America)"), CheckboxFilterOption("sw", "Swahili"), CheckboxFilterOption("sv", "Swedish"), CheckboxFilterOption("tg", "Tajik"), CheckboxFilterOption("ta", "Tamil"), CheckboxFilterOption("th", "Thai"), CheckboxFilterOption("ti", "Tigrinya"), CheckboxFilterOption("to", "Tonga"), CheckboxFilterOption("tr", "Turkish"), CheckboxFilterOption("tk", "Turkmen"), CheckboxFilterOption("uk", "Ukrainian"), CheckboxFilterOption("ur", "Urdu"), CheckboxFilterOption("uz", "Uzbek"), CheckboxFilterOption("vi", "Vietnamese"), CheckboxFilterOption("yo", "Yoruba"), CheckboxFilterOption("zu", "Zulu"), CheckboxFilterOption("_t", "Other"), ) private fun getGenreFilter() = listOf( TriStateFilterOption("artbook", "Artbook"), TriStateFilterOption("cartoon", "Cartoon"), TriStateFilterOption("comic", "Comic"), TriStateFilterOption("doujinshi", "Doujinshi"), TriStateFilterOption("imageset", "Imageset"), TriStateFilterOption("manga", "Manga"), TriStateFilterOption("manhua", "Manhua"), TriStateFilterOption("manhwa", "Manhwa"), TriStateFilterOption("webtoon", "Webtoon"), TriStateFilterOption("western", "Western"), TriStateFilterOption("josei", "Josei"), TriStateFilterOption("seinen", "Seinen"), TriStateFilterOption("shoujo", "Shoujo"), TriStateFilterOption("shoujo_ai", "Shoujo ai"), TriStateFilterOption("shounen", "Shounen"), TriStateFilterOption("shounen_ai", "Shounen ai"), TriStateFilterOption("yaoi", "Yaoi"), TriStateFilterOption("yuri", "Yuri"), TriStateFilterOption("ecchi", "Ecchi"), TriStateFilterOption("mature", "Mature"), TriStateFilterOption("adult", "Adult"), TriStateFilterOption("gore", "Gore"), TriStateFilterOption("violence", "Violence"), TriStateFilterOption("smut", "Smut"), TriStateFilterOption("hentai", "Hentai"), TriStateFilterOption("_4_koma", "4-Koma"), TriStateFilterOption("action", "Action"), TriStateFilterOption("adaptation", "Adaptation"), TriStateFilterOption("adventure", "Adventure"), TriStateFilterOption("aliens", "Aliens"), TriStateFilterOption("animals", "Animals"), TriStateFilterOption("anthology", "Anthology"), TriStateFilterOption("cars", "cars"), TriStateFilterOption("comedy", "Comedy"), TriStateFilterOption("cooking", "Cooking"), TriStateFilterOption("crime", "crime"), TriStateFilterOption("crossdressing", "Crossdressing"), TriStateFilterOption("delinquents", "Delinquents"), TriStateFilterOption("dementia", "Dementia"), TriStateFilterOption("demons", "Demons"), TriStateFilterOption("drama", "Drama"), TriStateFilterOption("fantasy", "Fantasy"), TriStateFilterOption("fan_colored", "Fan-Colored"), TriStateFilterOption("full_color", "Full Color"), TriStateFilterOption("game", "Game"), TriStateFilterOption("gender_bender", "Gender Bender"), TriStateFilterOption("genderswap", "Genderswap"), TriStateFilterOption("ghosts", "Ghosts"), TriStateFilterOption("gyaru", "Gyaru"), TriStateFilterOption("harem", "Harem"), TriStateFilterOption("harlequin", "Harlequin"), TriStateFilterOption("historical", "Historical"), TriStateFilterOption("horror", "Horror"), TriStateFilterOption("incest", "Incest"), TriStateFilterOption("isekai", "Isekai"), TriStateFilterOption("kids", "Kids"), TriStateFilterOption("loli", "Loli"), TriStateFilterOption("lolicon", "lolicon"), TriStateFilterOption("magic", "Magic"), TriStateFilterOption("magical_girls", "Magical Girls"), TriStateFilterOption("martial_arts", "Martial Arts"), TriStateFilterOption("mecha", "Mecha"), TriStateFilterOption("medical", "Medical"), TriStateFilterOption("military", "Military"), TriStateFilterOption("monster_girls", "Monster Girls"), TriStateFilterOption("monsters", "Monsters"), TriStateFilterOption("music", "Music"), TriStateFilterOption("mystery", "Mystery"), TriStateFilterOption("netorare", "Netorare/NTR"), TriStateFilterOption("ninja", "Ninja"), TriStateFilterOption("office_workers", "Office Workers"), TriStateFilterOption("oneshot", "Oneshot"), TriStateFilterOption("parody", "parody"), TriStateFilterOption("philosophical", "Philosophical"), TriStateFilterOption("police", "Police"), TriStateFilterOption("post_apocalyptic", "Post-Apocalyptic"), TriStateFilterOption("psychological", "Psychological"), TriStateFilterOption("reincarnation", "Reincarnation"), TriStateFilterOption("reverse_harem", "Reverse Harem"), TriStateFilterOption("romance", "Romance"), TriStateFilterOption("samurai", "Samurai"), TriStateFilterOption("school_life", "School Life"), TriStateFilterOption("sci_fi", "Sci-Fi"), TriStateFilterOption("shota", "Shota"), TriStateFilterOption("shotacon", "shotacon"), TriStateFilterOption("slice_of_life", "Slice of Life"), TriStateFilterOption("sm_bdsm", "SM/BDSM"), TriStateFilterOption("space", "Space"), TriStateFilterOption("sports", "Sports"), TriStateFilterOption("super_power", "Super Power"), TriStateFilterOption("superhero", "Superhero"), TriStateFilterOption("supernatural", "Supernatural"), TriStateFilterOption("survival", "Survival"), TriStateFilterOption("thriller", "Thriller"), TriStateFilterOption("time_travel", "Time Travel"), TriStateFilterOption("traditional_games", "Traditional Games"), TriStateFilterOption("tragedy", "Tragedy"), TriStateFilterOption("vampires", "Vampires"), TriStateFilterOption("video_games", "Video Games"), TriStateFilterOption("virtual_reality", "Virtual Reality"), TriStateFilterOption("wuxia", "Wuxia"), TriStateFilterOption("xianxia", "Xianxia"), TriStateFilterOption("xuanhuan", "Xuanhuan"), TriStateFilterOption("zombies", "Zombies"), // Hidden Genres TriStateFilterOption("award_winning", "Award Winning"), TriStateFilterOption("youkai", "Youkai"), TriStateFilterOption("uncategorized", "Uncategorized") ) private fun getLangFilter() = listOf( // Values exported from publish.bato.to CheckboxFilterOption("en", "English"), CheckboxFilterOption("ar", "Arabic"), CheckboxFilterOption("bg", "Bulgarian"), CheckboxFilterOption("zh", "Chinese"), CheckboxFilterOption("cs", "Czech"), CheckboxFilterOption("da", "Danish"), CheckboxFilterOption("nl", "Dutch"), CheckboxFilterOption("fil", "Filipino"), CheckboxFilterOption("fi", "Finnish"), CheckboxFilterOption("fr", "French"), CheckboxFilterOption("de", "German"), CheckboxFilterOption("el", "Greek"), CheckboxFilterOption("he", "Hebrew"), CheckboxFilterOption("hi", "Hindi"), CheckboxFilterOption("hu", "Hungarian"), CheckboxFilterOption("id", "Indonesian"), CheckboxFilterOption("it", "Italian"), CheckboxFilterOption("ja", "Japanese"), CheckboxFilterOption("ko", "Korean"), CheckboxFilterOption("ms", "Malay"), CheckboxFilterOption("pl", "Polish"), CheckboxFilterOption("pt", "Portuguese"), CheckboxFilterOption("pt_br", "Portuguese (Brazil)"), CheckboxFilterOption("ro", "Romanian"), CheckboxFilterOption("ru", "Russian"), CheckboxFilterOption("es", "Spanish"), CheckboxFilterOption("es_419", "Spanish (Latin America)"), CheckboxFilterOption("sv", "Swedish"), CheckboxFilterOption("th", "Thai"), CheckboxFilterOption("tr", "Turkish"), CheckboxFilterOption("uk", "Ukrainian"), CheckboxFilterOption("vi", "Vietnamese"), CheckboxFilterOption("af", "Afrikaans"), CheckboxFilterOption("sq", "Albanian"), CheckboxFilterOption("am", "Amharic"), CheckboxFilterOption("hy", "Armenian"), CheckboxFilterOption("az", "Azerbaijani"), CheckboxFilterOption("be", "Belarusian"), CheckboxFilterOption("bn", "Bengali"), CheckboxFilterOption("bs", "Bosnian"), CheckboxFilterOption("my", "Burmese"), CheckboxFilterOption("km", "Cambodian"), CheckboxFilterOption("ca", "Catalan"), CheckboxFilterOption("ceb", "Cebuano"), CheckboxFilterOption("zh_hk", "Chinese (Cantonese)"), CheckboxFilterOption("zh_tw", "Chinese (Traditional)"), CheckboxFilterOption("hr", "Croatian"), CheckboxFilterOption("en_us", "English (United States)"), CheckboxFilterOption("eo", "Esperanto"), CheckboxFilterOption("et", "Estonian"), CheckboxFilterOption("fo", "Faroese"), CheckboxFilterOption("ka", "Georgian"), CheckboxFilterOption("gn", "Guarani"), CheckboxFilterOption("gu", "Gujarati"), CheckboxFilterOption("ht", "Haitian Creole"), CheckboxFilterOption("ha", "Hausa"), CheckboxFilterOption("is", "Icelandic"), CheckboxFilterOption("ig", "Igbo"), CheckboxFilterOption("ga", "Irish"), CheckboxFilterOption("jv", "Javanese"), CheckboxFilterOption("kn", "Kannada"), CheckboxFilterOption("kk", "Kazakh"), CheckboxFilterOption("ku", "Kurdish"), CheckboxFilterOption("ky", "Kyrgyz"), CheckboxFilterOption("lo", "Laothian"), CheckboxFilterOption("lv", "Latvian"), CheckboxFilterOption("lt", "Lithuanian"), CheckboxFilterOption("lb", "Luxembourgish"), CheckboxFilterOption("mk", "Macedonian"), CheckboxFilterOption("mg", "Malagasy"), CheckboxFilterOption("ml", "Malayalam"), CheckboxFilterOption("mt", "Maltese"), CheckboxFilterOption("mi", "Maori"), CheckboxFilterOption("mr", "Marathi"), CheckboxFilterOption("mo", "Moldavian"), CheckboxFilterOption("mn", "Mongolian"), CheckboxFilterOption("ne", "Nepali"), CheckboxFilterOption("no", "Norwegian"), CheckboxFilterOption("ny", "Nyanja"), CheckboxFilterOption("ps", "Pashto"), CheckboxFilterOption("fa", "Persian"), CheckboxFilterOption("rm", "Romansh"), CheckboxFilterOption("sm", "Samoan"), CheckboxFilterOption("sr", "Serbian"), CheckboxFilterOption("sh", "Serbo-Croatian"), CheckboxFilterOption("st", "Sesotho"), CheckboxFilterOption("sn", "Shona"), CheckboxFilterOption("sd", "Sindhi"), CheckboxFilterOption("si", "Sinhalese"), CheckboxFilterOption("sk", "Slovak"), CheckboxFilterOption("sl", "Slovenian"), CheckboxFilterOption("so", "Somali"), CheckboxFilterOption("sw", "Swahili"), CheckboxFilterOption("tg", "Tajik"), CheckboxFilterOption("ta", "Tamil"), CheckboxFilterOption("ti", "Tigrinya"), CheckboxFilterOption("to", "Tonga"), CheckboxFilterOption("tk", "Turkmen"), CheckboxFilterOption("ur", "Urdu"), CheckboxFilterOption("uz", "Uzbek"), CheckboxFilterOption("yo", "Yoruba"), CheckboxFilterOption("zu", "Zulu"), CheckboxFilterOption("_t", "Other"), // Lang options from bato.to brows not in publish.bato.to CheckboxFilterOption("eu", "Basque"), CheckboxFilterOption("pt-PT", "Portuguese (Portugal)"), ).filterNot { it.value == siteLang } private inline fun <reified T> Iterable<*>.findInstance() = find { it is T } as? T }
apache-2.0
ba96aa522b22671d77bdece4591bb74f
45.284553
191
0.622431
4.638512
false
false
false
false
getsenic/nuimo-android
nuimo/src/main/kotlin/com/senic/nuimo/NuimoController.kt
1
2769
/* * Copyright (c) 2015 Senic. All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.senic.nuimo import java.util.* abstract class NuimoController(address: String) { companion object { @JvmField val OPTION_IGNORE_DUPLICATES = 1 shl 0 @JvmField val OPTION_WITH_ONION_SKINNING_FADE_IN = 1 shl 1 @JvmField val OPTION_WITHOUT_WRITE_RESPONSE = 1 shl 2 } val address: String = address var defaultMatrixDisplayInterval = 2.0 var connectionState = NuimoConnectionState.DISCONNECTED protected set var batteryPercentage: Int? = null protected set var firmwareVersion: String? = null protected set var hardwareVersion: String? = null protected set var color: String? = null protected set private val listeners = ArrayList<NuimoControllerListener>() abstract fun connect() abstract fun disconnect() fun displayLedMatrix(matrix: NuimoLedMatrix) { displayLedMatrix(matrix, defaultMatrixDisplayInterval, 0) } fun displayLedMatrix(matrix: NuimoLedMatrix, displayInterval: Double) { displayLedMatrix(matrix, displayInterval, 0) } fun displayLedMatrix(matrix: NuimoLedMatrix, options: Int) { displayLedMatrix(matrix, defaultMatrixDisplayInterval, options) } abstract fun displayLedMatrix(matrix: NuimoLedMatrix, displayInterval: Double, options: Int) fun addControllerListener(controllerListener: NuimoControllerListener) { listeners.add(controllerListener) } fun removeControllerListener(controllerListener: NuimoControllerListener) { listeners.remove(controllerListener) } /** * Calls "event" lambda on every listener. It does so by copying the list of listeners before to * avoid ConcurrentModificationExceptions that occur if the actual listener tries to modify the * listeners. */ protected fun notifyListeners(event: (listener: NuimoControllerListener) -> Unit) { ArrayList(listeners).forEach { event(it) } } } interface NuimoControllerListener { fun onConnect() {} fun onFailToConnect() {} fun onDisconnect() {} fun onLedMatrixWrite() {} fun onGestureEvent(event: NuimoGestureEvent) {} fun onBatteryPercentageChange(batteryPercentage: Int) {} } abstract class BaseNuimoControllerListener: NuimoControllerListener { override fun onConnect() {} override fun onDisconnect() {} override fun onLedMatrixWrite() {} override fun onGestureEvent(event: NuimoGestureEvent) {} override fun onBatteryPercentageChange(batteryPercentage: Int) {} }
mit
4745a331ade2fbe5d62f3ee647428469
30.11236
100
0.704948
4.615
false
false
false
false
java-opengl-labs/learn-OpenGL
src/main/kotlin/learnOpenGL/a_gettingStarted/5.1 transformations.kt
1
6697
package learnOpenGL.a_gettingStarted /** * Created by GBarbieri on 25.04.2017. */ import glm_.mat4x4.Mat4 import glm_.vec2.Vec2 import glm_.vec3.Vec3 import gln.draw.glDrawElements import gln.get import gln.glClearColor import gln.glf.semantic import gln.program.usingProgram import gln.texture.glTexImage2D import gln.texture.plus import gln.uniform.glUniform import gln.vertexArray.glBindVertexArray import gln.vertexArray.glVertexAttribPointer import learnOpenGL.common.flipY import learnOpenGL.common.readImage import learnOpenGL.common.toBuffer import org.lwjgl.opengl.EXTABGR import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL12.GL_BGR import org.lwjgl.opengl.GL13.GL_TEXTURE0 import org.lwjgl.opengl.GL13.glActiveTexture import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.glEnableVertexAttribArray import org.lwjgl.opengl.GL20.glGetUniformLocation import org.lwjgl.opengl.GL30.* import uno.buffer.destroyBuf import uno.buffer.intBufferBig import uno.buffer.use import uno.glfw.glfw import uno.glsl.Program import uno.glsl.glDeleteProgram import uno.glsl.glUseProgram fun main(args: Array<String>) { with(Transformations()) { run() end() } } private class Transformations { val window = initWindow("Transformations") val program = ProgramA() enum class Buffer { Vertex, Element } val buffers = intBufferBig<Buffer>() val vao = intBufferBig(1) val vertices = floatArrayOf( // positions | texture coords +0.5f, +0.5f, 0f, 1f, 1f, // top right +0.5f, -0.5f, 0f, 1f, 0f, // bottom right -0.5f, -0.5f, 0f, 0f, 0f, // bottom left -0.5f, +0.5f, 0f, 0f, 1f // top left ) val indices = intArrayOf( 0, 1, 3, // first triangle 1, 2, 3 // second triangle ) enum class Texture { A, B } val textures = intBufferBig<Texture>() inner class ProgramA : Program("shaders/a/_5_1", "transform.vert", "transform.frag") { val transform = glGetUniformLocation(name, "transform") // get matrix's uniform location init { usingProgram(name) { "textureA".unitE = Texture.A "textureB".unitE = Texture.B } } } init { // set up vertex data (and buffer(s)) and configure vertex attributes glGenVertexArrays(vao) glGenBuffers(buffers) // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(vao) glBindBuffer(GL_ARRAY_BUFFER, buffers[Buffer.Vertex]) glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[Buffer.Element]) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW) // position attribute glVertexAttribPointer(semantic.attr.POSITION, Vec3.length, GL_FLOAT, false, Vec3.size + Vec2.size, 0) glEnableVertexAttribArray(semantic.attr.POSITION) // texture coord attribute glVertexAttribPointer(semantic.attr.TEX_COORD, Vec2.length, GL_FLOAT, false, Vec3.size + Vec2.size, Vec3.size) glEnableVertexAttribArray(semantic.attr.TEX_COORD) // load and create a texture glGenTextures(textures) // texture A glBindTexture(GL_TEXTURE_2D, textures[Texture.A]) // set the texture wrapping parameters to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) // load image, create texture and generate mipmaps var image = readImage("textures/container.jpg").flipY() image.toBuffer().use { glTexImage2D(GL_RGB, image.width, image.height, GL_BGR, GL_UNSIGNED_BYTE, it) glGenerateMipmap(GL_TEXTURE_2D) } // texture B glBindTexture(GL_TEXTURE_2D, textures[Texture.B]) // set the texture wrapping parameters to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) // load image, create texture and generate mipmaps image = readImage("textures/awesomeface.png").flipY() image.toBuffer().use { glTexImage2D(GL_RGB, image.width, image.height, EXTABGR.GL_ABGR_EXT, GL_UNSIGNED_BYTE, it) glGenerateMipmap(GL_TEXTURE_2D) } /* You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. */ //glBindVertexArray() } fun run() { while (window.open) { window.processInput() // render glClearColor(clearColor) glClear(GL_COLOR_BUFFER_BIT) // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0 + Texture.A) glBindTexture(GL_TEXTURE_2D, textures[Texture.A]) glActiveTexture(GL_TEXTURE0 + Texture.B) glBindTexture(GL_TEXTURE_2D, textures[Texture.B]) // create transformations val transform = Mat4() .translate(0.5f, -0.5f, 0f) .rotate(glfw.time, 0f, 0f, 1f) glUseProgram(program) // set matrix glUniform(program.transform, transform) /* you may use also use "transform".location.mat4 = transform or program.transform.mat4 = transform */ // render container glBindVertexArray(vao) glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT) window.swapAndPoll() } } fun end() { // optional: de-allocate all resources once they've outlived their purpose: glDeleteProgram(program) glDeleteVertexArrays(vao) glDeleteBuffers(buffers) glDeleteTextures(textures) destroyBuf(vao, buffers, textures) window.end() } }
mit
d9568fdfb18cb6ab8375ae879ebedcf1
31.995074
125
0.646857
4.00778
false
false
false
false
inorichi/tachiyomi-extensions
src/en/manhwamanga/src/eu/kanade/tachiyomi/extension/en/manhwamanga/ManhwaManga.kt
1
7503
package eu.kanade.tachiyomi.extension.en.manhwamanga import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Request import okhttp3.RequestBody import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element @Nsfw class ManhwaManga : ParsedHttpSource() { override val name = "ManhwaManga.net" override val baseUrl = "https://manhwamanga.net" override val lang = "en" override val supportsLatest = true override fun popularMangaSelector() = ".home-truyendecu" override fun latestUpdatesSelector() = popularMangaSelector() override fun searchMangaSelector() = popularMangaSelector() override fun chapterListSelector() = "#list-chapter > div.row > div > ul > li:nth-child(n)" override fun popularMangaNextPageSelector() = "li.active+li a[data-page]" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/most-views/page/$page", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/latest-updates/page/$page", headers) } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return if (query.isNotBlank()) { GET("$baseUrl/?s=$query", headers) } else { val url = "$baseUrl/category/".toHttpUrlOrNull()!!.newBuilder() filters.forEach { filter -> when (filter) { is GenreFilter -> url.addPathSegment(filter.toUriPart()) } } url.addPathSegment("page") url.addPathSegment("$page") GET(url.toString(), headers) } } override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.setUrlWithoutDomain(element.select("a").attr("href")) manga.title = element.select("a").attr("title") manga.thumbnail_url = element.select("a img").attr("src") return manga } override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element) protected fun getXhrChapters(mangaId: String): Document { val xhrHeaders = headersBuilder().add("Content-Type: application/x-www-form-urlencoded; charset=UTF-8") .build() val body = RequestBody.create(null, "action=tw_ajax&type=list_chap&id=$mangaId") return client.newCall(POST("$baseUrl/wp-admin/admin-ajax.php", xhrHeaders, body)).execute().asJsoup() } override fun chapterListParse(response: Response): List<SChapter> { val document = response.asJsoup() val dataIdSelector = "input[id^=id_post]" return getXhrChapters(document.select(dataIdSelector).attr("value")).select("option").map { chapterFromElement(it) }.reversed() } override fun chapterFromElement(element: Element): SChapter { val chapter = SChapter.create() element.let { urlElement -> chapter.setUrlWithoutDomain(urlElement.attr("value")) chapter.name = urlElement.text() } chapter.date_upload = 0 return chapter } override fun mangaDetailsParse(document: Document) = SManga.create().apply { title = document.select("h3.title").text() description = document.select("div.desc-text > p").text() thumbnail_url = document.select("div.books > div > img").attr("src") author = document.select("div.info > div:nth-child(1) > a").attr("title") genre = document.select("div.info > div:nth-child(2) > a").joinToString { it.text() } status = document.select("div.info > div:nth-child(3) > span").text().let { when { it.contains("Ongoing") -> SManga.ONGOING it.contains("Completed") -> SManga.COMPLETED else -> SManga.UNKNOWN } } } override fun pageListParse(document: Document): List<Page> = mutableListOf<Page>().apply { document.select(".chapter_beta_content p img").forEachIndexed { index, element -> add(Page(index, "", element.attr("src"))) } } override fun imageUrlRequest(page: Page) = throw Exception("Not used") override fun imageUrlParse(document: Document) = throw Exception("Not used") override fun getFilterList() = FilterList( Filter.Header("NOTE: Ignored if using text search!"), Filter.Separator(), GenreFilter(getGenreList()) ) class GenreFilter(vals: Array<Pair<String, String>>) : UriPartFilter("Category", vals) private fun getGenreList() = arrayOf( Pair("All", ""), Pair("Action", "action"), Pair("Adult", "adult"), Pair("Adventure", "adventure"), Pair("BL", "bl"), Pair("Comedy", "comedy"), Pair("Comic", "comic"), Pair("Crime", "crime"), Pair("Detective", "detective"), Pair("Drama", "drama"), Pair("Ecchi", "ecchi"), Pair("Fantasy", "fantasy"), Pair("Gender bender", "gender-bender"), Pair("GL", "gl"), Pair("Gossip", "gossip"), Pair("Harem", "harem"), Pair("HentaiVN.Net", "hentaivn"), Pair("Historical", "historical"), Pair("HoiHentai.Com", "hoihentai-com"), Pair("Horror", "horror"), Pair("Incest", "incest"), Pair("Isekai", "isekai"), Pair("Manhua", "manhua"), Pair("Martial arts", "martial-arts"), Pair("Mature", "mature"), Pair("Mecha", "mecha"), Pair("Medical", "medical"), Pair("Monster/Tentacle", "monster-tentacle"), Pair("Mystery", "mystery"), Pair("Novel", "novel"), Pair("Office Life", "office-life"), Pair("One shot", "one-shot"), Pair("Psychological", "psychological"), Pair("Revenge", "revenge"), Pair("Romance", "romance"), Pair("School Life", "school-life"), Pair("Sci Fi", "sci-fi"), Pair("Seinen", "seinen"), Pair("Shoujo", "shoujo"), Pair("Shounen", "shounen"), Pair("Slice of Life", "slice-of-life"), Pair("Smut", "smut"), Pair("Sports", "sports"), Pair("Supernatural", "supernatural"), Pair("Teenager", "teenager"), Pair("Thriller", "thriller"), Pair("Time Travel", "time-travel"), Pair("Tragedy", "tragedy"), Pair("Uncensored", "uncensored"), Pair("Vampire", "vampire"), Pair("Webtoon", "webtoon"), Pair("Yaoi", "yaoi"), Pair("Yuri", "yuri") ) open class UriPartFilter(displayName: String, private val vals: Array<Pair<String, String>>) : Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) { fun toUriPart() = vals[state].second } }
apache-2.0
4615ec2866a6e365307db4c08f1def0c
39.33871
135
0.626416
4.317031
false
false
false
false
inorichi/tachiyomi-extensions
src/en/dynasty/src/eu/kanade/tachiyomi/extension/en/dynasty/DynastyScans.kt
1
9711
package eu.kanade.tachiyomi.extension.en.dynasty import android.net.Uri import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.jsoup.nodes.Node import org.jsoup.nodes.TextNode import org.jsoup.select.Elements import rx.Observable import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.ArrayList import java.util.Locale abstract class DynastyScans : ParsedHttpSource() { override val baseUrl = "https://dynasty-scans.com" abstract fun popularMangaInitialUrl(): String override val lang = "en" override val supportsLatest = false open val searchPrefix = "" private var parent: List<Node> = ArrayList() private var list = InternalList(ArrayList(), "") private var imgList = InternalList(ArrayList(), "") private var _valid: Validate = Validate(false, -1) private val json: Json by injectLazy() override fun popularMangaRequest(page: Int): Request { return GET(popularMangaInitialUrl(), headers) } override fun popularMangaSelector() = "ul.thumbnails > li.span2" override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.setUrlWithoutDomain(element.select("a").attr("href")) manga.title = element.select("div.caption").text() return manga } override fun popularMangaParse(response: Response): MangasPage { val mangas = response.asJsoup().select(popularMangaSelector()).map { element -> popularMangaFromElement(element) } return MangasPage(mangas, false) } override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { if (query.startsWith("manga:")) { return if (query.startsWith("manga:$searchPrefix:")) { val newQuery = query.removePrefix("manga:$searchPrefix:") client.newCall(GET("$baseUrl/$searchPrefix/$newQuery")) .asObservableSuccess() .map { response -> val details = mangaDetailsParse(response) details.url = "/$searchPrefix/$newQuery" MangasPage(listOf(details), false) } } else { return Observable.just(MangasPage(ArrayList<SManga>(0), false)) } } return super.fetchSearchManga(page, query, filters) } override fun searchMangaSelector() = "a.name" override fun searchMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.setUrlWithoutDomain(element.attr("href")) manga.title = element.text() return manga } override fun searchMangaNextPageSelector() = "div.pagination > ul > li.active + li > a" private fun buildListfromResponse(): List<Node> { return client.newCall( Request.Builder().headers(headers) .url(popularMangaInitialUrl()).build() ).execute().asJsoup() .select("div#main").first { it.hasText() }.childNodes() } protected fun parseHeader(document: Document, manga: SManga): Boolean { val elements = document.select("div.tags > h2.tag-title").first().getElementsByTag("a") if (elements.isEmpty()) { return false } if (elements.lastIndex == 0) { manga.author = elements[0].text() } else { manga.artist = elements[0].text() manga.author = elements[1].text() } manga.status = document.select("div.tags > h2.tag-title > small").text().let { when { it.contains("Ongoing") -> SManga.ONGOING it.contains("Completed") -> SManga.COMPLETED it.contains("Licensed") -> SManga.LICENSED else -> SManga.UNKNOWN } } return true } protected fun parseGenres(document: Document, manga: SManga, select: String = "div.tags > div.tag-tags a") { parseGenres(document.select(select), manga) } protected fun parseGenres(elements: Elements, manga: SManga) { if (!elements.isEmpty()) { val genres = mutableListOf<String>() elements.forEach { genres.add(it.text()) } manga.genre = genres.joinToString(", ") } } protected fun parseDescription(document: Document, manga: SManga) { manga.description = document.select("div.tags > div.row div.description").text() } private fun getValid(manga: SManga): Validate { if (parent.isEmpty()) parent = buildListfromResponse() if (list.isEmpty()) list = InternalList(parent, "href") if (imgList.isEmpty()) imgList = InternalList(parent, "src") val pos = list.indexOf(manga.url.substringBeforeLast("/") + "/" + Uri.encode(manga.url.substringAfterLast("/"))) return Validate((pos > -1), pos) } override fun mangaDetailsParse(document: Document): SManga { val manga = SManga.create() _valid = getValid(manga) return manga } override fun chapterListSelector() = "div.span10 > dl.chapter-list > dd" override fun chapterListParse(response: Response): List<SChapter> { return super.chapterListParse(response).asReversed() } override fun chapterFromElement(element: Element): SChapter { val chapter = SChapter.create() val nodes = InternalList(element.childNodes(), "text") chapter.setUrlWithoutDomain(element.select("a.name").attr("href")) chapter.name = nodes[0] if (nodes.contains(" by ")) { chapter.name += " by ${nodes[nodes.indexOfPartial(" by ") + 1]}" if (nodes.contains(" and ")) { chapter.name += " and ${nodes[nodes.indexOfPartial(" and ") + 1]}" } } chapter.date_upload = nodes[nodes.indexOfPartial("released")] .substringAfter("released ") .replace("\'", "") .toDate("MMM dd yy") return chapter } protected fun String?.toDate(pattern: String): Long { this ?: return 0 return try { SimpleDateFormat(pattern, Locale.ENGLISH).parse(this)?.time ?: 0 } catch (_: Exception) { 0 } } override fun pageListParse(document: Document): List<Page> { return try { val imageUrl = document.select("script").last().html().substringAfter("var pages = [").substringBefore("];") json.parseToJsonElement("[$imageUrl]").jsonArray.mapIndexed { index, it -> Page(index, imageUrl = "$baseUrl${it.jsonObject["image"]!!.jsonPrimitive.content}") } } catch (e: Exception) { e.printStackTrace() emptyList() } } class InternalList(nodes: List<Node>, type: String) : ArrayList<String>() { init { if (type == "text") { for (node in nodes) { if (node is TextNode) { if (node.text() != " " && !node.text().contains("\n")) { this.add(node.text()) } } else if (node is Element) this.add(node.text()) } } if (type == "src") { nodes .filter { it is Element && it.hasClass("thumbnails") } .flatMap { it.childNodes() } .filterIsInstance<Element>() .filter { it.hasClass("span2") } .forEach { this.add(it.child(0).child(0).attr(type)) } } if (type == "href") { nodes .filter { it is Element && it.hasClass("thumbnails") } .flatMap { it.childNodes() } .filterIsInstance<Element>() .filter { it.hasClass("span2") } .forEach { this.add(it.child(0).attr(type)) } } } fun indexOfPartial(partial: String): Int { return (0..this.lastIndex).firstOrNull { this[it].contains(partial) } ?: -1 } fun getItem(partial: String): String { return (0..this.lastIndex) .firstOrNull { super.get(it).contains(partial) } ?.let { super.get(it) } ?: "" } } class Validate(_isManga: Boolean, _pos: Int) { val isManga = _isManga val pos = _pos } override fun popularMangaNextPageSelector() = "" override fun latestUpdatesSelector() = "" override fun latestUpdatesNextPageSelector() = "" override fun imageUrlParse(document: Document): String = "" override fun latestUpdatesFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun latestUpdatesRequest(page: Int): Request { return popularMangaRequest(page) } }
apache-2.0
3e0fd79cc8d7b9aeb48ac255a67ab79d
35.100372
120
0.593245
4.695841
false
false
false
false