repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/formatter/FunctionExpression.after.kt | 8 | 583 | val a = fun() {}
val b = fun test() {}
val c = fun() {}
val c = fun() = 4
val c = fun() =
4
val c = fun() {}
val c = fun() = 4
fun test() = fun test() = 4
fun test() {
test(fun() {
})
test(fun test() {})
test(fun test() = 5)
test(fun test() = fun test(a: Int) = 2)
2.(fun test() {})()
(fun() = 4)
(fun() {})
test(fun test() = 4)
}
fun d = fun(
a: Int,
b: String
) {
}
fun e = fun() {
val a = 1
}
fun f = fun() { foo() }
val g: (String) -> Int = fun(p: String): Unit { /* comment */ /* other comment */ }
fun foo() {}
| apache-2.0 |
ingokegel/intellij-community | plugins/github/src/org/jetbrains/plugins/github/GHOpenInBrowserActionGroup.kt | 1 | 11429 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.URLUtil
import com.intellij.vcs.log.VcsLogDataKeys
import com.intellij.vcsUtil.VcsUtil
import git4idea.GitFileRevision
import git4idea.GitRevisionNumber
import git4idea.GitUtil
import git4idea.history.GitHistoryUtils
import git4idea.repo.GitRepository
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
import org.jetbrains.plugins.github.util.GithubNotificationIdsHolder
import org.jetbrains.plugins.github.util.GithubNotifications
import org.jetbrains.plugins.github.util.GithubUtil
open class GHOpenInBrowserActionGroup
: ActionGroup(GithubBundle.messagePointer("open.on.github.action"),
GithubBundle.messagePointer("open.on.github.action.description"),
AllIcons.Vcs.Vendors.Github), DumbAware {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun update(e: AnActionEvent) {
val data = getData(e.dataContext)
e.presentation.isEnabledAndVisible = !data.isNullOrEmpty()
e.presentation.isPerformGroup = data?.size == 1
e.presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, e.presentation.isPerformGroup);
e.presentation.isPopupGroup = true
e.presentation.isDisableGroupIfEmpty = false
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
e ?: return emptyArray()
val data = getData(e.dataContext) ?: return emptyArray()
if (data.size <= 1) return emptyArray()
return data.map { GithubOpenInBrowserAction(it) }.toTypedArray()
}
override fun actionPerformed(e: AnActionEvent) {
getData(e.dataContext)?.let { GithubOpenInBrowserAction(it.first()) }?.actionPerformed(e)
}
protected open fun getData(dataContext: DataContext): List<Data>? {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return null
return getDataFromPullRequest(project, dataContext)
?: getDataFromHistory(project, dataContext)
?: getDataFromLog(project, dataContext)
?: getDataFromVirtualFile(project, dataContext)
}
private fun getDataFromPullRequest(project: Project, dataContext: DataContext): List<Data>? {
val pullRequest = dataContext.getData(GHPRActionKeys.SELECTED_PULL_REQUEST)
?: dataContext.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)?.detailsData?.loadedDetails
?: return null
return listOf(Data.URL(project, pullRequest.url))
}
private fun getDataFromHistory(project: Project, dataContext: DataContext): List<Data>? {
val fileRevision = dataContext.getData(VcsDataKeys.VCS_FILE_REVISION) ?: return null
if (fileRevision !is GitFileRevision) return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(fileRevision.path)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories.map { Data.Revision(project, it.ghRepositoryCoordinates, fileRevision.revisionNumber.asString()) }
}
private fun getDataFromLog(project: Project, dataContext: DataContext): List<Data>? {
val selection = dataContext.getData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION) ?: return null
val selectedCommits = selection.commits
if (selectedCommits.size != 1) return null
val commit = ContainerUtil.getFirstItem(selectedCommits) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(commit.root)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories.map { Data.Revision(project, it.ghRepositoryCoordinates, commit.hash.asString()) }
}
private fun getDataFromVirtualFile(project: Project, dataContext: DataContext): List<Data>? {
val virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(virtualFile)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
val changeListManager = ChangeListManager.getInstance(project)
if (changeListManager.isUnversioned(virtualFile)) return null
val change = changeListManager.getChange(virtualFile)
return if (change != null && change.type == Change.Type.NEW) null
else accessibleRepositories.map { Data.File(project, it.ghRepositoryCoordinates, repository.root, virtualFile) }
}
protected sealed class Data(val project: Project) {
@Nls
abstract fun getName(): String
class File(project: Project,
val repository: GHRepositoryCoordinates,
val gitRepoRoot: VirtualFile,
val virtualFile: VirtualFile) : Data(project) {
override fun getName(): String {
@NlsSafe
val formatted = repository.toString().replace('_', ' ')
return formatted
}
}
class Revision(project: Project, val repository: GHRepositoryCoordinates, val revisionHash: String) : Data(project) {
override fun getName(): String {
@NlsSafe
val formatted = repository.toString().replace('_', ' ')
return formatted
}
}
class URL(project: Project, @NlsSafe val htmlUrl: String) : Data(project) {
override fun getName() = htmlUrl
}
}
private companion object {
class GithubOpenInBrowserAction(val data: Data)
: DumbAwareAction({ data.getName() }) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
when (data) {
is Data.Revision -> openCommitInBrowser(data.repository, data.revisionHash)
is Data.File -> openFileInBrowser(data.project, data.gitRepoRoot, data.repository, data.virtualFile,
e.getData(CommonDataKeys.EDITOR))
is Data.URL -> BrowserUtil.browse(data.htmlUrl)
}
}
private fun openCommitInBrowser(path: GHRepositoryCoordinates, revisionHash: String) {
BrowserUtil.browse("${path.toUrl()}/commit/$revisionHash")
}
private fun openFileInBrowser(project: Project,
repositoryRoot: VirtualFile,
path: GHRepositoryCoordinates,
virtualFile: VirtualFile,
editor: Editor?) {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repositoryRoot)
if (relativePath == null) {
GithubNotifications.showError(project, GithubNotificationIdsHolder.OPEN_IN_BROWSER_FILE_IS_NOT_UNDER_REPO,
GithubBundle.message("cannot.open.in.browser"),
GithubBundle.message("open.on.github.file.is.not.under.repository"),
"Root: " + repositoryRoot.presentableUrl + ", file: " + virtualFile.presentableUrl)
return
}
val hash = getCurrentFileRevisionHash(project, virtualFile)
if (hash == null) {
GithubNotifications.showError(project,
GithubNotificationIdsHolder.OPEN_IN_BROWSER_CANNOT_GET_LAST_REVISION,
GithubBundle.message("cannot.open.in.browser"),
GithubBundle.message("cannot.get.last.revision"))
return
}
val githubUrl = GHPathUtil.makeUrlToOpen(editor, relativePath, hash, path)
BrowserUtil.browse(githubUrl)
}
private fun getCurrentFileRevisionHash(project: Project, file: VirtualFile): String? {
val ref = Ref<GitRevisionNumber>()
object : Task.Modal(project, GithubBundle.message("open.on.github.getting.last.revision"), true) {
override fun run(indicator: ProgressIndicator) {
ref.set(GitHistoryUtils.getCurrentRevision(project, VcsUtil.getFilePath(file), "HEAD") as GitRevisionNumber?)
}
override fun onThrowable(error: Throwable) {
GithubUtil.LOG.warn(error)
}
}.queue()
return if (ref.isNull) null else ref.get().rev
}
}
}
}
object GHPathUtil {
fun getFileURL(repository: GitRepository,
path: GHRepositoryCoordinates,
virtualFile: VirtualFile,
editor: Editor?): String? {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repository.root)
if (relativePath == null) {
return null
}
val hash = repository.currentRevision
if (hash == null) {
return null
}
return makeUrlToOpen(editor, relativePath, hash, path)
}
fun makeUrlToOpen(editor: Editor?, relativePath: String, branch: String, path: GHRepositoryCoordinates): String {
val builder = StringBuilder()
if (StringUtil.isEmptyOrSpaces(relativePath)) {
builder.append(path.toUrl()).append("/tree/").append(branch)
}
else {
builder.append(path.toUrl()).append("/blob/").append(branch).append('/').append(URLUtil.encodePath(relativePath))
}
if (editor != null && editor.document.lineCount >= 1) {
// lines are counted internally from 0, but from 1 on github
val selectionModel = editor.selectionModel
val begin = editor.document.getLineNumber(selectionModel.selectionStart) + 1
val selectionEnd = selectionModel.selectionEnd
var end = editor.document.getLineNumber(selectionEnd) + 1
if (editor.document.getLineStartOffset(end - 1) == selectionEnd) {
end -= 1
}
builder.append("#L").append(begin)
if (begin != end) {
builder.append("-L").append(end)
}
}
return builder.toString()
}
} | apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/helpers/utils.kt | 1 | 2091 | // 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.contributors.helpers
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.scopes.KtScope
import org.jetbrains.kotlin.analysis.api.scopes.KtScopeNameFilter
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.idea.completion.checkers.CompletionVisibilityChecker
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
internal fun createStarTypeArgumentsList(typeArgumentsCount: Int): String =
if (typeArgumentsCount > 0) {
List(typeArgumentsCount) { "*" }.joinToString(prefix = "<", postfix = ">")
} else {
""
}
internal fun KtAnalysisSession.collectNonExtensions(
scope: KtScope,
visibilityChecker: CompletionVisibilityChecker,
scopeNameFilter: KtScopeNameFilter,
symbolFilter: (KtCallableSymbol) -> Boolean = { true }
): Sequence<KtCallableSymbol> = scope.getCallableSymbols { name ->
listOfNotNull(name, name.toJavaGetterName(), name.toJavaSetterName()).any(scopeNameFilter)
}
.filterNot { it.isExtension }
.filter { symbolFilter(it) }
.filter { visibilityChecker.isVisible(it) }
private fun Name.toJavaGetterName(): Name? = identifierOrNullIfSpecial?.let { Name.identifier(JvmAbi.getterName(it)) }
private fun Name.toJavaSetterName(): Name? = identifierOrNullIfSpecial?.let { Name.identifier(JvmAbi.setterName(it)) }
internal fun KtDeclaration.canDefinitelyNotBeSeenFromOtherFile(): Boolean {
return when {
isPrivate() -> true
hasModifier(KtTokens.INTERNAL_KEYWORD) && containingKtFile.isCompiled -> {
// internal declarations from library are invisible from source modules
true
}
else -> false
}
} | apache-2.0 |
leafclick/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectNotificationAware.kt | 1 | 2680 | // 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.externalSystem.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.project.Project
import gnu.trove.THashSet
import org.jetbrains.annotations.TestOnly
class ProjectNotificationAware : Disposable {
private var isHidden = false
private val projectsWithNotification = THashSet<ExternalSystemProjectId>()
fun notificationNotify(projectAware: ExternalSystemProjectAware) = runInEdt {
val projectId = projectAware.projectId
LOG.debug("${projectId.readableName}: Notify notification")
projectsWithNotification.add(projectId)
revealNotification()
}
fun notificationExpire(projectId: ExternalSystemProjectId) = runInEdt {
LOG.debug("${projectId.readableName}: Expire notification")
projectsWithNotification.remove(projectId)
revealNotification()
}
fun notificationExpire() = runInEdt {
LOG.debug("Expire notification")
projectsWithNotification.clear()
revealNotification()
}
override fun dispose() {
notificationExpire()
}
private fun setHideStatus(isHidden: Boolean) = runInEdt {
this.isHidden = isHidden
ApplicationManager.getApplication().assertIsDispatchThread()
val toolbarProvider = ProjectRefreshFloatingProvider.getExtension()
toolbarProvider.updateAllToolbarComponents()
}
private fun revealNotification() = setHideStatus(false)
fun hideNotification() = setHideStatus(true)
fun isNotificationVisible(): Boolean {
ApplicationManager.getApplication().assertIsDispatchThread()
return !isHidden && projectsWithNotification.isNotEmpty()
}
fun getSystemIds(): Set<ProjectSystemId> {
ApplicationManager.getApplication().assertIsDispatchThread()
return projectsWithNotification.map { it.systemId }.toSet()
}
@TestOnly
fun getProjectsWithNotification(): Set<ExternalSystemProjectId> {
ApplicationManager.getApplication().assertIsDispatchThread()
return projectsWithNotification.toSet()
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
@JvmStatic
fun getInstance(project: Project): ProjectNotificationAware {
return ServiceManager.getService(project, ProjectNotificationAware::class.java)
}
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertToStringTemplate/interpolateChar.kt | 4 | 64 | fun main(args: Array<String>){
val x = "abc" +<caret> 'd'
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/indentationOnNewline/afterUnmatchedBrace/LambdaArgumentBeforeLocalPropertyInitializer.kt | 3 | 100 | // WITH_RUNTIME
// WITHOUT_CUSTOM_LINE_INDENT_PROVIDER
fun test() {
val test = run { <caret>1
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/definiteReturns/labeledAndUnlabeledReturn2.kt | 4 | 250 | // WITH_RUNTIME
// PARAM_DESCRIPTOR: value-parameter it: kotlin.Int defined in foo.<anonymous>
// PARAM_TYPES: kotlin.Int
fun foo(a: Int): Int {
a.let {
<selection>if (it > 0) return@foo it else return -it</selection>
}
return 0
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertReceiverToParameter/memberFun.kt | 4 | 210 | // WITH_RUNTIME
class A {
fun <caret>String.foo(n: Int): Boolean {
return length - n/2 > 1
}
fun test() {
"1".foo(2)
}
}
fun test() {
with(A()) {
"1".foo(2)
}
} | apache-2.0 |
asarazan/Bismarck | bismarck/src/commonMain/kotlin/net/sarazan/bismarck/storage/MemoryStorage.kt | 1 | 810 | /*
* Copyright 2019 The Bismarck Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sarazan.bismarck.storage
open class MemoryStorage<T : Any>(var cached: T? = null) : Storage<T> {
override fun get(): T? = cached
override fun put(data: T?) {
cached = data
}
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/jvm-decompiler/src/org/jetbrains/kotlin/idea/jvmDecompiler/DecompileKotlinToJavaAction.kt | 1 | 2500 | // 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.jvmDecompiler
import com.intellij.codeInsight.AttachSourcesProvider
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.util.ActionCallback
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.base.util.KotlinPlatformUtils
import org.jetbrains.kotlin.psi.KtFile
class DecompileKotlinToJavaAction : AnAction(KotlinJvmDecompilerBundle.message("action.decompile.java.name")) {
override fun actionPerformed(e: AnActionEvent) {
val binaryFile = getBinaryKotlinFile(e) ?: return
KotlinJvmDecompilerFacadeImpl.showDecompiledCode(binaryFile)
}
override fun update(e: AnActionEvent) {
when {
KotlinPlatformUtils.isCidr -> e.presentation.isEnabledAndVisible = false
else -> e.presentation.isEnabled = getBinaryKotlinFile(e) != null
}
}
private fun getBinaryKotlinFile(e: AnActionEvent): KtFile? {
val file = e.getData(CommonDataKeys.PSI_FILE) as? KtFile ?: return null
if (!file.canBeDecompiledToJava()) return null
return file
}
}
fun KtFile.canBeDecompiledToJava() = isCompiled && virtualFile?.fileType == JavaClassFileType.INSTANCE
// Add action to "Attach sources" notification panel
class DecompileKotlinToJavaActionProvider : AttachSourcesProvider {
override fun getActions(
orderEntries: MutableList<LibraryOrderEntry>,
psiFile: PsiFile
): Collection<AttachSourcesProvider.AttachSourcesAction> {
if (psiFile !is KtFile || !psiFile.canBeDecompiledToJava()) return emptyList()
return listOf(object : AttachSourcesProvider.AttachSourcesAction {
override fun getName() = KotlinJvmDecompilerBundle.message("action.decompile.java.name")
override fun perform(orderEntriesContainingFile: List<LibraryOrderEntry>?): ActionCallback {
KotlinJvmDecompilerFacadeImpl.showDecompiledCode(psiFile)
return ActionCallback.DONE
}
override fun getBusyText() = KotlinJvmDecompilerBundle.message("action.decompile.busy.text")
})
}
}
| apache-2.0 |
JetBrains/kotlin-native | backend.native/tests/interop/objc/tests/KT38234_override.kt | 4 | 212 | import kotlin.test.*
import objcTests.*
class KT38234_Impl : KT38234_P1Protocol, KT38234_Base() {
override fun foo(): Int = 566
}
@Test fun testKT38234() {
assertEquals(566, KT38234_Impl().callFoo())
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/completion/tests/testData/handlers/keywords/Do.kt | 8 | 75 | // FIR_IDENTICAL
// FIR_COMPARISON
fun t() {
d<caret>
}
// ELEMENT: do | apache-2.0 |
kotlinx/kotlinx.html | src/jsMain/kotlin/utilsImpl-js.kt | 1 | 107 | package kotlinx.html
import kotlin.js.*
actual fun currentTimeMillis(): Long = Date().getTime().toLong()
| apache-2.0 |
taigua/exercism | kotlin/luhn/src/main/kotlin/Luhn.kt | 1 | 989 | /**
* Created by Corwin on 2017/1/31.
*/
class Luhn(num: Long) {
companion object {
private fun digits(num: Long) : List<Int> {
var n = num
val digits: MutableList<Int> = mutableListOf()
while (n != 0L) {
digits.add((n % 10).toInt())
n /= 10
}
return digits.toList()
}
private fun addends(num: Long) : List<Int> {
return digits(num).mapIndexed { i, v ->
if (i % 2 != 0) {
val temp = v * 2
if (temp > 9) temp - 9 else temp
} else {
v
}
}
}
}
val addends : List<Int> = Companion.addends(num).reversed()
val checkDigit: Int = addends.last()
val checksum: Int = addends.sum()
val isValid: Boolean = checksum % 10 == 0
val create: Long = num * 10 + (10 - Companion.addends(num * 10).sum() % 10) % 10
} | mit |
androidx/androidx | compose/foundation/foundation/src/desktopMain/kotlin/androidx/compose/foundation/text/StringHelpers.desktop.kt | 3 | 1040 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text
import org.jetbrains.skia.BreakIterator
internal actual fun String.findPrecedingBreak(index: Int): Int {
val it = BreakIterator.makeCharacterInstance()
it.setText(this)
return it.preceding(index)
}
internal actual fun String.findFollowingBreak(index: Int): Int {
val it = BreakIterator.makeCharacterInstance()
it.setText(this)
return it.following(index)
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteValueParameter/kotlinValueParameter/defaultParam2.kt | 13 | 77 | fun foo(a: Int, b: Int = 0, <caret>c: Int = 0) {
}
fun bar() {
foo(1)
} | apache-2.0 |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/IconDbMaintainer.kt | 7 | 588 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui
import com.intellij.configurationStore.SettingsSavingComponent
import com.intellij.openapi.Disposable
import com.intellij.util.SVGLoader
// icons maybe loaded before app loaded, so, SVGLoaderCache cannot be as a service
private class IconDbMaintainer : Disposable, SettingsSavingComponent {
override fun dispose() {
SVGLoader.persistentCache?.close()
}
override suspend fun save() {
SVGLoader.persistentCache?.save()
}
} | apache-2.0 |
GunoH/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookIntervalPointer.kt | 2 | 1877 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.Key
import com.intellij.util.EventDispatcher
import java.util.*
/**
* Pointer becomes invalid when code cell is removed.
* It may become valid again when action is undone or redone.
* Invalid pointer returns null.
*/
interface NotebookIntervalPointer {
/** should be called in read-action */
fun get(): NotebookCellLines.Interval?
}
private val key = Key.create<NotebookIntervalPointerFactory>(NotebookIntervalPointerFactory::class.java.name)
interface NotebookIntervalPointerFactory {
/**
* Interval should be valid, return pointer to it.
* Should be called in read-action.
*/
fun create(interval: NotebookCellLines.Interval): NotebookIntervalPointer
/**
* Can be called only inside write-action.
* Undo and redo will be added automatically.
*/
fun modifyPointers(changes: Iterable<Change>)
interface ChangeListener : EventListener {
fun onUpdated(event: NotebookIntervalPointersEvent)
}
val changeListeners: EventDispatcher<ChangeListener>
companion object {
fun get(editor: Editor): NotebookIntervalPointerFactory =
getOrNull(editor)!!
fun getOrNull(editor: Editor): NotebookIntervalPointerFactory? =
key.get(editor.document) ?: tryInstall(editor)
private fun tryInstall(editor: Editor): NotebookIntervalPointerFactory? =
getLanguage(editor)
?.let { NotebookIntervalPointerFactoryProvider.forLanguage(it) }
?.create(editor)
?.also { key.set(editor.document, it) }
}
sealed interface Change
/** invalidate pointer to interval, create new pointer */
data class Invalidate(val interval: NotebookCellLines.Interval) : Change
/** swap two pointers */
data class Swap(val firstOrdinal: Int, val secondOrdinal: Int) : Change
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinIdeDescriptorRenderer.kt | 2 | 58506 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.parameterInfo
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.builtins.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.idea.ClassifierNamePolicyEx
import org.jetbrains.kotlin.idea.parameterInfo.KotlinIdeDescriptorRendererHighlightingManager.Companion.Attributes
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.renderer.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils.isCompanionObject
import org.jetbrains.kotlin.resolve.constants.AnnotationValue
import org.jetbrains.kotlin.resolve.constants.ArrayValue
import org.jetbrains.kotlin.resolve.constants.ConstantValue
import org.jetbrains.kotlin.resolve.constants.KClassValue
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.descriptorUtil.declaresOrInheritsDefaultValue
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.TypeUtils.CANNOT_INFER_FUNCTION_PARAM_TYPE
import org.jetbrains.kotlin.types.error.*
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.typeUtil.isUnresolvedType
import org.jetbrains.kotlin.util.capitalizeDecapitalize.toLowerCaseAsciiOnly
import java.util.*
open class KotlinIdeDescriptorRenderer(
open val options: KotlinIdeDescriptorOptions
) : DescriptorRenderer(), DescriptorRendererOptions by options /* this gives access to options without qualifier */ {
private var overriddenHighlightingManager: KotlinIdeDescriptorRendererHighlightingManager<Attributes>? = null
get() = field ?: options.highlightingManager
private inline fun <R> withNoHighlighting(action: () -> R): R {
val old = overriddenHighlightingManager
overriddenHighlightingManager = KotlinIdeDescriptorRendererHighlightingManager.NO_HIGHLIGHTING
val result = action()
overriddenHighlightingManager = old
return result
}
fun withIdeOptions(changeOptions: KotlinIdeDescriptorOptions.() -> Unit): KotlinIdeDescriptorRenderer {
val options = this.options.copy()
options.changeOptions()
options.lock()
return KotlinIdeDescriptorRenderer(options)
}
companion object {
fun withOptions(changeOptions: KotlinIdeDescriptorOptions.() -> Unit): KotlinIdeDescriptorRenderer {
val options = KotlinIdeDescriptorOptions()
options.changeOptions()
options.lock()
return KotlinIdeDescriptorRenderer(options)
}
private val STANDARD_JAVA_ALIASES = setOf(
"kotlin.collections.RandomAccess",
"kotlin.collections.ArrayList",
"kotlin.collections.LinkedHashMap",
"kotlin.collections.HashMap",
"kotlin.collections.LinkedHashSet",
"kotlin.collections.HashSet"
)
}
private val functionTypeAnnotationsRenderer: KotlinIdeDescriptorRenderer by lazy {
withIdeOptions {
excludedTypeAnnotationClasses += listOf(StandardNames.FqNames.extensionFunctionType)
}
}
private fun StringBuilder.appendHighlighted(
value: String,
attributesBuilder: KotlinIdeDescriptorRendererHighlightingManager<Attributes>.() -> Attributes
) {
return with(overriddenHighlightingManager!!) { [email protected](value, attributesBuilder()) }
}
private fun highlight(
value: String,
attributesBuilder: KotlinIdeDescriptorRendererHighlightingManager<Attributes>.() -> Attributes
): String {
return with(overriddenHighlightingManager!!) { buildString { appendHighlighted(value, attributesBuilder()) } }
}
private fun highlightByLexer(value: String): String {
return with(overriddenHighlightingManager!!) { buildString { appendCodeSnippetHighlightedByLexer(value) } }
}
/* FORMATTING */
private fun renderKeyword(keyword: String): String {
val highlighted = highlight(keyword) { asKeyword }
return when (textFormat) {
RenderingFormat.PLAIN -> highlighted
RenderingFormat.HTML -> if (options.bold && !boldOnlyForNamesInHtml) "<b>$highlighted</b>" else highlighted
}
}
protected fun renderError(message: String): String {
val highlighted = highlight(message) { asError }
return when (textFormat) {
RenderingFormat.PLAIN -> highlighted
RenderingFormat.HTML -> if (options.bold) "<b>$highlighted</b>" else highlighted
}
}
protected fun escape(string: String) = textFormat.escape(string)
protected fun lt() = highlight(escape("<")) { asOperationSign }
protected fun gt() = highlight(escape(">")) { asOperationSign }
protected fun arrow(): String {
return highlight(escape("->")) { asArrow }
}
override fun renderMessage(message: String): String {
val highlighted = highlight(message) { asInfo }
return when (textFormat) {
RenderingFormat.PLAIN -> highlighted
RenderingFormat.HTML -> "<i>$highlighted</i>"
}
}
/* NAMES RENDERING */
override fun renderName(name: Name, rootRenderedElement: Boolean): String {
val escaped = escape(name.render())
return if (options.bold && boldOnlyForNamesInHtml && textFormat == RenderingFormat.HTML && rootRenderedElement) {
"<b>$escaped</b>"
} else
escaped
}
protected fun StringBuilder.appendName(descriptor: DeclarationDescriptor, rootRenderedElement: Boolean) {
append(renderName(descriptor.name, rootRenderedElement))
}
private fun StringBuilder.appendName(
descriptor: DeclarationDescriptor,
rootRenderedElement: Boolean,
attributesBuilder: KotlinIdeDescriptorRendererHighlightingManager<Attributes>.() -> Attributes
) {
return with(options.highlightingManager) {
[email protected](renderName(descriptor.name, rootRenderedElement), attributesBuilder())
}
}
private fun StringBuilder.appendCompanionObjectName(descriptor: DeclarationDescriptor) {
if (renderCompanionObjectName) {
if (startFromName) {
appendHighlighted("companion object") { asKeyword }
}
appendSpaceIfNeeded()
val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration != null) {
appendHighlighted("of ") { asInfo }
appendHighlighted(renderName(containingDeclaration.name, false)) { asObjectName }
}
}
if (verbose || descriptor.name != SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT) {
if (!startFromName) appendSpaceIfNeeded()
appendHighlighted(renderName(descriptor.name, true)) { asObjectName }
}
}
override fun renderFqName(fqName: FqNameUnsafe) = renderFqName(fqName.pathSegments())
private fun renderFqName(pathSegments: List<Name>): String {
val rendered = buildString {
for (element in pathSegments) {
if (isNotEmpty()) {
appendHighlighted(".") { asDot }
}
appendHighlighted(element.render()) { asClassName }
}
}
return escape(rendered)
}
override fun renderClassifierName(klass: ClassifierDescriptor): String = if (ErrorUtils.isError(klass)) {
klass.typeConstructor.toString()
} else
classifierNamePolicy.renderClassifier(klass, this)
fun renderClassifierNameWithType(klass: ClassifierDescriptor, type: KotlinType): String = if (ErrorUtils.isError(klass)) {
klass.typeConstructor.toString()
} else {
val policy = classifierNamePolicy
if (policy is ClassifierNamePolicyEx) {
policy.renderClassifierWithType(klass, this, type)
} else {
policy.renderClassifier(klass, this)
}
}
/* TYPES RENDERING */
override fun renderType(type: KotlinType): String = buildString {
appendNormalizedType(typeNormalizer(type))
}
private fun StringBuilder.appendNormalizedType(type: KotlinType) {
val abbreviated = type.unwrap() as? AbbreviatedType
if (abbreviated != null) {
if (renderTypeExpansions) {
appendNormalizedTypeAsIs(abbreviated.expandedType)
} else {
// TODO nullability is lost for abbreviated type?
appendNormalizedTypeAsIs(abbreviated.abbreviation)
if (renderUnabbreviatedType) {
appendAbbreviatedTypeExpansion(abbreviated)
}
}
return
}
appendNormalizedTypeAsIs(type)
}
private fun StringBuilder.appendAbbreviatedTypeExpansion(abbreviated: AbbreviatedType) {
if (options.doNotExpandStandardJavaTypeAliases && abbreviated.fqName?.asString() in STANDARD_JAVA_ALIASES) {
return
}
if (textFormat == RenderingFormat.HTML) {
append("<i>")
}
val expandedType = withNoHighlighting { buildString { appendNormalizedTypeAsIs(abbreviated.expandedType) } }
appendHighlighted(" /* = $expandedType */") { asInfo }
if (textFormat == RenderingFormat.HTML) {
append("</i></font>")
}
}
private fun StringBuilder.appendNormalizedTypeAsIs(type: KotlinType) {
if (type is WrappedType && debugMode && !type.isComputed()) {
appendHighlighted("<Not computed yet>") { asInfo }
return
}
when (val unwrappedType = type.unwrap()) {
is FlexibleType -> append(unwrappedType.render(this@KotlinIdeDescriptorRenderer, this@KotlinIdeDescriptorRenderer))
is SimpleType -> appendSimpleType(unwrappedType)
}
}
private fun StringBuilder.appendSimpleType(type: SimpleType) {
if (type == CANNOT_INFER_FUNCTION_PARAM_TYPE || TypeUtils.isDontCarePlaceholder(type)) {
appendHighlighted("???") { asError }
return
}
if (ErrorUtils.isUninferredTypeVariable(type)) {
if (uninferredTypeParameterAsName) {
append(renderError((type.constructor as ErrorTypeConstructor).getParam(0)))
} else {
appendHighlighted("???") { asError }
}
return
}
if (type.isError) {
appendDefaultType(type)
return
}
if (shouldRenderAsPrettyFunctionType(type)) {
appendFunctionType(type)
} else {
appendDefaultType(type)
}
}
protected fun shouldRenderAsPrettyFunctionType(type: KotlinType): Boolean {
return type.isBuiltinFunctionalType && type.arguments.none { it.isStarProjection }
}
override fun renderFlexibleType(lowerRendered: String, upperRendered: String, builtIns: KotlinBuiltIns): String {
val lowerType = escape(StringUtil.removeHtmlTags(lowerRendered))
val upperType = escape(StringUtil.removeHtmlTags(upperRendered))
if (differsOnlyInNullability(lowerType, upperType)) {
if (upperType.startsWith("(")) {
// the case of complex type, e.g. (() -> Unit)?
return buildString {
appendHighlighted("(") { asParentheses }
append(lowerRendered)
appendHighlighted(")") { asParentheses }
appendHighlighted("!") { asOperationSign }
}
}
return buildString {
append(lowerRendered)
appendHighlighted("!") { asOperationSign }
}
}
val kotlinCollectionsPrefix = classifierNamePolicy.renderClassifier(builtIns.collection, this)
.let { escape(StringUtil.removeHtmlTags(it)) }
.substringBefore("Collection")
val mutablePrefix = "Mutable"
// java.util.List<Foo> -> (Mutable)List<Foo!>!
val simpleCollection = replacePrefixes(
lowerType,
kotlinCollectionsPrefix + mutablePrefix,
upperType,
kotlinCollectionsPrefix,
"$kotlinCollectionsPrefix($mutablePrefix)"
)
if (simpleCollection != null) return simpleCollection
// java.util.Map.Entry<Foo, Bar> -> (Mutable)Map.(Mutable)Entry<Foo!, Bar!>!
val mutableEntry = replacePrefixes(
lowerType,
kotlinCollectionsPrefix + "MutableMap.MutableEntry",
upperType,
kotlinCollectionsPrefix + "Map.Entry",
"$kotlinCollectionsPrefix(Mutable)${highlight("Map") { asClassName }}.(Mutable)${highlight("Entry") { asClassName }}"
)
if (mutableEntry != null) return mutableEntry
val kotlinPrefix = classifierNamePolicy.renderClassifier(builtIns.array, this)
.let { escape(StringUtil.removeHtmlTags(it)) }
.substringBefore("Array")
// Foo[] -> Array<(out) Foo!>!
val array = replacePrefixes(
lowerType,
kotlinPrefix + escape("Array<"),
upperType,
kotlinPrefix + escape("Array<out "),
kotlinPrefix + highlight("Array") { asClassName } + escape("<(out) ")
)
if (array != null) return array
return "($lowerRendered..$upperRendered)"
}
override fun renderTypeArguments(typeArguments: List<TypeProjection>): String = if (typeArguments.isEmpty()) ""
else buildString {
append(lt())
appendTypeProjections(typeArguments)
append(gt())
}
private fun StringBuilder.appendDefaultType(type: KotlinType) {
appendAnnotations(type)
if (type.isError) {
if (isUnresolvedType(type) && presentableUnresolvedTypes) {
appendHighlighted(ErrorUtils.unresolvedTypeAsItIs(type)) { asError }
} else {
if (type is ErrorType && !informativeErrorType) {
appendHighlighted(type.debugMessage) { asError }
} else {
appendHighlighted(type.constructor.toString()) { asError } // Debug name of an error type is more informative
}
appendHighlighted(renderTypeArguments(type.arguments)) { asError }
}
} else {
appendTypeConstructorAndArguments(type)
}
if (type.isMarkedNullable) {
appendHighlighted("?") { asNullityMarker }
}
if (classifierNamePolicy !is ClassifierNamePolicyEx) {
if (type.isDefinitelyNotNullType) {
appendHighlighted(" & Any") { asNonNullAssertion }
}
}
}
private fun StringBuilder.appendTypeConstructorAndArguments(
type: KotlinType,
typeConstructor: TypeConstructor = type.constructor
) {
val possiblyInnerType = type.buildPossiblyInnerType()
if (possiblyInnerType == null) {
append(renderTypeConstructorOfType(typeConstructor, type))
append(renderTypeArguments(type.arguments))
return
}
appendPossiblyInnerType(possiblyInnerType)
}
private fun StringBuilder.appendPossiblyInnerType(possiblyInnerType: PossiblyInnerType) {
possiblyInnerType.outerType?.let {
appendPossiblyInnerType(it)
appendHighlighted(".") { asDot }
appendHighlighted(renderName(possiblyInnerType.classifierDescriptor.name, false)) { asClassName }
} ?: append(renderTypeConstructor(possiblyInnerType.classifierDescriptor.typeConstructor))
append(renderTypeArguments(possiblyInnerType.arguments))
}
override fun renderTypeConstructor(typeConstructor: TypeConstructor): String = when (val cd = typeConstructor.declarationDescriptor) {
is TypeParameterDescriptor -> highlight(renderClassifierName(cd)) { asTypeParameterName }
is ClassDescriptor -> highlight(renderClassifierName(cd)) { asClassName }
is TypeAliasDescriptor -> highlight(renderClassifierName(cd)) { asTypeAlias }
null -> highlight(escape(typeConstructor.toString())) { asClassName }
else -> error("Unexpected classifier: " + cd::class.java)
}
private fun renderTypeConstructorOfType(typeConstructor: TypeConstructor, type: KotlinType): String =
when (val cd = typeConstructor.declarationDescriptor) {
is TypeParameterDescriptor -> highlight(renderClassifierNameWithType(cd, type)) { asTypeParameterName }
is ClassDescriptor -> highlight(renderClassifierNameWithType(cd, type)) { asClassName }
is TypeAliasDescriptor -> highlight(renderClassifierNameWithType(cd, type)) { asTypeAlias }
null -> highlight(escape(typeConstructor.toString())) { asClassName }
else -> error("Unexpected classifier: " + cd::class.java)
}
override fun renderTypeProjection(typeProjection: TypeProjection) = buildString {
appendTypeProjections(listOf(typeProjection))
}
private fun StringBuilder.appendTypeProjections(typeProjections: List<TypeProjection>) {
typeProjections.joinTo(this, highlight(", ") { asComma }) {
if (it.isStarProjection) {
highlight("*") { asOperationSign }
} else {
val type = renderType(it.type)
if (it.projectionKind == Variance.INVARIANT) type
else "${highlight(it.projectionKind.toString()) { asKeyword }} $type"
}
}
}
private fun StringBuilder.appendFunctionType(type: KotlinType) {
val lengthBefore = length
// we need special renderer to skip @ExtensionFunctionType
with(functionTypeAnnotationsRenderer) {
appendAnnotations(type)
}
val hasAnnotations = length != lengthBefore
val isSuspend = type.isSuspendFunctionType
val isNullable = type.isMarkedNullable
val receiverType = type.getReceiverTypeFromFunctionType()
val needParenthesis = isNullable || (hasAnnotations && receiverType != null)
if (needParenthesis) {
if (isSuspend) {
insert(lengthBefore, highlight("(") { asParentheses })
} else {
if (hasAnnotations) {
assert(last().isWhitespace())
if (get(lastIndex - 1) != ')') {
// last annotation rendered without parenthesis - need to add them otherwise parsing will be incorrect
insert(lastIndex, highlight("()") { asParentheses })
}
}
appendHighlighted("(") { asParentheses }
}
}
appendModifier(isSuspend, "suspend")
if (receiverType != null) {
val surroundReceiver = shouldRenderAsPrettyFunctionType(receiverType) && !receiverType.isMarkedNullable ||
receiverType.hasModifiersOrAnnotations()
if (surroundReceiver) {
appendHighlighted("(") { asParentheses }
}
appendNormalizedType(receiverType)
if (surroundReceiver) {
appendHighlighted(")") { asParentheses }
}
appendHighlighted(".") { asDot }
}
appendHighlighted("(") { asParentheses }
val parameterTypes = type.getValueParameterTypesFromFunctionType()
for ((index, typeProjection) in parameterTypes.withIndex()) {
if (index > 0) appendHighlighted(", ") { asComma }
val name = if (parameterNamesInFunctionalTypes) typeProjection.type.extractParameterNameFromFunctionTypeArgument() else null
if (name != null) {
appendHighlighted(renderName(name, false)) { asParameter }
appendHighlighted(": ") { asColon }
}
append(renderTypeProjection(typeProjection))
}
appendHighlighted(") ") { asParentheses }
append(arrow())
append(" ")
appendNormalizedType(type.getReturnTypeFromFunctionType())
if (needParenthesis) appendHighlighted(")") { asParentheses }
if (isNullable) appendHighlighted("?") { asNullityMarker }
}
protected fun KotlinType.hasModifiersOrAnnotations() =
isSuspendFunctionType || !annotations.isEmpty()
/* METHODS FOR ALL KINDS OF DESCRIPTORS */
private fun StringBuilder.appendDefinedIn(descriptor: DeclarationDescriptor) {
if (descriptor is PackageFragmentDescriptor || descriptor is PackageViewDescriptor) {
return
}
if (descriptor is ModuleDescriptor) {
append(renderMessage(" is a module"))
return
}
val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration != null && containingDeclaration !is ModuleDescriptor) {
append(renderMessage(" defined in "))
val fqName = DescriptorUtils.getFqName(containingDeclaration)
append(if (fqName.isRoot) "root package" else renderFqName(fqName))
if (withSourceFileForTopLevel &&
containingDeclaration is PackageFragmentDescriptor &&
descriptor is DeclarationDescriptorWithSource
) {
descriptor.source.containingFile.name?.let { sourceFileName ->
append(renderMessage(" in file "))
append(sourceFileName)
}
}
}
}
private fun StringBuilder.appendAnnotations(
annotated: Annotated,
placeEachAnnotationOnNewLine: Boolean = false,
target: AnnotationUseSiteTarget? = null
) {
if (DescriptorRendererModifier.ANNOTATIONS !in modifiers) return
val excluded = if (annotated is KotlinType) excludedTypeAnnotationClasses else excludedAnnotationClasses
val annotationFilter = annotationFilter
for (annotation in annotated.annotations) {
if (annotation.fqName !in excluded
&& !annotation.isParameterName()
&& (annotationFilter == null || annotationFilter(annotation))
) {
append(renderAnnotation(annotation, target))
if (placeEachAnnotationOnNewLine) {
appendLine()
} else {
append(" ")
}
}
}
}
protected fun AnnotationDescriptor.isParameterName(): Boolean {
return fqName == StandardNames.FqNames.parameterName
}
override fun renderAnnotation(annotation: AnnotationDescriptor, target: AnnotationUseSiteTarget?): String {
return buildString {
appendHighlighted("@") { asAnnotationName }
if (target != null) {
appendHighlighted(target.renderName) { asKeyword }
appendHighlighted(":") { asAnnotationName }
}
val annotationType = annotation.type
val renderedAnnotationName = withNoHighlighting { renderType(annotationType) }
appendHighlighted(renderedAnnotationName) { asAnnotationName }
if (includeAnnotationArguments) {
val arguments = renderAndSortAnnotationArguments(annotation)
if (includeEmptyAnnotationArguments || arguments.isNotEmpty()) {
arguments.joinTo(
this, highlight(", ") { asComma }, highlight("(") { asParentheses }, highlight(")") { asParentheses })
}
}
if (verbose && (annotationType.isError || annotationType.constructor.declarationDescriptor is NotFoundClasses.MockClassDescriptor)) {
appendHighlighted(" /* annotation class not found */") { asError }
}
}
}
private fun renderAndSortAnnotationArguments(descriptor: AnnotationDescriptor): List<String> {
val allValueArguments = descriptor.allValueArguments
val classDescriptor = if (renderDefaultAnnotationArguments) descriptor.annotationClass else null
val parameterDescriptorsWithDefaultValue = classDescriptor?.unsubstitutedPrimaryConstructor?.valueParameters
?.filter { it.declaresDefaultValue() }
?.map { it.name }
.orEmpty()
val defaultList = parameterDescriptorsWithDefaultValue
.filter { it !in allValueArguments }
.map {
buildString {
appendHighlighted(it.asString()) { asAnnotationAttributeName }
appendHighlighted(" = ") { asOperationSign }
appendHighlighted("...") { asInfo }
}
}
val argumentList = allValueArguments.entries
.map { (name, value) ->
buildString {
appendHighlighted(name.asString()) { asAnnotationAttributeName }
appendHighlighted(" = ") { asOperationSign }
if (name !in parameterDescriptorsWithDefaultValue) {
append(renderConstant(value))
} else {
appendHighlighted("...") { asInfo }
}
}
}
return (defaultList + argumentList).sorted()
}
private fun renderConstant(value: ConstantValue<*>): String {
return when (value) {
is ArrayValue -> {
buildString {
appendHighlighted("{") { asBraces }
value.value.joinTo(this, highlight(", ") { asComma }) { renderConstant(it) }
appendHighlighted("}") { asBraces }
}
}
is AnnotationValue -> renderAnnotation(value.value).removePrefix("@")
is KClassValue -> when (val classValue = value.value) {
is KClassValue.Value.LocalClass -> buildString {
appendHighlighted(classValue.type.toString()) { asClassName }
appendHighlighted("::") { asDoubleColon }
appendHighlighted("class") { asKeyword }
}
is KClassValue.Value.NormalClass -> {
var type = classValue.classId.asSingleFqName().asString()
repeat(classValue.arrayDimensions) {
type = buildString {
appendHighlighted("kotlin") { asClassName }
appendHighlighted(".") { asDot }
appendHighlighted("Array") { asClassName }
appendHighlighted("<") { asOperationSign }
append(type)
appendHighlighted(">") { asOperationSign }
}
}
buildString {
append(type)
appendHighlighted("::") { asDoubleColon }
appendHighlighted("class") { asKeyword }
}
}
}
else -> highlightByLexer(value.toString())
}
}
private fun StringBuilder.appendVisibility(visibility: DescriptorVisibility): Boolean {
@Suppress("NAME_SHADOWING")
var visibility = visibility
if (DescriptorRendererModifier.VISIBILITY !in modifiers) return false
if (normalizedVisibilities) {
visibility = visibility.normalize()
}
if (!renderDefaultVisibility && visibility == DescriptorVisibilities.DEFAULT_VISIBILITY) return false
append(renderKeyword(visibility.internalDisplayName))
append(" ")
return true
}
private fun StringBuilder.appendModality(modality: Modality, defaultModality: Modality) {
if (!renderDefaultModality && modality == defaultModality) return
appendModifier(DescriptorRendererModifier.MODALITY in modifiers, modality.name.toLowerCaseAsciiOnly())
}
private fun MemberDescriptor.implicitModalityWithoutExtensions(): Modality {
if (this is ClassDescriptor) {
return if (kind == ClassKind.INTERFACE) Modality.ABSTRACT else Modality.FINAL
}
val containingClassDescriptor = containingDeclaration as? ClassDescriptor ?: return Modality.FINAL
if (this !is CallableMemberDescriptor) return Modality.FINAL
if (this.overriddenDescriptors.isNotEmpty()) {
if (containingClassDescriptor.modality != Modality.FINAL) return Modality.OPEN
}
return if (containingClassDescriptor.kind == ClassKind.INTERFACE && this.visibility != DescriptorVisibilities.PRIVATE) {
if (this.modality == Modality.ABSTRACT) Modality.ABSTRACT else Modality.OPEN
} else
Modality.FINAL
}
private fun StringBuilder.appendModalityForCallable(callable: CallableMemberDescriptor) {
if (!DescriptorUtils.isTopLevelDeclaration(callable) || callable.modality != Modality.FINAL) {
if (overrideRenderingPolicy == OverrideRenderingPolicy.RENDER_OVERRIDE && callable.modality == Modality.OPEN &&
overridesSomething(callable)
) {
return
}
appendModality(callable.modality, callable.implicitModalityWithoutExtensions())
}
}
private fun StringBuilder.appendOverride(callableMember: CallableMemberDescriptor) {
if (DescriptorRendererModifier.OVERRIDE !in modifiers) return
if (overridesSomething(callableMember)) {
if (overrideRenderingPolicy != OverrideRenderingPolicy.RENDER_OPEN) {
appendModifier(true, "override")
if (verbose) {
appendHighlighted("/*${callableMember.overriddenDescriptors.size}*/ ") { asInfo }
}
}
}
}
private fun StringBuilder.appendMemberKind(callableMember: CallableMemberDescriptor) {
if (DescriptorRendererModifier.MEMBER_KIND !in modifiers) return
if (verbose && callableMember.kind != CallableMemberDescriptor.Kind.DECLARATION) {
appendHighlighted("/*${callableMember.kind.name.toLowerCaseAsciiOnly()}*/ ") { asInfo }
}
}
private fun StringBuilder.appendModifier(value: Boolean, modifier: String) {
if (value) {
append(renderKeyword(modifier))
append(" ")
}
}
private fun StringBuilder.appendMemberModifiers(descriptor: MemberDescriptor) {
appendModifier(descriptor.isExternal, "external")
appendModifier(DescriptorRendererModifier.EXPECT in modifiers && descriptor.isExpect, "expect")
appendModifier(DescriptorRendererModifier.ACTUAL in modifiers && descriptor.isActual, "actual")
}
private fun StringBuilder.appendAdditionalModifiers(functionDescriptor: FunctionDescriptor) {
val isOperator =
functionDescriptor.isOperator && (functionDescriptor.overriddenDescriptors.none { it.isOperator } || alwaysRenderModifiers)
val isInfix =
functionDescriptor.isInfix && (functionDescriptor.overriddenDescriptors.none { it.isInfix } || alwaysRenderModifiers)
appendModifier(functionDescriptor.isTailrec, "tailrec")
appendSuspendModifier(functionDescriptor)
appendModifier(functionDescriptor.isInline, "inline")
appendModifier(isInfix, "infix")
appendModifier(isOperator, "operator")
}
private fun StringBuilder.appendSuspendModifier(functionDescriptor: FunctionDescriptor) {
appendModifier(functionDescriptor.isSuspend, "suspend")
}
override fun render(declarationDescriptor: DeclarationDescriptor): String {
return buildString {
declarationDescriptor.accept(RenderDeclarationDescriptorVisitor(), this)
if (withDefinedIn) {
appendDefinedIn(declarationDescriptor)
}
}
}
/* TYPE PARAMETERS */
private fun StringBuilder.appendTypeParameter(typeParameter: TypeParameterDescriptor, topLevel: Boolean) {
if (topLevel) {
append(lt())
}
if (verbose) {
appendHighlighted("/*${typeParameter.index}*/ ") { asInfo }
}
appendModifier(typeParameter.isReified, "reified")
val variance = typeParameter.variance.label
appendModifier(variance.isNotEmpty(), variance)
appendAnnotations(typeParameter)
appendName(typeParameter, topLevel) { asTypeParameterName }
val upperBoundsCount = typeParameter.upperBounds.size
if ((upperBoundsCount > 1 && !topLevel) || upperBoundsCount == 1) {
val upperBound = typeParameter.upperBounds.iterator().next()
if (!KotlinBuiltIns.isDefaultBound(upperBound)) {
appendHighlighted(" : ") { asColon }
append(renderType(upperBound))
}
} else if (topLevel) {
var first = true
for (upperBound in typeParameter.upperBounds) {
if (KotlinBuiltIns.isDefaultBound(upperBound)) {
continue
}
if (first) {
appendHighlighted(" : ") { asColon }
} else {
appendHighlighted(" & ") { asOperationSign }
}
append(renderType(upperBound))
first = false
}
} else {
// rendered with "where"
}
if (topLevel) {
append(gt())
}
}
private fun StringBuilder.appendTypeParameters(typeParameters: List<TypeParameterDescriptor>, withSpace: Boolean) {
if (withoutTypeParameters) return
if (typeParameters.isNotEmpty()) {
append(lt())
appendTypeParameterList(typeParameters)
append(gt())
if (withSpace) {
append(" ")
}
}
}
private fun StringBuilder.appendTypeParameterList(typeParameters: List<TypeParameterDescriptor>) {
val iterator = typeParameters.iterator()
while (iterator.hasNext()) {
val typeParameterDescriptor = iterator.next()
appendTypeParameter(typeParameterDescriptor, false)
if (iterator.hasNext()) {
appendHighlighted(", ") { asComma }
}
}
}
/* FUNCTIONS */
private fun StringBuilder.appendFunction(function: FunctionDescriptor) {
if (!startFromName) {
if (!startFromDeclarationKeyword) {
appendAnnotations(function, eachAnnotationOnNewLine)
appendVisibility(function.visibility)
appendModalityForCallable(function)
if (includeAdditionalModifiers) {
appendMemberModifiers(function)
}
appendOverride(function)
if (includeAdditionalModifiers) {
appendAdditionalModifiers(function)
} else {
appendSuspendModifier(function)
}
appendMemberKind(function)
if (verbose) {
if (function.isHiddenToOvercomeSignatureClash) {
appendHighlighted("/*isHiddenToOvercomeSignatureClash*/ ") { asInfo }
}
if (function.isHiddenForResolutionEverywhereBesideSupercalls) {
appendHighlighted("/*isHiddenForResolutionEverywhereBesideSupercalls*/ ") { asInfo }
}
}
}
append(renderKeyword("fun"))
append(" ")
appendTypeParameters(function.typeParameters, true)
appendReceiver(function)
}
appendName(function, true) { asFunDeclaration }
appendValueParameters(function.valueParameters, function.hasSynthesizedParameterNames())
appendReceiverAfterName(function)
val returnType = function.returnType
if (!withoutReturnType && (unitReturnType || (returnType == null || !KotlinBuiltIns.isUnit(returnType)))) {
appendHighlighted(": ") { asColon }
append(if (returnType == null) highlight("[NULL]") { asError } else renderType(returnType))
}
appendWhereSuffix(function.typeParameters)
}
private fun StringBuilder.appendReceiverAfterName(callableDescriptor: CallableDescriptor) {
if (!receiverAfterName) return
val receiver = callableDescriptor.extensionReceiverParameter
if (receiver != null) {
appendHighlighted(" on ") { asInfo }
append(renderType(receiver.type))
}
}
private fun StringBuilder.appendReceiver(callableDescriptor: CallableDescriptor) {
val receiver = callableDescriptor.extensionReceiverParameter
if (receiver != null) {
appendAnnotations(receiver, target = AnnotationUseSiteTarget.RECEIVER)
val type = receiver.type
var result = renderType(type)
if (shouldRenderAsPrettyFunctionType(type) && !TypeUtils.isNullableType(type)) {
result = "${highlight("(") { asParentheses }}$result${highlight(")") { asParentheses }}"
}
append(result)
appendHighlighted(".") { asDot }
}
}
private fun StringBuilder.appendConstructor(constructor: ConstructorDescriptor) {
appendAnnotations(constructor)
val visibilityRendered = (options.renderDefaultVisibility || constructor.constructedClass.modality != Modality.SEALED)
&& appendVisibility(constructor.visibility)
appendMemberKind(constructor)
val constructorKeywordRendered = renderConstructorKeyword || !constructor.isPrimary || visibilityRendered
if (constructorKeywordRendered) {
append(renderKeyword("constructor"))
}
val classDescriptor = constructor.containingDeclaration
if (secondaryConstructorsAsPrimary) {
if (constructorKeywordRendered) {
append(" ")
}
appendName(classDescriptor, true) { asClassName }
appendTypeParameters(constructor.typeParameters, false)
}
appendValueParameters(constructor.valueParameters, constructor.hasSynthesizedParameterNames())
if (renderConstructorDelegation && !constructor.isPrimary && classDescriptor is ClassDescriptor) {
val primaryConstructor = classDescriptor.unsubstitutedPrimaryConstructor
if (primaryConstructor != null) {
val parametersWithoutDefault = primaryConstructor.valueParameters.filter {
!it.declaresDefaultValue() && it.varargElementType == null
}
if (parametersWithoutDefault.isNotEmpty()) {
appendHighlighted(" : ") { asColon }
append(renderKeyword("this"))
append(parametersWithoutDefault.joinToString(
prefix = highlight("(") { asParentheses },
separator = highlight(", ") { asComma },
postfix = highlight(")") { asParentheses }
) { "" }
)
}
}
}
if (secondaryConstructorsAsPrimary) {
appendWhereSuffix(constructor.typeParameters)
}
}
private fun StringBuilder.appendWhereSuffix(typeParameters: List<TypeParameterDescriptor>) {
if (withoutTypeParameters) return
val upperBoundStrings = ArrayList<String>(0)
for (typeParameter in typeParameters) {
typeParameter.upperBounds
.drop(1) // first parameter is rendered by renderTypeParameter
.mapTo(upperBoundStrings) {
buildString {
appendHighlighted(renderName(typeParameter.name, false)) { asTypeParameterName }
appendHighlighted(" : ") { asColon }
append(renderType(it))
}
}
}
if (upperBoundStrings.isNotEmpty()) {
append(" ")
append(renderKeyword("where"))
append(" ")
upperBoundStrings.joinTo(this, highlight(", ") { asComma })
}
}
override fun renderValueParameters(parameters: Collection<ValueParameterDescriptor>, synthesizedParameterNames: Boolean) = buildString {
appendValueParameters(parameters, synthesizedParameterNames)
}
private fun StringBuilder.appendValueParameters(
parameters: Collection<ValueParameterDescriptor>,
synthesizedParameterNames: Boolean
) {
val includeNames = shouldRenderParameterNames(synthesizedParameterNames)
val parameterCount = parameters.size
valueParametersHandler.appendBeforeValueParameters(parameterCount, this)
for ((index, parameter) in parameters.withIndex()) {
valueParametersHandler.appendBeforeValueParameter(parameter, index, parameterCount, this)
appendValueParameter(parameter, includeNames, false)
valueParametersHandler.appendAfterValueParameter(parameter, index, parameterCount, this)
}
valueParametersHandler.appendAfterValueParameters(parameterCount, this)
}
private fun shouldRenderParameterNames(synthesizedParameterNames: Boolean): Boolean = when (parameterNameRenderingPolicy) {
ParameterNameRenderingPolicy.ALL -> true
ParameterNameRenderingPolicy.ONLY_NON_SYNTHESIZED -> !synthesizedParameterNames
ParameterNameRenderingPolicy.NONE -> false
}
/* VARIABLES */
private fun StringBuilder.appendValueParameter(
valueParameter: ValueParameterDescriptor,
includeName: Boolean,
topLevel: Boolean
) {
if (topLevel) {
append(renderKeyword("value-parameter"))
append(" ")
}
if (verbose) {
appendHighlighted("/*${valueParameter.index}*/ ") { asInfo }
}
appendAnnotations(valueParameter)
appendModifier(valueParameter.isCrossinline, "crossinline")
appendModifier(valueParameter.isNoinline, "noinline")
val isPrimaryConstructor = renderPrimaryConstructorParametersAsProperties &&
(valueParameter.containingDeclaration as? ClassConstructorDescriptor)?.isPrimary == true
if (isPrimaryConstructor) {
appendModifier(actualPropertiesInPrimaryConstructor, "actual")
}
appendVariable(valueParameter, includeName, topLevel, isPrimaryConstructor)
val withDefaultValue =
defaultParameterValueRenderer != null &&
(if (debugMode) valueParameter.declaresDefaultValue() else valueParameter.declaresOrInheritsDefaultValue())
if (withDefaultValue) {
appendHighlighted(" = ") { asOperationSign }
append(highlightByLexer(defaultParameterValueRenderer!!(valueParameter)))
}
}
private fun StringBuilder.appendValVarPrefix(variable: VariableDescriptor, isInPrimaryConstructor: Boolean = false) {
if (isInPrimaryConstructor || variable !is ValueParameterDescriptor) {
if (variable.isVar) {
appendHighlighted("var") { asVar }
} else {
appendHighlighted("val") { asVal }
}
append(" ")
}
}
private fun StringBuilder.appendVariable(
variable: VariableDescriptor,
includeName: Boolean,
topLevel: Boolean,
isInPrimaryConstructor: Boolean = false
) {
val realType = variable.type
val varargElementType = (variable as? ValueParameterDescriptor)?.varargElementType
val typeToRender = varargElementType ?: realType
appendModifier(varargElementType != null, "vararg")
if (isInPrimaryConstructor || topLevel && !startFromName) {
appendValVarPrefix(variable, isInPrimaryConstructor)
}
if (includeName) {
appendName(variable, topLevel) { asLocalVarOrVal }
appendHighlighted(": ") { asColon }
}
append(renderType(typeToRender))
appendInitializer(variable)
if (verbose && varargElementType != null) {
val expandedType = withNoHighlighting { renderType(realType) }
appendHighlighted(" /*${expandedType}*/") { asInfo }
}
}
private fun StringBuilder.appendProperty(property: PropertyDescriptor) {
if (!startFromName) {
if (!startFromDeclarationKeyword) {
appendPropertyAnnotations(property)
appendVisibility(property.visibility)
appendModifier(DescriptorRendererModifier.CONST in modifiers && property.isConst, "const")
appendMemberModifiers(property)
appendModalityForCallable(property)
appendOverride(property)
appendModifier(DescriptorRendererModifier.LATEINIT in modifiers && property.isLateInit, "lateinit")
appendMemberKind(property)
}
appendValVarPrefix(property)
appendTypeParameters(property.typeParameters, true)
appendReceiver(property)
}
appendName(property, true) { asInstanceProperty }
appendHighlighted(": ") { asColon }
append(renderType(property.type))
appendReceiverAfterName(property)
appendInitializer(property)
appendWhereSuffix(property.typeParameters)
}
private fun StringBuilder.appendPropertyAnnotations(property: PropertyDescriptor) {
if (DescriptorRendererModifier.ANNOTATIONS !in modifiers) return
appendAnnotations(property, eachAnnotationOnNewLine)
property.backingField?.let { appendAnnotations(it, target = AnnotationUseSiteTarget.FIELD) }
property.delegateField?.let { appendAnnotations(it, target = AnnotationUseSiteTarget.PROPERTY_DELEGATE_FIELD) }
if (propertyAccessorRenderingPolicy == PropertyAccessorRenderingPolicy.NONE) {
property.getter?.let {
appendAnnotations(it, target = AnnotationUseSiteTarget.PROPERTY_GETTER)
}
property.setter?.let { setter ->
setter.let {
appendAnnotations(it, target = AnnotationUseSiteTarget.PROPERTY_SETTER)
}
setter.valueParameters.single().let {
appendAnnotations(it, target = AnnotationUseSiteTarget.SETTER_PARAMETER)
}
}
}
}
private fun StringBuilder.appendInitializer(variable: VariableDescriptor) {
if (includePropertyConstant) {
variable.compileTimeInitializer?.let { constant ->
appendHighlighted(" = ") { asOperationSign }
append(escape(renderConstant(constant)))
}
}
}
private fun StringBuilder.appendTypeAlias(typeAlias: TypeAliasDescriptor) {
appendAnnotations(typeAlias, eachAnnotationOnNewLine)
appendVisibility(typeAlias.visibility)
appendMemberModifiers(typeAlias)
append(renderKeyword("typealias"))
append(" ")
appendName(typeAlias, true) { asTypeAlias }
appendTypeParameters(typeAlias.declaredTypeParameters, false)
appendCapturedTypeParametersIfRequired(typeAlias)
appendHighlighted(" = ") { asOperationSign }
append(renderType(typeAlias.underlyingType))
}
private fun StringBuilder.appendCapturedTypeParametersIfRequired(classifier: ClassifierDescriptorWithTypeParameters) {
val typeParameters = classifier.declaredTypeParameters
val typeConstructorParameters = classifier.typeConstructor.parameters
if (verbose && classifier.isInner && typeConstructorParameters.size > typeParameters.size) {
val capturedTypeParametersInfo = buildString {
append(" /*captured type parameters: ")
withNoHighlighting {
appendTypeParameterList(typeConstructorParameters.subList(typeParameters.size, typeConstructorParameters.size))
}
append("*/")
}
appendHighlighted(capturedTypeParametersInfo) { asInfo }
}
}
/* CLASSES */
private fun StringBuilder.appendClass(klass: ClassDescriptor) {
val isEnumEntry = klass.kind == ClassKind.ENUM_ENTRY
if (!startFromName) {
appendAnnotations(klass, eachAnnotationOnNewLine)
if (!isEnumEntry) {
appendVisibility(klass.visibility)
}
if (!(klass.kind == ClassKind.INTERFACE && klass.modality == Modality.ABSTRACT ||
klass.kind.isSingleton && klass.modality == Modality.FINAL)
) {
appendModality(klass.modality, klass.implicitModalityWithoutExtensions())
}
appendMemberModifiers(klass)
appendModifier(DescriptorRendererModifier.INNER in modifiers && klass.isInner, "inner")
appendModifier(DescriptorRendererModifier.DATA in modifiers && klass.isData, "data")
appendModifier(DescriptorRendererModifier.INLINE in modifiers && klass.isInline, "inline")
appendModifier(DescriptorRendererModifier.VALUE in modifiers && klass.isValue, "value")
appendModifier(DescriptorRendererModifier.FUN in modifiers && klass.isFun, "fun")
appendClassKindPrefix(klass)
}
if (!isCompanionObject(klass)) {
if (!startFromName) appendSpaceIfNeeded()
appendName(klass, true) { asClassName }
} else {
appendCompanionObjectName(klass)
}
if (isEnumEntry) return
val typeParameters = klass.declaredTypeParameters
appendTypeParameters(typeParameters, false)
appendCapturedTypeParametersIfRequired(klass)
val primaryConstructor = klass.unsubstitutedPrimaryConstructor
if (primaryConstructor != null &&
(klass.isData && options.dataClassWithPrimaryConstructor || !klass.kind.isSingleton && classWithPrimaryConstructor)
) {
if (!klass.isData || !primaryConstructor.annotations.isEmpty()) {
append(" ")
appendAnnotations(primaryConstructor)
appendVisibility(primaryConstructor.visibility)
append(renderKeyword("constructor"))
}
appendValueParameters(primaryConstructor.valueParameters, primaryConstructor.hasSynthesizedParameterNames())
appendSuperTypes(klass, indent = " ")
} else {
appendSuperTypes(klass, prefix = "\n ")
}
appendWhereSuffix(typeParameters)
}
private fun StringBuilder.appendSuperTypes(klass: ClassDescriptor, prefix: String = " ", indent: String = " ") {
if (withoutSuperTypes) return
if (KotlinBuiltIns.isNothing(klass.defaultType)) return
val supertypes = klass.typeConstructor.supertypes.toMutableList()
if (klass.kind == ClassKind.ENUM_CLASS) {
supertypes.removeIf { KotlinBuiltIns.isEnum(it) }
}
if (supertypes.isEmpty() || supertypes.size == 1 && KotlinBuiltIns.isAnyOrNullableAny(supertypes.iterator().next())) return
append(prefix)
appendHighlighted(": ") { asColon }
val separator = when {
supertypes.size <= 3 -> ", "
else -> ",\n$indent "
}
supertypes.joinTo(this, highlight(separator) { asComma }) { renderType(it) }
}
private fun StringBuilder.appendClassKindPrefix(klass: ClassDescriptor) {
append(renderKeyword(getClassifierKindPrefix(klass)))
}
/* OTHER */
private fun StringBuilder.appendPackageView(packageView: PackageViewDescriptor) {
appendPackageHeader(packageView.fqName, "package")
if (debugMode) {
appendHighlighted(" in context of ") { asInfo }
appendName(packageView.module, false) { asPackageName }
}
}
private fun StringBuilder.appendPackageFragment(fragment: PackageFragmentDescriptor) {
appendPackageHeader(fragment.fqName, "package-fragment")
if (debugMode) {
appendHighlighted(" in ") { asInfo }
appendName(fragment.containingDeclaration, false) { asPackageName }
}
}
private fun StringBuilder.appendPackageHeader(fqName: FqName, fragmentOrView: String) {
append(renderKeyword(fragmentOrView))
val fqNameString = renderFqName(fqName.toUnsafe())
if (fqNameString.isNotEmpty()) {
append(" ")
append(fqNameString)
}
}
private fun StringBuilder.appendAccessorModifiers(descriptor: PropertyAccessorDescriptor) {
appendMemberModifiers(descriptor)
}
/* STUPID DISPATCH-ONLY VISITOR */
private inner class RenderDeclarationDescriptorVisitor : DeclarationDescriptorVisitor<Unit, StringBuilder> {
override fun visitValueParameterDescriptor(descriptor: ValueParameterDescriptor, builder: StringBuilder) {
builder.appendValueParameter(descriptor, true, true)
}
override fun visitVariableDescriptor(descriptor: VariableDescriptor, builder: StringBuilder) {
builder.appendVariable(descriptor, true, true)
}
override fun visitPropertyDescriptor(descriptor: PropertyDescriptor, builder: StringBuilder) {
builder.appendProperty(descriptor)
}
override fun visitPropertyGetterDescriptor(descriptor: PropertyGetterDescriptor, builder: StringBuilder) {
visitPropertyAccessorDescriptor(descriptor, builder, "getter")
}
override fun visitPropertySetterDescriptor(descriptor: PropertySetterDescriptor, builder: StringBuilder) {
visitPropertyAccessorDescriptor(descriptor, builder, "setter")
}
private fun visitPropertyAccessorDescriptor(descriptor: PropertyAccessorDescriptor, builder: StringBuilder, kind: String) {
when (propertyAccessorRenderingPolicy) {
PropertyAccessorRenderingPolicy.PRETTY -> {
builder.appendAccessorModifiers(descriptor)
builder.appendHighlighted("$kind for ") { asInfo }
builder.appendProperty(descriptor.correspondingProperty)
}
PropertyAccessorRenderingPolicy.DEBUG -> {
visitFunctionDescriptor(descriptor, builder)
}
PropertyAccessorRenderingPolicy.NONE -> {
}
}
}
override fun visitFunctionDescriptor(descriptor: FunctionDescriptor, builder: StringBuilder) {
builder.appendFunction(descriptor)
}
override fun visitReceiverParameterDescriptor(descriptor: ReceiverParameterDescriptor, builder: StringBuilder) {
builder.append(descriptor.name) // renders <this>
}
override fun visitConstructorDescriptor(constructorDescriptor: ConstructorDescriptor, builder: StringBuilder) {
builder.appendConstructor(constructorDescriptor)
}
override fun visitTypeParameterDescriptor(descriptor: TypeParameterDescriptor, builder: StringBuilder) {
builder.appendTypeParameter(descriptor, true)
}
override fun visitPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor, builder: StringBuilder) {
builder.appendPackageFragment(descriptor)
}
override fun visitPackageViewDescriptor(descriptor: PackageViewDescriptor, builder: StringBuilder) {
builder.appendPackageView(descriptor)
}
override fun visitModuleDeclaration(descriptor: ModuleDescriptor, builder: StringBuilder) {
builder.appendName(descriptor, true) { asPackageName }
}
override fun visitScriptDescriptor(scriptDescriptor: ScriptDescriptor, builder: StringBuilder) {
visitClassDescriptor(scriptDescriptor, builder)
}
override fun visitClassDescriptor(descriptor: ClassDescriptor, builder: StringBuilder) {
builder.appendClass(descriptor)
}
override fun visitTypeAliasDescriptor(descriptor: TypeAliasDescriptor, builder: StringBuilder) {
builder.appendTypeAlias(descriptor)
}
}
private fun StringBuilder.appendSpaceIfNeeded() {
if (isEmpty() || this[length - 1] != ' ') {
append(' ')
}
}
private fun replacePrefixes(
lowerRendered: String,
lowerPrefix: String,
upperRendered: String,
upperPrefix: String,
foldedPrefix: String
): String? {
if (lowerRendered.startsWith(lowerPrefix) && upperRendered.startsWith(upperPrefix)) {
val lowerWithoutPrefix = lowerRendered.substring(lowerPrefix.length)
val upperWithoutPrefix = upperRendered.substring(upperPrefix.length)
val flexibleCollectionName = foldedPrefix + lowerWithoutPrefix
return when {
lowerWithoutPrefix == upperWithoutPrefix -> flexibleCollectionName
differsOnlyInNullability(lowerWithoutPrefix, upperWithoutPrefix) -> "$flexibleCollectionName!"
else -> null
}
}
return null
}
private fun differsOnlyInNullability(lower: String, upper: String) =
lower == upper.replace("?", "") || upper.endsWith("?") && ("$lower?") == upper || "($lower)?" == upper
private fun overridesSomething(callable: CallableMemberDescriptor) = !callable.overriddenDescriptors.isEmpty()
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/surroundWithArrayOfForNamedArgumentsToVarargs/replaceForVarargOfAny.kt | 5 | 147 | // "Surround with *arrayOf(...)" "true"
// LANGUAGE_VERSION: 1.2
fun anyFoo(vararg a: Any) {}
fun test() {
anyFoo(a = intArr<caret>ayOf(1))
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/whenWithOnlyElse/subjectVariable/singleElse/singleReference.kt | 4 | 146 | // WITH_RUNTIME
fun test() {
when<caret> (val a = create()) {
else -> use(a)
}
}
fun create(): String = ""
fun use(s: String) {} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/filterTextAny.kt | 1 | 74 | // WITH_RUNTIME
fun main() {
"abc".<caret>filter { it == 'a' }.any()
} | apache-2.0 |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/ChangeTypeFixUtils.kt | 3 | 2928 | // 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 org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
object ChangeTypeFixUtils {
fun familyName(): String = KotlinBundle.message("fix.change.return.type.family")
fun functionOrConstructorParameterPresentation(element: KtCallableDeclaration, containerName: String?): String? {
val name = element.name
return if (name != null) {
val fullName = if (containerName != null) "'${containerName}.$name'" else "'$name'"
when (element) {
is KtParameter -> KotlinBundle.message("fix.change.return.type.presentation.property", fullName)
is KtProperty -> KotlinBundle.message("fix.change.return.type.presentation.property", fullName)
else -> KotlinBundle.message("fix.change.return.type.presentation.function", fullName)
}
} else null
}
fun baseFunctionOrConstructorParameterPresentation(presentation: String): String =
KotlinBundle.message("fix.change.return.type.presentation.base", presentation)
fun baseFunctionOrConstructorParameterPresentation(element: KtCallableDeclaration, containerName: String?): String? {
val presentation = functionOrConstructorParameterPresentation(element, containerName) ?: return null
return baseFunctionOrConstructorParameterPresentation(presentation)
}
fun getTextForQuickFix(
element: KtCallableDeclaration,
presentation: String?,
isUnitType: Boolean,
typePresentation: String
): String {
if (isUnitType && element is KtFunction && element.hasBlockBody()) {
return if (presentation == null)
KotlinBundle.message("fix.change.return.type.remove.explicit.return.type")
else
KotlinBundle.message("fix.change.return.type.remove.explicit.return.type.of", presentation)
}
return when (element) {
is KtFunction -> {
if (presentation != null)
KotlinBundle.message("fix.change.return.type.return.type.text.of", presentation, typePresentation)
else
KotlinBundle.message("fix.change.return.type.return.type.text", typePresentation)
}
else -> {
if (presentation != null)
KotlinBundle.message("fix.change.return.type.type.text.of", presentation, typePresentation)
else
KotlinBundle.message("fix.change.return.type.type.text", typePresentation)
}
}
}
} | apache-2.0 |
dkrivoruchko/ScreenStream | mjpeg/src/main/kotlin/info/dvkr/screenstream/mjpeg/state/MjpegStateMachine.kt | 1 | 21301 | package info.dvkr.screenstream.mjpeg.state
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import com.elvishew.xlog.XLog
import info.dvkr.screenstream.common.AppError
import info.dvkr.screenstream.common.AppStateMachine
import info.dvkr.screenstream.common.getLog
import info.dvkr.screenstream.common.settings.AppSettings
import info.dvkr.screenstream.mjpeg.*
import info.dvkr.screenstream.mjpeg.httpserver.HttpServer
import info.dvkr.screenstream.mjpeg.image.BitmapCapture
import info.dvkr.screenstream.mjpeg.image.NotificationBitmap
import info.dvkr.screenstream.mjpeg.settings.MjpegSettings
import info.dvkr.screenstream.mjpeg.state.helper.BroadcastHelper
import info.dvkr.screenstream.mjpeg.state.helper.ConnectivityHelper
import info.dvkr.screenstream.mjpeg.state.helper.NetworkHelper
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.util.concurrent.LinkedBlockingDeque
class MjpegStateMachine(
private val serviceContext: Context,
private val appSettings: AppSettings,
private val mjpegSettings: MjpegSettings,
private val effectSharedFlow: MutableSharedFlow<AppStateMachine.Effect>,
private val onSlowConnectionDetected: () -> Unit
) : AppStateMachine {
private val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
XLog.e(getLog("onCoroutineException"), throwable)
onError(CoroutineException)
}
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default + coroutineExceptionHandler)
private val bitmapStateFlow = MutableStateFlow(Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888))
private val projectionManager = serviceContext.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
private val projectionCallback = object : MediaProjection.Callback() {
override fun onStop() {
XLog.i([email protected]("MediaProjection.Callback", "onStop"))
sendEvent(AppStateMachine.Event.StopStream)
}
}
private val broadcastHelper = BroadcastHelper.getInstance(serviceContext)
private val connectivityHelper: ConnectivityHelper = ConnectivityHelper.getInstance(serviceContext)
private val networkHelper = NetworkHelper(serviceContext)
private val notificationBitmap = NotificationBitmap(serviceContext, mjpegSettings)
private val httpServer = HttpServer(serviceContext, coroutineScope, mjpegSettings, bitmapStateFlow.asStateFlow(), notificationBitmap)
private var mediaProjectionIntent: Intent? = null
private val powerManager = serviceContext.getSystemService(Context.POWER_SERVICE) as PowerManager
private var wakeLock: PowerManager.WakeLock? = null
internal sealed class InternalEvent : AppStateMachine.Event() {
object DiscoverAddress : InternalEvent()
object StartServer : InternalEvent()
data class ComponentError(val appError: AppError) : InternalEvent()
object StartStopFromWebPage : InternalEvent()
data class RestartServer(val reason: RestartReason) : InternalEvent()
object ScreenOff : InternalEvent()
object Destroy : InternalEvent()
override fun toString(): String = javaClass.simpleName
}
internal sealed class RestartReason(private val msg: String) {
class ConnectionChanged(msg: String) : RestartReason(msg)
class SettingsChanged(msg: String) : RestartReason(msg)
class NetworkSettingsChanged(msg: String) : RestartReason(msg)
override fun toString(): String = "${javaClass.simpleName}[$msg]"
}
override fun sendEvent(event: AppStateMachine.Event, timeout: Long) {
if (timeout > 0) {
XLog.d(getLog("sendEvent[Timeout: $timeout]", "Event: $event"))
coroutineScope.launch { delay(timeout); sendEvent(event) }
return
}
XLog.d(getLog("sendEvent", "Event: $event"))
runCatching {
eventDeque.addLast(event)
eventSharedFlow.tryEmit(event) || throw IllegalStateException("eventSharedFlow IsFull")
XLog.d(getLog("sendEvent", "Pending events => $eventDeque"))
}.onFailure { cause ->
XLog.e(getLog("sendEvent", "Pending events => $eventDeque"), cause)
coroutineScope.launch(NonCancellable) {
streamState = componentError(streamState, ChannelException, true)
effectSharedFlow.emit(streamState.toPublicState())
}
}
}
private var streamState = StreamState()
private var previousStreamState = StreamState()
private val eventSharedFlow = MutableSharedFlow<AppStateMachine.Event>(replay = 5, extraBufferCapacity = 8)
private val eventDeque = LinkedBlockingDeque<AppStateMachine.Event>()
init {
XLog.d(getLog("init"))
coroutineScope.launch {
if (mjpegSettings.enablePinFlow.first() && mjpegSettings.newPinOnAppStartFlow.first())
mjpegSettings.setPin(randomPin())
}
coroutineScope.launch(CoroutineName("MjpegAppStateMachine.eventSharedFlow")) {
eventSharedFlow.onEach { event ->
XLog.d([email protected]("eventSharedFlow.onEach", "$event"))
if (StateToEventMatrix.skippEvent(streamState.state, event).not()) {
previousStreamState = streamState
streamState = when (event) {
is InternalEvent.DiscoverAddress -> discoverAddress(streamState)
is InternalEvent.StartServer -> startServer(streamState)
is InternalEvent.ComponentError -> componentError(streamState, event.appError, false)
is InternalEvent.StartStopFromWebPage -> startStopFromWebPage(streamState)
is InternalEvent.RestartServer -> restartServer(streamState, event.reason)
is InternalEvent.ScreenOff -> screenOff(streamState)
is InternalEvent.Destroy -> destroy(streamState)
is AppStateMachine.Event.StartStream -> startStream(streamState)
is AppStateMachine.Event.CastPermissionsDenied -> castPermissionsDenied(streamState)
is AppStateMachine.Event.StartProjection -> startProjection(streamState, event.intent)
is AppStateMachine.Event.StopStream -> stopStream(streamState)
is AppStateMachine.Event.RequestPublicState -> requestPublicState(streamState)
is AppStateMachine.Event.RecoverError -> recoverError(streamState)
else -> throw IllegalArgumentException("Unknown AppStateMachine.Event: $event")
}
if (streamState.isPublicStatePublishRequired(previousStreamState)) effectSharedFlow.emit(streamState.toPublicState())
XLog.i([email protected]("eventSharedFlow.onEach", "New state:${streamState.state}"))
}
eventDeque.pollFirst()
XLog.d([email protected]("eventSharedFlow.onEach.done", eventDeque.toString()))
}
.catch { cause ->
XLog.e([email protected]("eventSharedFlow.catch"), cause)
streamState = componentError(streamState, CoroutineException, true)
effectSharedFlow.emit(streamState.toPublicState())
}
.collect()
}
mjpegSettings.htmlEnableButtonsFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.HTML_ENABLE_BUTTONS.name)))
}
mjpegSettings.htmlBackColorFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.HTML_BACK_COLOR.name)))
}
mjpegSettings.enablePinFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.ENABLE_PIN.name)))
}
mjpegSettings.pinFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.PIN.name)))
}
mjpegSettings.blockAddressFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.SettingsChanged(MjpegSettings.Key.BLOCK_ADDRESS.name)))
}
mjpegSettings.useWiFiOnlyFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.USE_WIFI_ONLY.name)))
}
mjpegSettings.enableIPv6Flow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.ENABLE_IPV6.name)))
}
mjpegSettings.enableLocalHostFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.ENABLE_LOCAL_HOST.name)))
}
mjpegSettings.localHostOnlyFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.LOCAL_HOST_ONLY.name)))
}
mjpegSettings.serverPortFlow.listenForChange(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.NetworkSettingsChanged(MjpegSettings.Key.SERVER_PORT.name)))
}
broadcastHelper.startListening(
onScreenOff = { sendEvent(InternalEvent.ScreenOff) },
onConnectionChanged = { sendEvent(InternalEvent.RestartServer(RestartReason.ConnectionChanged("BroadcastHelper"))) }
)
connectivityHelper.startListening(coroutineScope) {
sendEvent(InternalEvent.RestartServer(RestartReason.ConnectionChanged("ConnectivityHelper")))
}
coroutineScope.launch(CoroutineName("MjpegStateMachine.httpServer.eventSharedFlow")) {
httpServer.eventSharedFlow.onEach { event ->
if (event !is HttpServer.Event.Statistic)
XLog.d([email protected]("httpServer.eventSharedFlow.onEach", "$event"))
when (event) {
is HttpServer.Event.Action ->
when (event) {
is HttpServer.Event.Action.StartStopRequest -> sendEvent(InternalEvent.StartStopFromWebPage)
}
is HttpServer.Event.Statistic ->
when (event) {
is HttpServer.Event.Statistic.Clients -> {
effectSharedFlow.emit(AppStateMachine.Effect.Statistic.Clients(event.clients))
if (appSettings.autoStartStopFlow.first()) checkAutoStartStop(event.clients)
if (mjpegSettings.notifySlowConnectionsFlow.first()) checkForSlowClients(event.clients)
}
is HttpServer.Event.Statistic.Traffic ->
effectSharedFlow.emit(AppStateMachine.Effect.Statistic.Traffic(event.traffic))
}
is HttpServer.Event.Error -> onError(event.error)
}
}
.catch { cause ->
XLog.e([email protected]("httpServer.eventSharedFlow.catch"), cause)
onError(CoroutineException)
}
.collect()
}
}
private var slowClients: List<MjpegClient> = emptyList()
private fun checkForSlowClients(clients: List<MjpegClient>) {
val currentSlowConnections = clients.filter { it.isSlowConnection }.toList()
if (slowClients.containsAll(currentSlowConnections).not()) onSlowConnectionDetected()
slowClients = currentSlowConnections
}
private fun checkAutoStartStop(clients: List<MjpegClient>) {
if (clients.isNotEmpty() && streamState.isStreaming().not()) {
XLog.d(getLog("checkAutoStartStop", "Auto starting"))
sendEvent(AppStateMachine.Event.StartStream)
}
if (clients.isEmpty() && streamState.isStreaming()) {
XLog.d(getLog("checkAutoStartStop", "Auto stopping"))
sendEvent(AppStateMachine.Event.StopStream)
}
}
override fun destroy() {
XLog.d(getLog("destroy"))
wakeLock?.release()
wakeLock = null
sendEvent(InternalEvent.Destroy)
try {
runBlocking(coroutineScope.coroutineContext) { withTimeout(1000) { httpServer.destroy().await() } }
} catch (cause: Throwable) {
XLog.e(getLog("destroy", cause.toString()))
}
broadcastHelper.stopListening()
connectivityHelper.stopListening()
coroutineScope.cancel()
mediaProjectionIntent = null
}
private fun onError(appError: AppError) {
XLog.e(getLog("onError", "AppError: $appError"))
wakeLock?.release()
wakeLock = null
sendEvent(InternalEvent.ComponentError(appError))
}
private fun stopProjection(streamState: StreamState): StreamState {
XLog.d(getLog("stopProjection"))
if (streamState.isStreaming()) {
streamState.bitmapCapture?.destroy()
streamState.mediaProjection?.unregisterCallback(projectionCallback)
streamState.mediaProjection?.stop()
}
wakeLock?.release()
wakeLock = null
return streamState.copy(mediaProjection = null, bitmapCapture = null)
}
private suspend fun discoverAddress(streamState: StreamState): StreamState {
XLog.d(getLog("discoverAddress"))
val netInterfaces = networkHelper.getNetInterfaces(
mjpegSettings.useWiFiOnlyFlow.first(), mjpegSettings.enableIPv6Flow.first(),
mjpegSettings.enableLocalHostFlow.first(), mjpegSettings.localHostOnlyFlow.first()
)
if (netInterfaces.isEmpty())
return if (streamState.httpServerAddressAttempt < 3) {
sendEvent(InternalEvent.DiscoverAddress, 1000)
streamState.copy(httpServerAddressAttempt = streamState.httpServerAddressAttempt + 1)
} else {
XLog.w(getLog("discoverAddress", "No address found"))
streamState.copy(
state = StreamState.State.ERROR,
netInterfaces = emptyList(),
httpServerAddressAttempt = 0,
appError = AddressNotFoundException
)
}
sendEvent(InternalEvent.StartServer)
return streamState.copy(
state = StreamState.State.ADDRESS_DISCOVERED,
netInterfaces = netInterfaces,
httpServerAddressAttempt = 0
)
}
private suspend fun startServer(streamState: StreamState): StreamState {
XLog.d(getLog("startServer"))
require(streamState.netInterfaces.isNotEmpty())
withTimeoutOrNull(300) { httpServer.stop().await() }
httpServer.start(streamState.netInterfaces)
bitmapStateFlow.tryEmit(notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.START))
return streamState.copy(state = StreamState.State.SERVER_STARTED)
}
private fun startStream(streamState: StreamState): StreamState {
XLog.d(getLog("startStream"))
return if (mediaProjectionIntent != null) {
sendEvent(AppStateMachine.Event.StartProjection(mediaProjectionIntent!!))
streamState
} else {
streamState.copy(state = StreamState.State.PERMISSION_PENDING)
}
}
private fun castPermissionsDenied(streamState: StreamState): StreamState {
XLog.d(getLog("castPermissionsDenied"))
return streamState.copy(state = StreamState.State.SERVER_STARTED)
}
private suspend fun startProjection(streamState: StreamState, intent: Intent): StreamState {
XLog.d(getLog("startProjection", "Intent: $intent"))
try {
val mediaProjection = withContext(Dispatchers.Main) {
delay(500)
projectionManager.getMediaProjection(Activity.RESULT_OK, intent).apply {
registerCallback(projectionCallback, Handler(Looper.getMainLooper()))
}
}
mediaProjectionIntent = intent
val bitmapCapture = BitmapCapture(serviceContext, mjpegSettings, mediaProjection, bitmapStateFlow, ::onError)
bitmapCapture.start()
if (appSettings.keepAwakeFlow.first()) {
@Suppress("DEPRECATION")
@SuppressLint("WakelockTimeout")
wakeLock = powerManager.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "ScreenStream::StreamingTag"
).apply { acquire() }
}
return streamState.copy(
state = StreamState.State.STREAMING,
mediaProjection = mediaProjection,
bitmapCapture = bitmapCapture
)
} catch (cause: Throwable) {
XLog.e(getLog("startProjection"), cause)
}
mediaProjectionIntent = null
return streamState.copy(state = StreamState.State.ERROR, appError = CastSecurityException)
}
private suspend fun stopStream(streamState: StreamState): StreamState {
XLog.d(getLog("stopStream"))
val state = stopProjection(streamState)
if (mjpegSettings.enablePinFlow.first() && mjpegSettings.autoChangePinFlow.first()) {
mjpegSettings.setPin(randomPin())
} else {
bitmapStateFlow.tryEmit(notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.START))
}
return state.copy(state = StreamState.State.SERVER_STARTED)
}
private suspend fun screenOff(streamState: StreamState): StreamState {
XLog.d(getLog("screenOff"))
return if (appSettings.stopOnSleepFlow.first() && streamState.isStreaming()) stopStream(streamState)
else streamState
}
private fun destroy(streamState: StreamState): StreamState {
XLog.d(getLog("destroy"))
return stopProjection(streamState).copy(state = StreamState.State.DESTROYED)
}
private suspend fun startStopFromWebPage(streamState: StreamState): StreamState {
XLog.d(getLog("startStopFromWebPage"))
if (streamState.isStreaming()) return stopStream(streamState)
if (streamState.state == StreamState.State.SERVER_STARTED)
return streamState.copy(state = StreamState.State.PERMISSION_PENDING)
return streamState
}
private suspend fun restartServer(streamState: StreamState, reason: RestartReason): StreamState {
XLog.d(getLog("restartServer"))
val state = stopProjection(streamState)
when (reason) {
is RestartReason.ConnectionChanged ->
effectSharedFlow.emit(AppStateMachine.Effect.ConnectionChanged)
is RestartReason.SettingsChanged ->
bitmapStateFlow.emit(notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.RELOAD_PAGE))
is RestartReason.NetworkSettingsChanged ->
bitmapStateFlow.emit(notificationBitmap.getNotificationBitmap(NotificationBitmap.Type.NEW_ADDRESS))
}
withTimeoutOrNull(300) { httpServer.stop().await() }
if (state.state == StreamState.State.ERROR)
sendEvent(AppStateMachine.Event.RecoverError)
else
sendEvent(InternalEvent.DiscoverAddress, 1000)
return state.copy(
state = StreamState.State.RESTART_PENDING,
netInterfaces = emptyList(),
httpServerAddressAttempt = 0
)
}
private fun componentError(streamState: StreamState, appError: AppError, report: Boolean): StreamState {
XLog.d(getLog("componentError"))
if (report) XLog.e(getLog("componentError"), appError)
return stopProjection(streamState).copy(state = StreamState.State.ERROR, appError = appError)
}
private fun recoverError(streamState: StreamState): StreamState {
XLog.d(getLog("recoverError"))
sendEvent(InternalEvent.DiscoverAddress)
return streamState.copy(state = StreamState.State.RESTART_PENDING, appError = null)
}
private suspend fun requestPublicState(streamState: StreamState): StreamState {
XLog.d(getLog("requestPublicState"))
effectSharedFlow.emit(streamState.toPublicState())
return streamState
}
private fun <T> Flow<T>.listenForChange(scope: CoroutineScope, action: suspend (T) -> Unit) =
distinctUntilChanged().drop(1).onEach { action(it) }.launchIn(scope)
} | mit |
jwren/intellij-community | python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.kt | 1 | 9333 | // 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.jetbrains.python.console
import com.intellij.application.options.RegistryManager
import com.intellij.codeInsight.hint.HintManager
import com.intellij.execution.console.LanguageConsoleImpl
import com.intellij.execution.console.LanguageConsoleView
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.console.actions.CommandQueueForPythonConsoleService
import com.jetbrains.python.console.pydev.ConsoleCommunication
import com.jetbrains.python.console.pydev.ConsoleCommunicationListener
import com.jetbrains.python.psi.PyElementGenerator
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyStatementList
import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher
import java.awt.Font
open class PydevConsoleExecuteActionHandler(private val myConsoleView: LanguageConsoleView,
processHandler: ProcessHandler,
final override val consoleCommunication: ConsoleCommunication) : PythonConsoleExecuteActionHandler(processHandler, false), ConsoleCommunicationListener {
private val project = myConsoleView.project
private val myEnterHandler = PyConsoleEnterHandler()
private var myIpythonInputPromptCount = 2
fun decreaseInputPromptCount(value : Int) {
myIpythonInputPromptCount -= value
}
override var isEnabled: Boolean = false
set(value) {
field = value
updateConsoleState()
}
init {
this.consoleCommunication.addCommunicationListener(this)
}
override fun processLine(line: String) {
executeMultiLine(line)
}
private fun executeMultiLine(text: String) {
val commandText = if (!text.endsWith("\n")) {
text + "\n"
}
else {
text
}
sendLineToConsole(ConsoleCommunication.ConsoleCodeFragment(commandText, checkSingleLine(text)))
}
override fun checkSingleLine(text: String): Boolean {
val languageLevel = PythonLanguageLevelPusher.getLanguageLevelForVirtualFile(project, myConsoleView.virtualFile)
val pyFile = PyElementGenerator.getInstance(project).createDummyFile(languageLevel, text) as PyFile
return PsiTreeUtil.findChildOfAnyType(pyFile, PyStatementList::class.java) == null && pyFile.statements.size < 2
}
private fun sendLineToConsole(code: ConsoleCommunication.ConsoleCodeFragment) {
val consoleComm = consoleCommunication
if (!consoleComm.isWaitingForInput) {
executingPrompt()
}
if (ipythonEnabled && !consoleComm.isWaitingForInput && !code.getText().isBlank()) {
++myIpythonInputPromptCount
}
if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) {
// add new command to CommandQueue service
service<CommandQueueForPythonConsoleService>().addNewCommand(this, code)
} else {
consoleComm.execInterpreter(code) {}
}
}
override fun updateConsoleState() {
if (!isEnabled) {
executingPrompt()
}
else if (consoleCommunication.isWaitingForInput) {
waitingForInputPrompt()
}
else if (canExecuteNow()) {
if (consoleCommunication.needsMore()) {
more()
}
else {
inPrompt()
}
}
else {
if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) {
inPrompt()
} else {
executingPrompt()
}
}
}
private fun inPrompt() {
if (ipythonEnabled) {
ipythonInPrompt()
}
else {
ordinaryPrompt()
}
}
private fun ordinaryPrompt() {
if (PyConsoleUtil.ORDINARY_PROMPT != myConsoleView.prompt) {
myConsoleView.prompt = PyConsoleUtil.ORDINARY_PROMPT
myConsoleView.indentPrompt = PyConsoleUtil.INDENT_PROMPT
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
private val ipythonEnabled: Boolean
get() = PyConsoleUtil.getOrCreateIPythonData(myConsoleView.virtualFile).isIPythonEnabled
private fun ipythonInPrompt() {
myConsoleView.setPromptAttributes(object : ConsoleViewContentType("", TextAttributes()) {
override fun getAttributes(): TextAttributes {
val attrs = EditorColorsManager.getInstance().globalScheme.getAttributes(USER_INPUT_KEY);
attrs.fontType = Font.PLAIN
return attrs
}
})
val prompt = "In [$myIpythonInputPromptCount]:"
val indentPrompt = PyConsoleUtil.IPYTHON_INDENT_PROMPT.padStart(prompt.length)
myConsoleView.prompt = prompt
myConsoleView.indentPrompt = indentPrompt
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
private fun executingPrompt() {
myConsoleView.prompt = PyConsoleUtil.EXECUTING_PROMPT
myConsoleView.indentPrompt = PyConsoleUtil.EXECUTING_PROMPT
}
private fun waitingForInputPrompt() {
if (PyConsoleUtil.INPUT_PROMPT != myConsoleView.prompt && PyConsoleUtil.HELP_PROMPT != myConsoleView.prompt) {
myConsoleView.prompt = PyConsoleUtil.INPUT_PROMPT
myConsoleView.indentPrompt = PyConsoleUtil.INPUT_PROMPT
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
private fun more() {
val prompt = if (ipythonEnabled) {
PyConsoleUtil.IPYTHON_INDENT_PROMPT
}
else {
PyConsoleUtil.INDENT_PROMPT
}
if (prompt != myConsoleView.prompt) {
myConsoleView.prompt = prompt
myConsoleView.indentPrompt = prompt
PyConsoleUtil.scrollDown(myConsoleView.currentEditor)
}
}
override fun commandExecuted(more: Boolean): Unit = updateConsoleState()
override fun inputRequested() {
isEnabled = true
}
override val cantExecuteMessage: String
get() {
if (!isEnabled) {
return consoleIsNotEnabledMessage
}
else if (!canExecuteNow()) {
return prevCommandRunningMessage
}
else {
return "Can't execute the command"
}
}
override fun runExecuteAction(console: LanguageConsoleView) {
if (isEnabled) {
if (RegistryManager.getInstance().`is`("python.console.CommandQueue")) {
doRunExecuteAction(console)
} else {
if (!canExecuteNow()) {
HintManager.getInstance().showErrorHint(console.consoleEditor, prevCommandRunningMessage)
}
else {
doRunExecuteAction(console)
}
}
}
else {
HintManager.getInstance().showErrorHint(console.consoleEditor, consoleIsNotEnabledMessage)
}
}
private fun doRunExecuteAction(console: LanguageConsoleView) {
val doc = myConsoleView.editorDocument
val endMarker = doc.createRangeMarker(doc.textLength, doc.textLength)
endMarker.isGreedyToLeft = false
endMarker.isGreedyToRight = true
val isComplete = myEnterHandler.handleEnterPressed(console.consoleEditor)
if (isComplete || consoleCommunication.isWaitingForInput) {
deleteString(doc, endMarker)
if (shouldCopyToHistory(console)) {
(console as? PythonConsoleView)?.let { pythonConsole ->
pythonConsole.flushDeferredText()
pythonConsole.storeExecutionCounterLineNumber(myIpythonInputPromptCount,
pythonConsole.historyViewer.document.lineCount +
console.consoleEditor.document.lineCount)
}
copyToHistoryAndExecute(console)
}
else {
processLine(myConsoleView.consoleEditor.document.text)
}
}
}
private fun copyToHistoryAndExecute(console: LanguageConsoleView) = super.runExecuteAction(console)
override fun canExecuteNow(): Boolean = !consoleCommunication.isExecuting || consoleCommunication.isWaitingForInput
protected open val consoleIsNotEnabledMessage: String
get() = notEnabledMessage
companion object {
val prevCommandRunningMessage: String
get() = "Previous command is still running. Please wait or press Ctrl+C in console to interrupt."
val notEnabledMessage: String
get() = "Console is not enabled."
private fun shouldCopyToHistory(console: LanguageConsoleView): Boolean {
return !PyConsoleUtil.isPagingPrompt(console.prompt)
}
fun deleteString(document: Document, endMarker : RangeMarker) {
if (endMarker.endOffset - endMarker.startOffset > 0) {
ApplicationManager.getApplication().runWriteAction {
CommandProcessor.getInstance().runUndoTransparentAction {
document.deleteString(endMarker.startOffset, endMarker.endOffset)
}
}
}
}
}
}
private var LanguageConsoleView.indentPrompt: String
get() {
return (this as? LanguageConsoleImpl)?.consolePromptDecorator?.indentPrompt ?: ""
}
set(value) {
(this as? LanguageConsoleImpl)?.consolePromptDecorator?.indentPrompt = value
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/SpecifyExplicitTypeFixFactories.kt | 1 | 2661 | /*
* Copyright 2010-2021 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.quickfix.fixes
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.KotlinApplicableQuickFix
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactory
import org.jetbrains.kotlin.idea.codeinsights.impl.base.CallableReturnTypeUpdaterUtils.TypeInfo
import org.jetbrains.kotlin.idea.codeinsights.impl.base.CallableReturnTypeUpdaterUtils.getTypeInfo
import org.jetbrains.kotlin.idea.codeinsights.impl.base.CallableReturnTypeUpdaterUtils.updateType
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
object SpecifyExplicitTypeFixFactories {
val ambiguousAnonymousTypeInferred =
diagnosticFixFactory(KtFirDiagnostic.AmbiguousAnonymousTypeInferred::class) { createQuickFix(it.psi) }
val noExplicitReturnTypeInApiMode =
diagnosticFixFactory(KtFirDiagnostic.NoExplicitReturnTypeInApiMode::class) { createQuickFix(it.psi) }
val noExplicitReturnTypeInApiModeWarning =
diagnosticFixFactory(KtFirDiagnostic.NoExplicitReturnTypeInApiModeWarning::class) { createQuickFix(it.psi) }
context(KtAnalysisSession)
private fun createQuickFix(declaration: KtDeclaration) =
if (declaration is KtCallableDeclaration) listOf(SpecifyExplicitTypeQuickFix(declaration, getTypeInfo(declaration)))
else emptyList()
private class SpecifyExplicitTypeQuickFix(
target: KtCallableDeclaration,
private val typeInfo: TypeInfo,
) : KotlinApplicableQuickFix<KtCallableDeclaration>(target) {
override fun getFamilyName(): String = KotlinBundle.message("specify.type.explicitly")
override fun getActionName(element: KtCallableDeclaration): String = when (element) {
is KtFunction -> KotlinBundle.message("specify.return.type.explicitly")
else -> KotlinBundle.message("specify.type.explicitly")
}
override fun apply(element: KtCallableDeclaration, project: Project, editor: Editor?, file: KtFile) =
updateType(element, typeInfo, project, editor)
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/FromLambda.kt | 13 | 85 | fun foo() {
val z = <selection>123</selection>
val x: (Int) -> Int = { 123}
} | apache-2.0 |
GunoH/intellij-community | uast/uast-common/src/org/jetbrains/uast/expressions/UExpressionList.kt | 13 | 1187 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* Represents a generic list of expressions.
*/
interface UExpressionList : UExpression {
/**
* Returns the list of expressions.
*/
val expressions: List<UExpression>
/**
* Returns the list kind.
*/
val kind: UastSpecialExpressionKind
override fun accept(visitor: UastVisitor) {
if (visitor.visitExpressionList(this)) return
uAnnotations.acceptList(visitor)
expressions.acceptList(visitor)
visitor.afterVisitExpressionList(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R =
visitor.visitExpressionList(this, data)
fun firstOrNull(): UExpression? = expressions.firstOrNull()
override fun asLogString(): String = log(kind.name)
override fun asRenderString(): String = kind.name + " " + expressions.joinToString(" : ") { it.asRenderString() }
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/suppress/forStatement/unavailable/objectLiteral.kt | 13 | 294 | // "class com.intellij.codeInspection.SuppressIntentionAction" "false"
// ACTION: Suppress 'UNNECESSARY_NOT_NULL_ASSERTION' for fun foo
// ACTION: Suppress 'UNNECESSARY_NOT_NULL_ASSERTION' for file objectLiteral.kt
fun foo() {
object : Base(""<caret>!!) {
}
}
open class Base(s: Any) | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/util/contrainingFileUtils.kt | 2 | 962 | /*
* 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.fir.low.level.api.util
import org.jetbrains.kotlin.fir.declarations.FirCallableDeclaration
import org.jetbrains.kotlin.fir.declarations.FirClassLikeDeclaration
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.declarations.FirFile
import org.jetbrains.kotlin.fir.resolve.firProvider
fun FirDeclaration.getContainingFile(): FirFile? {
val provider = session.firProvider
return when (this) {
is FirFile -> this
is FirCallableDeclaration<*> -> provider.getFirCallableContainerFile(symbol)
is FirClassLikeDeclaration<*> -> provider.getFirClassifierContainerFile(symbol)
else -> error("Unsupported declaration ${this::class.java}")
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/generate/secondaryConstructors/primaryExists.kt | 13 | 210 | // ACTION_CLASS: org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateSecondaryConstructorAction
// NOT_APPLICABLE
class Foo(x: Int) {<caret>
val x: Int
fun foo() {
}
fun bar() {
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hierarchicalMultiplatformImport/kT46417NativePlatformTestSourceSets/p2/src/iosX64Test/kotlin/P2IosX64Test.kt | 10 | 444 | import kotlin.test.Test
import kotlin.test.assertEquals
class P2IosX64Test {
@Test
fun testCommonMain() {
val x = P1CommonMain()
assertEquals(x.invoke(), P1CommonMain())
}
@Test
fun testNativeMain() {
val x = P1NativeMain()
assertEquals(x.invoke(), P1NativeMain())
}
@Test
fun testIosMain() {
val x = P1IosMain()
assertEquals(x.invoke(), P1IosMain())
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/collections/KotlinCollectionChainBuilder.kt | 6 | 3383 | // 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.debugger.sequence.psi.collections
import org.jetbrains.kotlin.idea.debugger.sequence.psi.KotlinPsiUtil
import org.jetbrains.kotlin.idea.debugger.sequence.psi.impl.KotlinChainBuilderBase
import org.jetbrains.kotlin.idea.debugger.sequence.psi.previousCall
import org.jetbrains.kotlin.idea.core.receiverType
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
class KotlinCollectionChainBuilder
: KotlinChainBuilderBase(CollectionChainTransformer()) {
private companion object {
// TODO: Avoid enumeration of all available types
val SUPPORTED_RECEIVERS = setOf(
"kotlin.collections.Iterable", "kotlin.CharSequence", "kotlin.Array",
"kotlin.BooleanArray", "kotlin.ByteArray", "kotlin.ShortArray", "kotlin.CharArray", "kotlin.IntArray",
"kotlin.LongArray", "kotlin.DoubleArray", "kotlin.FloatArray"
)
}
private fun isCollectionTransformationCall(expression: KtCallExpression): Boolean {
val receiverType = expression.receiverType() ?: return false
if (isTypeSuitable(receiverType)) return true
return receiverType.supertypes().any { isTypeSuitable(it) }
}
override val existenceChecker: ExistenceChecker = object : ExistenceChecker() {
override fun visitCallExpression(expression: KtCallExpression) {
if (isFound()) return
if (isCollectionTransformationCall(expression)) {
fireElementFound()
} else {
super.visitCallExpression(expression)
}
}
}
override fun createChainsBuilder(): ChainBuilder = object : ChainBuilder() {
private val previousCalls: MutableMap<KtCallExpression, KtCallExpression> = mutableMapOf()
private val visitedCalls: MutableSet<KtCallExpression> = mutableSetOf()
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
if (isCollectionTransformationCall(expression)) {
visitedCalls.add(expression)
val previous = expression.previousCall()
if (previous != null && isCollectionTransformationCall(previous)) {
previousCalls[expression] = previous
}
}
}
override fun chains(): List<List<KtCallExpression>> {
val notLastCalls: Set<KtCallExpression> = previousCalls.values.toSet()
return visitedCalls.filter { it !in notLastCalls }.map { buildPsiChain(it) }
}
private fun buildPsiChain(expression: KtCallExpression): List<KtCallExpression> {
val result = mutableListOf<KtCallExpression>()
var current: KtCallExpression? = expression
while (current != null) {
result.add(current)
current = previousCalls[current]
}
result.reverse()
return result
}
}
private fun isTypeSuitable(type: KotlinType): Boolean =
SUPPORTED_RECEIVERS.contains(KotlinPsiUtil.getTypeWithoutTypeParameters(type))
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/unnecessaryLateinit/lateinitWithMultipleInit.kt | 13 | 175 | // "Remove 'lateinit' modifier" "true"
class Foo {
<caret>lateinit var bar: String
var baz: Int
init {
baz = 1
}
init {
bar = ""
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/autoImports/importGetValueExtensionForDelegateWithLambda.before.Dependency.kt | 12 | 184 | package base
class MyDelegate<T>(init: () -> T) {
var value: T = init()
}
operator fun <T> MyDelegate<T>.getValue(thisObj: Any?, property: kotlin.reflect.KProperty<*>): T = value | apache-2.0 |
smmribeiro/intellij-community | platform/execution-impl/src/com/intellij/execution/wsl/target/WslTargetEnvironmentRequest.kt | 1 | 3017 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.wsl.target
import com.intellij.execution.Platform
import com.intellij.execution.process.LocalPtyOptions
import com.intellij.execution.target.*
import com.intellij.execution.target.TargetEnvironment.*
import com.intellij.execution.target.value.TargetValue
import com.intellij.execution.wsl.WSLCommandLineOptions
import com.intellij.ide.IdeBundle
class WslTargetEnvironmentRequest : BaseTargetEnvironmentRequest {
override val configuration: WslTargetEnvironmentConfiguration
var ptyOptions: LocalPtyOptions? = null
val wslOptions: WSLCommandLineOptions = WSLCommandLineOptions()
constructor(config: WslTargetEnvironmentConfiguration) {
this.configuration = config
}
private constructor(config: WslTargetEnvironmentConfiguration,
uploadVolumes: MutableSet<UploadRoot>,
downloadVolumes: MutableSet<DownloadRoot>,
targetPortBindings: MutableSet<TargetPortBinding>,
localPortBindings: MutableSet<LocalPortBinding>) : super(uploadVolumes, downloadVolumes, targetPortBindings,
localPortBindings) {
this.configuration = config
}
override fun duplicate(): WslTargetEnvironmentRequest {
return WslTargetEnvironmentRequest(configuration,
HashSet(uploadVolumes),
HashSet(downloadVolumes),
HashSet(targetPortBindings),
HashSet(localPortBindings))
}
override val targetPlatform: TargetPlatform
get() = TargetPlatform(Platform.UNIX)
override val defaultVolume: TargetEnvironmentRequest.Volume
get() {
throw UnsupportedOperationException("defaultVolume is not implemented")
}
override fun createUploadRoot(remoteRootPath: String?, temporary: Boolean): TargetEnvironmentRequest.Volume {
throw UnsupportedOperationException("createUploadRoot is not implemented")
}
override fun createDownloadRoot(remoteRootPath: String?): TargetEnvironmentRequest.DownloadableVolume {
throw UnsupportedOperationException("createDownloadRoot is not implemented")
}
override fun bindTargetPort(targetPort: Int): TargetValue<Int> {
return TargetValue.fixed(targetPort)
}
override fun bindLocalPort(localPort: Int): TargetValue<HostPort> {
return TargetValue.fixed(HostPort("localhost", localPort))
}
override fun prepareEnvironment(progressIndicator: TargetProgressIndicator): TargetEnvironment {
val distribution = configuration.distribution
if (distribution == null) {
error(IdeBundle.message("wsl.no.distribution.found.error"))
}
return WslTargetEnvironment(this, distribution).also { environmentPrepared(it, progressIndicator) }
}
}
| apache-2.0 |
appmattus/layercache | layercache/src/main/kotlin/com/appmattus/layercache/CacheException.kt | 1 | 1479 | /*
* Copyright 2021 Appmattus Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appmattus.layercache
/**
* A cache exception that can hold multiple causes. The first exception is available in cause and subsequent exceptions
* in suppressed
*/
public data class CacheException(override val message: String, val innerExceptions: List<Throwable>) : Exception(message) {
init {
require(innerExceptions.isNotEmpty()) { "You must provide at least one Exception" }
initCause(innerExceptions.first())
val hasAddSuppressed: Boolean = try {
Throwable::class.java.getDeclaredMethod("addSuppressed", Throwable::class.java) != null
} catch (ignore: NoSuchMethodException) {
false
} catch (ignore: SecurityException) {
false
}
if (hasAddSuppressed) {
innerExceptions.subList(1, innerExceptions.size).forEach { addSuppressed(it) }
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/testUtils.kt | 2 | 6681 | // 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.workspaceModel.storage
import com.google.common.collect.HashBiMap
import com.intellij.workspaceModel.storage.impl.*
import com.intellij.workspaceModel.storage.impl.containers.BidirectionalLongMultiMap
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import junit.framework.TestCase.*
import org.junit.Assert
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.function.BiPredicate
import kotlin.reflect.full.memberProperties
class TestEntityTypesResolver : EntityTypesResolver {
private val pluginPrefix = "PLUGIN___"
override fun getPluginId(clazz: Class<*>): String? = pluginPrefix + clazz.name
override fun resolveClass(name: String, pluginId: String?): Class<*> {
Assert.assertEquals(pluginPrefix + name, pluginId)
if (name.startsWith("[")) return Class.forName(name)
return javaClass.classLoader.loadClass(name)
}
}
object SerializationRoundTripChecker {
fun verifyPSerializationRoundTrip(storage: WorkspaceEntityStorage, virtualFileManager: VirtualFileUrlManager): ByteArray {
storage as WorkspaceEntityStorageImpl
storage.assertConsistency()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager)
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, storage)
val byteArray = stream.toByteArray()
val deserialized = (serializer.deserializeCache(ByteArrayInputStream(byteArray)) as WorkspaceEntityStorageBuilderImpl).toStorage()
deserialized.assertConsistency()
assertStorageEquals(storage, deserialized)
storage.assertConsistency()
return byteArray
}
private fun assertStorageEquals(expected: WorkspaceEntityStorageImpl, actual: WorkspaceEntityStorageImpl) {
// Assert entity data
assertEquals(expected.entitiesByType.size(), actual.entitiesByType.size())
for ((clazz, expectedEntityFamily) in expected.entitiesByType.entityFamilies.withIndex()) {
val actualEntityFamily = actual.entitiesByType.entityFamilies[clazz]
if (expectedEntityFamily == null || actualEntityFamily == null) {
assertNull(expectedEntityFamily)
assertNull(actualEntityFamily)
continue
}
val expectedEntities = expectedEntityFamily.entities
val actualEntities = actualEntityFamily.entities
assertOrderedEquals(expectedEntities, actualEntities) { a, b -> a == null && b == null || a != null && b != null && a.equalsIgnoringEntitySource(b) }
}
// Assert refs
assertMapsEqual(expected.refs.oneToOneContainer, actual.refs.oneToOneContainer)
assertMapsEqual(expected.refs.oneToManyContainer, actual.refs.oneToManyContainer)
assertMapsEqual(expected.refs.abstractOneToOneContainer, actual.refs.abstractOneToOneContainer)
assertMapsEqual(expected.refs.oneToAbstractManyContainer, actual.refs.oneToAbstractManyContainer)
assertMapsEqual(expected.indexes.virtualFileIndex.entityId2VirtualFileUrl, actual.indexes.virtualFileIndex.entityId2VirtualFileUrl)
assertMapsEqual(expected.indexes.virtualFileIndex.vfu2EntityId, actual.indexes.virtualFileIndex.vfu2EntityId)
// Just checking that all properties have been asserted
assertEquals(4, RefsTable::class.memberProperties.size)
// Assert indexes
assertBiLongMultiMap(expected.indexes.softLinks.index, actual.indexes.softLinks.index)
assertBiMap(expected.indexes.persistentIdIndex.index, actual.indexes.persistentIdIndex.index)
// External index should not be persisted
assertTrue(actual.indexes.externalMappings.isEmpty())
// Just checking that all properties have been asserted
assertEquals(5, StorageIndexes::class.memberProperties.size)
}
// Use UsefulTestCase.assertOrderedEquals in case it'd be used in this module
private fun <T> assertOrderedEquals(actual: Iterable<T?>, expected: Iterable<T?>, comparator: (T?, T?) -> Boolean) {
if (!equals(actual, expected, BiPredicate(comparator))) {
val expectedString: String = expected.toString()
val actualString: String = actual.toString()
Assert.assertEquals("", expectedString, actualString)
Assert.fail(
"Warning! 'toString' does not reflect the difference.\nExpected: $expectedString\nActual: $actualString")
}
}
private fun <T> equals(a1: Iterable<T?>, a2: Iterable<T?>, predicate: BiPredicate<in T?, in T?>): Boolean {
val it1 = a1.iterator()
val it2 = a2.iterator()
while (it1.hasNext() || it2.hasNext()) {
if (!it1.hasNext() || !it2.hasNext() || !predicate.test(it1.next(), it2.next())) {
return false
}
}
return true
}
private fun assertMapsEqual(expected: Map<*, *>, actual: Map<*, *>) {
val local = HashMap(expected)
for ((key, value) in actual) {
val expectedValue = local.remove(key)
if (expectedValue == null) {
Assert.fail(String.format("Expected to find '%s' -> '%s' mapping but it doesn't exist", key, value))
}
if (expectedValue != value) {
Assert.fail(
String.format("Expected to find '%s' value for the key '%s' but got '%s'", expectedValue, key, value))
}
}
if (local.isNotEmpty()) {
Assert.fail("No mappings found for the following keys: " + local.keys)
}
}
private fun <B> assertBiLongMultiMap(expected: BidirectionalLongMultiMap<B>, actual: BidirectionalLongMultiMap<B>) {
val local = expected.copy()
actual.keys.forEach { key ->
val value = actual.getValues(key)
val expectedValue = local.getValues(key)
local.removeKey(key)
assertOrderedEquals(expectedValue.sortedBy { it.toString() }, value.sortedBy { it.toString() }) { a, b -> a == b }
}
if (!local.isEmpty()) {
Assert.fail("No mappings found for the following keys: " + local.keys)
}
}
private fun <T> assertBiMap(expected: HashBiMap<EntityId, T>, actual: HashBiMap<EntityId, T>) {
val local = HashBiMap.create(expected)
for (key in actual.keys) {
val value = actual.getValue(key)
val expectedValue = local.remove(key)
if (expectedValue == null) {
Assert.fail(String.format("Expected to find '%s' -> '%s' mapping but it doesn't exist", key, value))
}
if (expectedValue != value) {
Assert.fail(
String.format("Expected to find '%s' value for the key '%s' but got '%s'", expectedValue, key, value))
}
}
if (local.isNotEmpty()) {
Assert.fail("No mappings found for the following keys: " + local.keys)
}
}
}
| apache-2.0 |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/AccordionTransformer.kt | 1 | 983 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.sinyuk.fanfou.ui
import android.view.View
class AccordionTransformer : ABaseTransformer() {
override fun onTransform(page: View, position: Float) {
page.pivotX = (if (position < 0) 0 else page.width).toFloat()
page.scaleX = if (position < 0) 1f + position else 1f - position
}
} | mit |
erdo/asaf-project | example-kt-07apollo3/src/main/java/foo/bar/example/foreapollo3/App.kt | 1 | 390 | package foo.bar.example.foreapollo3
import android.app.Application
/**
* Copyright © 2019 early.co. All rights reserved.
*/
@ExperimentalStdlibApi
class App : Application() {
override fun onCreate() {
super.onCreate()
inst = this
OG.setApplication(this)
OG.init()
}
companion object {
lateinit var inst: App private set
}
}
| apache-2.0 |
vivchar/RendererRecyclerViewAdapter | example/src/main/java/com/github/vivchar/example/MainApplication.kt | 1 | 280 | package com.github.vivchar.example
import android.app.Application
import com.github.vivchar.network.MainManager
/**
* Created by Vivchar Vitaly on 08.10.17.
*/
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
MainManager.init(this)
}
} | apache-2.0 |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/utils/localization/DurationLocalizable.kt | 1 | 1587 | package ch.rmy.android.framework.utils.localization
import android.content.Context
import ch.rmy.android.framework.R
import ch.rmy.android.framework.extensions.logException
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
data class DurationLocalizable(private val duration: Duration) : Localizable {
override fun localize(context: Context): CharSequence {
try {
if (duration < 1.seconds) {
return context.resources.getQuantityString(
R.plurals.milliseconds,
duration.inWholeMilliseconds.toInt(),
duration.inWholeMilliseconds.toInt(),
)
}
val minutes = duration.inWholeMinutes.toInt()
val seconds = (duration - minutes.minutes).inWholeSeconds.toInt()
return if (minutes > 0 && seconds > 0) {
context.getString(
R.string.pattern_minutes_seconds,
context.resources.getQuantityString(R.plurals.minutes, minutes, minutes),
context.resources.getQuantityString(R.plurals.seconds, seconds, seconds),
)
} else if (minutes > 0) {
context.resources.getQuantityString(R.plurals.minutes, minutes, minutes)
} else {
context.resources.getQuantityString(R.plurals.seconds, seconds, seconds)
}
} catch (e: Exception) {
logException(e)
return "-- error --"
}
}
}
| mit |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/RequestData.kt | 1 | 537 | package ch.rmy.android.http_shortcuts.http
import androidx.core.net.toUri
import ch.rmy.android.http_shortcuts.exceptions.InvalidUrlException
import ch.rmy.android.http_shortcuts.utils.Validation
data class RequestData(
val url: String,
val username: String,
val password: String,
val authToken: String,
val body: String,
val proxyHost: String?,
) {
val uri
get() = url.toUri()
init {
if (!Validation.isValidHttpUrl(uri)) {
throw InvalidUrlException(url)
}
}
}
| mit |
jrg94/PopLibrary | mobile/app/src/main/java/com/therenegadecoder/poplibrary/frontend/BookActivity.kt | 1 | 1403 | package com.therenegadecoder.poplibrary.frontend
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.therenegadecoder.poplibrary.R
class BookActivity : AppCompatActivity() {
private lateinit var titleView: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.book_add_form)
titleView = findViewById(R.id.book_title_input_form)
val submitButton = findViewById<Button>(R.id.book_submit_button)
submitButton.setOnClickListener {
val replyIntent = Intent()
if (TextUtils.isEmpty(titleView.text)) {
setResult(Activity.RESULT_CANCELED, replyIntent)
} else {
val title = titleView.text.toString()
replyIntent.putExtra(EXTRA_REPLY, title)
setResult(Activity.RESULT_OK, replyIntent)
}
finish()
}
}
fun loadMainActivity(view: View) {
val intent: Intent = Intent(this, MainActivity::class.java)
this.startActivity(intent)
}
companion object {
const val EXTRA_REPLY = "com.example.android.wordlistsql.REPLY"
}
} | gpl-3.0 |
mars-sim/mars-sim | mars-sim-core/src/main/kotlin/com/beust/nnk/NonLinearities.kt | 1 | 1127 | package com.beust.nnk
import java.io.Serializable
data class NonLinearity (
val activate: ((Float) -> Float),
val activateDerivative: ((Float) -> Float)): Serializable
enum class NonLinearities(val value: NonLinearity) {
TANH(NonLinearity(
{ x -> Math.tanh(x.toDouble()).toFloat() },
{ x -> (1.0f - x * x) }
)),
RELU(NonLinearity(
{ x -> if (x > 0) x else 0f },
{ x -> if (x > 0) 1f else 0f }
)),
LEAKYRELU(NonLinearity(
{ x -> if (x > 0) x else 0.01f * x },
{ x -> if (x > 0) 1f else 0.01f }
)),
SOFTPLUS(NonLinearity(
{ x -> Math.log10(1 + Math.exp(x.toDouble())).toFloat() },
{ x -> 1 / (1 + Math.exp(-x.toDouble())).toFloat() }
)),
SIGMOID(NonLinearity(
{ x -> 1 / (1 + Math.exp(-x.toDouble())).toFloat() },
{ x -> Math.exp(x.toDouble() / Math.pow(1 + Math.exp(-x.toDouble()), 2.0)).toFloat() }
)),
SOFTSIGN(NonLinearity(
{ x -> x / (1 + Math.abs(x)) },
{ x -> 1 / ((1+Math.abs(x))*(1+Math.abs(x)))}
)),
}
| gpl-3.0 |
seventhroot/elysium | bukkit/rpk-player-lib-bukkit/src/main/kotlin/com/rpkit/players/bukkit/event/profile/RPKBukkitProfileCreateEvent.kt | 1 | 1313 | /*
* Copyright 2019 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.players.bukkit.event.profile
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import com.rpkit.players.bukkit.profile.RPKProfile
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitProfileCreateEvent(
override val profile: RPKProfile
): RPKBukkitEvent(), RPKProfileCreateEvent, Cancellable {
companion object {
@JvmStatic val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | apache-2.0 |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/toolbar/main/CustomToolbar.kt | 1 | 1103 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.toolbar.main
import android.content.Context
import jp.hazuki.yuzubrowser.legacy.action.manager.ActionController
import jp.hazuki.yuzubrowser.legacy.action.manager.ActionIconManager
import jp.hazuki.yuzubrowser.ui.settings.AppPrefs
class CustomToolbar(context: Context, controller: ActionController, iconManager: ActionIconManager, request_callback: RequestCallback) : CustomToolbarBase(context, AppPrefs.toolbar_custom1, controller, iconManager, request_callback)
| apache-2.0 |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/db/PreRoomMigration.kt | 1 | 28001 | package com.orgzly.android.db
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.text.TextUtils
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQueryBuilder
import com.orgzly.android.App
import com.orgzly.android.db.mappers.OrgTimestampMapper
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.util.MiscUtils
import com.orgzly.org.datetime.OrgDateTime
import com.orgzly.org.parser.OrgNestedSetParser
import java.util.*
import java.util.regex.Pattern
object PreRoomMigration {
val MIGRATION_130_131 = object : Migration(130, 131) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE books ADD COLUMN title") // TITLE
}
}
val MIGRATION_131_132 = object : Migration(131, 132) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE books ADD COLUMN is_indented INTEGER DEFAULT 0") // IS_INDENTED
db.execSQL("ALTER TABLE books ADD COLUMN used_encoding TEXT") // USED_ENCODING
db.execSQL("ALTER TABLE books ADD COLUMN detected_encoding TEXT") // DETECTED_ENCODING
db.execSQL("ALTER TABLE books ADD COLUMN selected_encoding TEXT") // SELECTED_ENCODING
}
}
val MIGRATION_132_133 = object : Migration(132, 133) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_133_134 = object : Migration(133, 134) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE notes ADD COLUMN parent_id") // PARENT_ID
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_is_visible ON notes(is_visible)") // LFT
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_parent_position ON notes(parent_position)") // RGT
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_is_collapsed ON notes(is_collapsed)") // IS_FOLDED
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_is_under_collapsed ON notes(is_under_collapsed)") // FOLDED_UNDER_ID
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_parent_id ON notes(parent_id)") // PARENT_ID
db.execSQL("CREATE INDEX IF NOT EXISTS i_notes_has_children ON notes(has_children)") // DESCENDANTS_COUNT
convertNotebooksFromPositionToNestedSet(db)
}
}
private fun convertNotebooksFromPositionToNestedSet(db: SupportSQLiteDatabase) {
val query = SupportSQLiteQueryBuilder
.builder("books")
.columns(arrayOf("_id"))
.create()
eachForQuery(db, query) { cursor ->
val bookId = cursor.getLong(0)
convertNotebookFromPositionToNestedSet(db, bookId)
updateParentIds(db, bookId)
}
}
private fun convertNotebookFromPositionToNestedSet(db: SupportSQLiteDatabase, bookId: Long) {
/* Insert root note. */
val rootNoteValues = ContentValues()
rootNoteValues.put("level", 0)
rootNoteValues.put("book_id", bookId)
rootNoteValues.put("position", 0)
db.insert("notes", SQLiteDatabase.CONFLICT_ROLLBACK, rootNoteValues)
updateNotesPositionsFromLevel(db, bookId)
}
private fun updateNotesPositionsFromLevel(db: SupportSQLiteDatabase, bookId: Long) {
val stack = Stack<NotePosition>()
var prevLevel = -1
var sequence = OrgNestedSetParser.STARTING_VALUE - 1
val query = SupportSQLiteQueryBuilder
.builder("notes")
.selection("book_id = $bookId", null)
.orderBy("position")
.create()
eachForQuery(db, query) { cursor ->
val note = noteFromCursor(cursor)
if (prevLevel < note.level) {
/*
* This is a descendant of previous thisNode.
*/
/* Put the current thisNode on the stack. */
sequence += 1
note.lft = sequence
stack.push(note)
} else if (prevLevel == note.level) {
/*
* This is a sibling, which means that the last thisNode visited can be completed.
* Take it off the stack, update its rgt value and announce it.
*/
val nodeFromStack = stack.pop()
sequence += 1
nodeFromStack.rgt = sequence
calculateAndSetDescendantsCount(nodeFromStack)
updateNotePositionValues(db, nodeFromStack)
/* Put the current thisNode on the stack. */
sequence += 1
note.lft = sequence
stack.push(note)
} else {
/*
* Note has lower level then the previous one - we're out of the set.
* Start popping the stack, up to and including the thisNode with the same level.
*/
while (!stack.empty()) {
val nodeFromStack = stack.peek()
if (nodeFromStack.level >= note.level) {
stack.pop()
sequence += 1
nodeFromStack.rgt = sequence
calculateAndSetDescendantsCount(nodeFromStack)
updateNotePositionValues(db, nodeFromStack)
} else {
break
}
}
/* Put the current thisNode on the stack. */
sequence += 1
note.lft = sequence
stack.push(note)
}
prevLevel = note.level
}
/* Pop remaining nodes. */
while (!stack.empty()) {
val nodeFromStack = stack.pop()
sequence += 1
nodeFromStack.rgt = sequence
calculateAndSetDescendantsCount(nodeFromStack)
updateNotePositionValues(db, nodeFromStack)
}
}
private fun updateNotePositionValues(db: SupportSQLiteDatabase, note: NotePosition): Int {
val values = contentValuesFromNote(note)
return db.update("notes", SQLiteDatabase.CONFLICT_ROLLBACK, values, "_id = ${note.id}", null)
}
private fun calculateAndSetDescendantsCount(node: NotePosition) {
node.descendantsCount = (node.rgt - node.lft - 1).toInt() / (2 * 1)
}
private fun updateParentIds(db: SupportSQLiteDatabase, bookId: Long) {
val parentId = "(SELECT _id FROM notes AS n WHERE " +
"book_id = " + bookId + " AND " +
"n.is_visible < notes.is_visible AND " +
"notes.parent_position < n.parent_position ORDER BY n.is_visible DESC LIMIT 1)"
db.execSQL("UPDATE notes SET parent_id = " + parentId +
" WHERE book_id = " + bookId + " AND is_cut = 0 AND level > 0")
}
private fun noteFromCursor(cursor: Cursor): NotePosition {
val position = NotePosition()
position.id = cursor.getLong(cursor.getColumnIndex("_id"))
position.bookId = cursor.getLong(cursor.getColumnIndex("book_id"))
position.level = cursor.getInt(cursor.getColumnIndex("level"))
position.lft = cursor.getLong(cursor.getColumnIndex("is_visible"))
position.rgt = cursor.getLong(cursor.getColumnIndex("parent_position"))
position.descendantsCount = cursor.getInt(cursor.getColumnIndex("has_children"))
position.foldedUnderId = cursor.getLong(cursor.getColumnIndex("is_under_collapsed"))
position.parentId = cursor.getLong(cursor.getColumnIndex("parent_id"))
position.isFolded = cursor.getInt(cursor.getColumnIndex("is_collapsed")) != 0
return position
}
private fun contentValuesFromNote(position: NotePosition): ContentValues {
val values = ContentValues()
// values.put("_id", position.id)
values.put("book_id", position.bookId)
values.put("level", position.level)
values.put("is_visible", position.lft)
values.put("parent_position", position.rgt)
values.put("has_children", position.descendantsCount)
values.put("is_under_collapsed", position.foldedUnderId)
values.put("parent_id", position.parentId)
values.put("is_collapsed", if (position.isFolded) 1 else 0)
values.put("position", 0)
return values
}
private class NotePosition {
var id: Long = 0
var bookId: Long = 0
var lft: Long = 0
var rgt: Long = 0
var level: Int = 0
var descendantsCount: Int = 0
var foldedUnderId: Long = 0
var parentId: Long = 0
var isFolded: Boolean = false
}
val MIGRATION_134_135 = object : Migration(134, 135) {
override fun migrate(db: SupportSQLiteDatabase) {
fixOrgRanges(db)
}
}
/**
* 1.4-beta.1 misused insertWithOnConflict due to
* https://code.google.com/p/android/issues/detail?id=13045.
*
* org_ranges ended up with duplicates having -1 for
* start_timestamp_id and end_timestamp_id.
*
* Delete those, update notes tables and add a unique constraint to the org_ranges.
*/
private fun fixOrgRanges(db: SupportSQLiteDatabase) {
val notesFields = arrayOf("scheduled_range_id", "deadline_range_id", "closed_range_id", "clock_range_id")
val query = SupportSQLiteQueryBuilder
.builder("org_ranges")
.columns(arrayOf("_id", "string"))
.selection("start_timestamp_id = -1 OR end_timestamp_id = -1", null)
.create()
eachForQuery(db, query) { cursor ->
val id = cursor.getLong(0)
val string = cursor.getString(1)
val validTimestampId = "(start_timestamp_id IS NULL OR start_timestamp_id != -1) AND (end_timestamp_id IS NULL OR end_timestamp_id != -1)"
val validEntry = "(SELECT _id FROM org_ranges WHERE string = " + android.database.DatabaseUtils.sqlEscapeString(string) + " and " + validTimestampId + ")"
for (field in notesFields) {
db.execSQL("UPDATE notes SET $field = $validEntry WHERE $field = $id")
}
}
db.execSQL("DELETE FROM org_ranges WHERE start_timestamp_id = -1 OR end_timestamp_id = -1")
db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS i_org_ranges_string ON org_ranges(string)")
}
/* Properties moved from content. */
val MIGRATION_135_136 = object : Migration(135, 136) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("CREATE TABLE IF NOT EXISTS note_properties (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"note_id INTEGER," +
"position INTEGER," +
"property_id INTEGER," +
"UNIQUE(note_id, position, property_id))")
db.execSQL("CREATE TABLE IF NOT EXISTS property_names (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT UNIQUE)")
db.execSQL("CREATE TABLE IF NOT EXISTS property_values (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"value TEXT UNIQUE)")
db.execSQL("CREATE TABLE IF NOT EXISTS properties (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name_id INTEGER," +
"value_id INTEGER," +
"UNIQUE(name_id, value_id))")
movePropertiesFromBody(db)
}
}
private fun movePropertiesFromBody(db: SupportSQLiteDatabase) {
val query = SupportSQLiteQueryBuilder
.builder("notes")
.columns(arrayOf("_id", "content"))
.create()
val contentUpdates = hashMapOf<Long, ContentValues>()
eachForQuery(db, query) { cursor ->
val noteId = cursor.getLong(0)
val content = cursor.getString(1)
if (!TextUtils.isEmpty(content)) {
val newContent = StringBuilder()
val properties = getPropertiesFromContent(content, newContent)
if (properties.isNotEmpty()) {
var pos = 1
for (property in properties) {
val nameId = getOrInsert(
db, "property_names", arrayOf("name"), arrayOf(property[0]))
val valueId = getOrInsert(
db, "property_values", arrayOf("value"), arrayOf(property[1]))
val propertyId = getOrInsert(
db,
"properties",
arrayOf("name_id", "value_id"),
arrayOf(nameId.toString(), valueId.toString()))
getOrInsert(
db,
"note_properties",
arrayOf("note_id", "position", "property_id"),
arrayOf(noteId.toString(), pos++.toString(), propertyId.toString()))
}
// New content and its line count
contentUpdates[noteId] = ContentValues().apply {
put("content", newContent.toString())
put("content_line_count", MiscUtils.lineCount(newContent.toString()))
}
}
}
}
// This was causing issues (skipped notes) when done inside eachForQuery loop
for ((id, values) in contentUpdates) {
db.update("notes", SQLiteDatabase.CONFLICT_ROLLBACK, values, "_id = $id", null)
}
}
private fun getOrInsert(
db: SupportSQLiteDatabase,
table: String,
fieldNames: Array<String>,
fieldValues: Array<String>): Long {
val selection = fieldNames.joinToString(" AND ") { "$it = ?" }
val query = SupportSQLiteQueryBuilder
.builder(table)
.columns(arrayOf("_id"))
.selection(selection, fieldValues)
.create()
val id = db.query(query).use { cursor ->
if (cursor != null && cursor.moveToFirst()) {
cursor.getLong(0)
} else {
0
}
}
return if (id > 0) {
id
} else {
val values = ContentValues()
fieldNames.forEachIndexed { index, field ->
values.put(field, fieldValues[index])
}
db.insert(table, SQLiteDatabase.CONFLICT_ROLLBACK, values)
}
}
private fun getPropertiesFromContent(content: String, newContent: StringBuilder): List<Array<String>> {
val properties = ArrayList<Array<String>>()
val propertiesPattern = Pattern.compile("^\\s*:PROPERTIES:(.*?):END: *\n*(.*)", Pattern.DOTALL)
val propertyPattern = Pattern.compile("^:([^:\\s]+):\\s+(.*)\\s*$")
val m = propertiesPattern.matcher(content)
if (m.find()) {
val propertyLines = m.group(1)?.split("\n") ?: emptyList()
for (propertyLine in propertyLines) {
val pm = propertyPattern.matcher(propertyLine.trim())
if (pm.find()) {
val name = pm.group(1)
val value = pm.group(2)
// Add name-value pair
if (name != null && value != null) {
properties.add(arrayOf(name, value))
}
}
}
newContent.append(m.group(2))
}
return properties
}
val MIGRATION_136_137 = object : Migration(136, 137) {
override fun migrate(db: SupportSQLiteDatabase) {
encodeRookUris(db)
}
}
/**
* file:/dir/file name.org
* file:/dir/file%20name.org
*/
private fun encodeRookUris(db: SupportSQLiteDatabase) {
val query = SupportSQLiteQueryBuilder
.builder("rook_urls")
.columns(arrayOf("_id", "rook_url"))
.create()
eachForQuery(db, query) { cursor ->
val id = cursor.getLong(0)
val uri = cursor.getString(1)
val encodedUri = MiscUtils.encodeUri(uri)
if (uri != encodedUri) {
encodeRookUri(db, id, encodedUri)
}
}
}
/* Update unless same URL already exists. */
private fun encodeRookUri(db: SupportSQLiteDatabase, id: Long, encodedUri: String?) {
val query = SupportSQLiteQueryBuilder
.builder("rook_urls")
.columns(arrayOf("_id"))
.selection("rook_url = ?", arrayOf(encodedUri))
.create()
if (!db.query(query).moveToFirst()) {
val values = ContentValues()
values.put("rook_url", encodedUri)
db.update("rook_urls", SQLiteDatabase.CONFLICT_ROLLBACK, values, "_id = $id", null)
}
}
val MIGRATION_137_138 = object : Migration(137, 138) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("""
CREATE TABLE IF NOT EXISTS note_ancestors (
book_id INTEGER,
note_id INTEGER,
ancestor_note_id INTEGER)""".trimIndent())
db.execSQL("CREATE INDEX IF NOT EXISTS i_note_ancestors_" + "book_id" + " ON note_ancestors(" + "book_id" + ")")
db.execSQL("CREATE INDEX IF NOT EXISTS i_note_ancestors_" + "note_id" + " ON note_ancestors(" + "note_id" + ")")
db.execSQL("CREATE INDEX IF NOT EXISTS i_note_ancestors_" + "ancestor_note_id" + " ON note_ancestors(" + "ancestor_note_id" + ")")
db.execSQL("INSERT INTO note_ancestors (book_id, note_id, ancestor_note_id) " +
"SELECT n.book_id, n._id, a._id FROM notes n " +
"JOIN notes a on (n.book_id = a.book_id AND a.is_visible < n.is_visible AND n.parent_position < a.parent_position) " +
"WHERE a.level > 0")
}
}
val MIGRATION_138_139 = object : Migration(138, 139) {
override fun migrate(db: SupportSQLiteDatabase) {
migrateOrgTimestamps(db)
}
}
private fun migrateOrgTimestamps(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE org_timestamps RENAME TO org_timestamps_prev")
db.execSQL("""
CREATE TABLE IF NOT EXISTS org_timestamps (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
string TEXT NOT NULL UNIQUE,
is_active INTEGER NOT NULL,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
day INTEGER NOT NULL,
hour INTEGER,
minute INTEGER,
second INTEGER,
end_hour INTEGER,
end_minute INTEGER,
end_second INTEGER,
repeater_type INTEGER,
repeater_value INTEGER,
repeater_unit INTEGER,
habit_deadline_value INTEGER,
habit_deadline_unit INTEGER,
delay_type INTEGER,
delay_value INTEGER,
delay_unit INTEGER,
timestamp INTEGER,
end_timestamp INTEGER)""".trimIndent())
db.execSQL("CREATE INDEX IF NOT EXISTS i_org_timestamps_string ON org_timestamps(string)")
db.execSQL("CREATE INDEX IF NOT EXISTS i_org_timestamps_timestamp ON org_timestamps(timestamp)")
db.execSQL("CREATE INDEX IF NOT EXISTS i_org_timestamps_end_timestamp ON org_timestamps(end_timestamp)")
val query = SupportSQLiteQueryBuilder
.builder("org_timestamps_prev")
.columns(arrayOf("_id", "string"))
.create()
eachForQuery(db, query) { cursor ->
val id = cursor.getLong(0)
val string = cursor.getString(1)
val orgDateTime = OrgDateTime.parse(string)
val values = ContentValues()
values.put("_id", id)
toContentValues(values, orgDateTime)
db.insert("org_timestamps", SQLiteDatabase.CONFLICT_ROLLBACK, values)
}
db.execSQL("DROP TABLE org_timestamps_prev")
}
private fun toContentValues(values: ContentValues, orgDateTime: OrgDateTime) {
values.put("string", orgDateTime.toString())
values.put("is_active", if (orgDateTime.isActive) 1 else 0)
values.put("year", orgDateTime.calendar.get(Calendar.YEAR))
values.put("month", orgDateTime.calendar.get(Calendar.MONTH) + 1)
values.put("day", orgDateTime.calendar.get(Calendar.DAY_OF_MONTH))
if (orgDateTime.hasTime()) {
values.put("hour", orgDateTime.calendar.get(Calendar.HOUR_OF_DAY))
values.put("minute", orgDateTime.calendar.get(Calendar.MINUTE))
values.put("second", orgDateTime.calendar.get(Calendar.SECOND))
} else {
values.putNull("hour")
values.putNull("minute")
values.putNull("second")
}
values.put("timestamp", orgDateTime.calendar.timeInMillis)
if (orgDateTime.hasEndTime()) {
values.put("end_hour", orgDateTime.endCalendar.get(Calendar.HOUR_OF_DAY))
values.put("end_minute", orgDateTime.endCalendar.get(Calendar.MINUTE))
values.put("end_second", orgDateTime.endCalendar.get(Calendar.SECOND))
values.put("end_timestamp", orgDateTime.endCalendar.timeInMillis)
} else {
values.putNull("end_hour")
values.putNull("end_minute")
values.putNull("end_second")
values.putNull("end_timestamp")
}
if (orgDateTime.hasRepeater()) {
values.put("repeater_type", OrgTimestampMapper.repeaterType(orgDateTime.repeater.type))
values.put("repeater_value", orgDateTime.repeater.value)
values.put("repeater_unit", OrgTimestampMapper.timeUnit(orgDateTime.repeater.unit))
if (orgDateTime.repeater.hasHabitDeadline()) {
values.put("habit_deadline_value", orgDateTime.repeater.habitDeadline.value)
values.put("habit_deadline_unit", OrgTimestampMapper.timeUnit(orgDateTime.repeater.habitDeadline.unit))
} else {
values.putNull("habit_deadline_value")
values.putNull("habit_deadline_unit")
}
} else {
values.putNull("repeater_type")
values.putNull("repeater_value")
values.putNull("repeater_unit")
values.putNull("habit_deadline_value")
values.putNull("habit_deadline_unit")
}
if (orgDateTime.hasDelay()) {
values.put("delay_type", OrgTimestampMapper.delayType(orgDateTime.delay.type))
values.put("delay_value", orgDateTime.delay.value)
values.put("delay_unit", OrgTimestampMapper.timeUnit(orgDateTime.delay.unit))
} else {
values.putNull("delay_type")
values.putNull("delay_value")
values.putNull("delay_unit")
}
}
val MIGRATION_139_140 = object : Migration(139, 140) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_140_141 = object : Migration(140, 141) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_141_142 = object : Migration(141, 142) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_142_143 = object : Migration(142, 143) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_143_144 = object : Migration(143, 144) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_144_145 = object : Migration(144, 145) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_145_146 = object : Migration(145, 146) {
override fun migrate(db: SupportSQLiteDatabase) {
insertAgendaSavedSearch(db)
}
}
val MIGRATION_146_147 = object : Migration(146, 147) {
override fun migrate(db: SupportSQLiteDatabase) {
addAndSetCreatedAt(db, App.getAppContext())
}
}
val MIGRATION_147_148 = object : Migration(147, 148) {
override fun migrate(db: SupportSQLiteDatabase) {
// Views-only updates
}
}
val MIGRATION_148_149 = object : Migration(148, 149) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE book_links ADD COLUMN repo_id INTEGER")
db.execSQL("UPDATE book_links SET repo_id = (SELECT repo_id FROM rooks WHERE rooks._id = rook_id)")
}
}
private fun addAndSetCreatedAt(db: SupportSQLiteDatabase, context: Context) {
db.execSQL("ALTER TABLE notes ADD COLUMN created_at INTEGER DEFAULT 0")
if (!AppPreferences.createdAt(context)) {
return
}
val createdAtPropName = AppPreferences.createdAtProperty(context)
val query = SupportSQLiteQueryBuilder
.builder("note_properties"
+ " JOIN notes ON (notes._id = note_properties.note_id)"
+ " JOIN properties ON (properties._id = note_properties.property_id)"
+ " JOIN property_names ON (property_names._id = properties.name_id)"
+ " JOIN property_values ON (property_values._id = properties.value_id)")
.columns(arrayOf("notes._id AS note_id", "property_values.value AS value"))
.selection("note_id IS NOT NULL AND name IS NOT NULL AND value IS NOT NULL AND name = ?", arrayOf(createdAtPropName))
.distinct()
.create()
eachForQuery(db, query) { cursor ->
val noteId = cursor.getLong(0)
val propValue = cursor.getString(1)
val dateTime = OrgDateTime.doParse(propValue)
if (dateTime != null) {
val millis = dateTime.calendar.timeInMillis
val values = ContentValues()
values.put("created_at", millis)
db.update("notes", SQLiteDatabase.CONFLICT_ROLLBACK, values, "_id = $noteId", null)
}
}
}
private fun insertAgendaSavedSearch(db: SupportSQLiteDatabase) {
val values = ContentValues()
values.put("name", "Agenda")
values.put("search", ".it.done ad.7")
values.put("position", -2) // Display first
db.insert("searches", SQLiteDatabase.CONFLICT_ROLLBACK, values)
values.put("name", "Next 3 days")
values.put("search", ".it.done s.ge.today ad.3")
values.put("position", -1) // Display second
db.insert("searches", SQLiteDatabase.CONFLICT_ROLLBACK, values)
}
private fun eachForQuery(db: SupportSQLiteDatabase, query: SupportSQLiteQuery, action: (Cursor) -> Unit) {
db.query(query).use { cursor ->
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
action(cursor)
cursor.moveToNext()
}
}
}
}
} | gpl-3.0 |
kvnxiao/meirei | meirei-jda/src/main/kotlin/com/github/kvnxiao/discord/meirei/jda/MeireiJDA.kt | 1 | 9851 | /*
* Copyright (C) 2017-2018 Ze Hao Xiao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.kvnxiao.discord.meirei.jda
import com.github.kvnxiao.discord.meirei.Meirei
import com.github.kvnxiao.discord.meirei.command.CommandContext
import com.github.kvnxiao.discord.meirei.command.database.CommandRegistry
import com.github.kvnxiao.discord.meirei.command.database.CommandRegistryImpl
import com.github.kvnxiao.discord.meirei.jda.command.CommandJDA
import com.github.kvnxiao.discord.meirei.jda.command.CommandParserJDA
import com.github.kvnxiao.discord.meirei.jda.command.DefaultErrorHandler
import com.github.kvnxiao.discord.meirei.jda.command.ErrorHandler
import com.github.kvnxiao.discord.meirei.jda.permission.PermissionPropertiesJDA
import com.github.kvnxiao.discord.meirei.utility.SplitString.Companion.splitString
import net.dv8tion.jda.core.JDABuilder
import net.dv8tion.jda.core.entities.ChannelType
import net.dv8tion.jda.core.entities.Message
import net.dv8tion.jda.core.events.ReadyEvent
import net.dv8tion.jda.core.events.message.MessageReceivedEvent
import net.dv8tion.jda.core.hooks.EventListener
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Scheduler
import reactor.core.scheduler.Schedulers
import java.util.EnumSet
class MeireiJDA(jdaBuilder: JDABuilder, registry: CommandRegistry) : Meirei(commandParser = CommandParserJDA(), registry = registry) {
private var botOwnerId: Long = 0
private val errorHandler: ErrorHandler = DefaultErrorHandler()
private val scheduler: Scheduler = Schedulers.newParallel("MeireiExec-pool")
constructor(jdaBuilder: JDABuilder) : this(jdaBuilder, CommandRegistryImpl())
init {
// Register message-received event listener
Flux.create<MessageReceivedEvent> {
jdaBuilder.addEventListener(EventListener { event -> if (event is MessageReceivedEvent) it.next(event) })
}.publishOn(scheduler)
.doOnNext { Meirei.LOGGER.debug { "Received message ${it.message.contentRaw} from ${it.author.id} ${if (it.isFromType(ChannelType.PRIVATE)) "in direct message." else "in guild ${it.guild.id}"}" } }
.doOnError { Meirei.LOGGER.error(it) { "An error occurred in processing a MessageReceivedEvent!" } }
.subscribe(this::consumeMessage)
// Register ready-event listener
Mono.create<ReadyEvent> {
jdaBuilder.addEventListener(EventListener { event -> if (event is ReadyEvent) it.success(event) })
}.publishOn(scheduler)
.doOnSuccess(this::setBotOwner)
.doOnError { Meirei.LOGGER.error(it) { "An error occurred in processing the ReadyEvent!" } }
.subscribe()
}
private fun setBotOwner(event: ReadyEvent) {
event.jda.asBot().applicationInfo.queue {
botOwnerId = it.owner.idLong
Meirei.LOGGER.debug { "Bot owner ID found: ${java.lang.Long.toUnsignedString(botOwnerId)}" }
}
}
override fun registerEventListeners(client: Any) {
val dispatcher = (client as JDABuilder)
commandParser.commandEventListeners.values.forEach {
dispatcher.addEventListener(it)
}
}
private fun consumeMessage(event: MessageReceivedEvent) {
val message = event.message
val rawContent = message.contentRaw
val isPrivate = event.isFromType(ChannelType.PRIVATE)
// Split to check for bot mention
val (firstStr, secondStr) = splitString(rawContent)
firstStr.let {
// Check for bot mention
val hasBotMention = hasBotMention(it, message)
// Process for command alias and arguments
val content = if (hasBotMention) secondStr else rawContent
content?.let { process(it, event, isPrivate, hasBotMention) }
}
}
private fun process(input: String, event: MessageReceivedEvent, isDirectMsg: Boolean, hasBotMention: Boolean) {
val (alias, args) = splitString(input)
alias.let {
val command = registry.getCommandByAlias(it) as CommandJDA?
command?.let {
val properties = registry.getPropertiesById(it.id)
val permissions = registry.getPermissionsById(it.id)
if (properties != null && permissions != null) {
// Execute command
val context = CommandContext(alias, args, properties, permissions,
isDirectMsg, hasBotMention, if (it.registryAware) registry else null)
Meirei.LOGGER.debug { "Evaluating input for potential commands: $input" }
execute(it, context, event)
}
}
}
}
private fun execute(command: CommandJDA, context: CommandContext, event: MessageReceivedEvent): Boolean {
if (!context.properties.isDisabled) {
// Check sub-commands
val args = context.args
if (args != null && registry.hasSubCommands(command.id)) {
// Try getting a sub-command from the args
val (subAlias, subArgs) = splitString(args)
val subCommand = registry.getSubCommandByAlias(subAlias, command.id) as CommandJDA?
if (subCommand != null) {
val subProperties = registry.getPropertiesById(subCommand.id)
val subPermissions = registry.getPermissionsById(subCommand.id)
if (subProperties != null && subPermissions != null) {
// Execute sub-command
val subContext = CommandContext(subAlias, subArgs, subProperties, subPermissions,
context.isDirectMessage, context.hasBotMention, if (subCommand.registryAware) registry else null)
// Execute parent-command if the boolean value is true
if (context.properties.execWithSubCommands) command.execute(context, event)
return execute(subCommand, subContext, event)
}
}
}
return executeCommand(command, context, event)
}
return false
}
private fun executeCommand(command: CommandJDA, context: CommandContext, event: MessageReceivedEvent): Boolean {
// Validate mention-only command
if (!validateMentionOnly(context)) return false
// Validate permissions
if (!validatePermissions(context, event)) return false
// Validate rate-limits
if (!validateRateLimits(command, context, event)) return false
// Remove call msg if set to true
if (context.permissions.data.removeCallMsg) {
event.message.delete().reason("Command $command requires its message to be removed upon a successful call.").queue()
}
try {
Meirei.LOGGER.debug { "Executing command $command" }
command.execute(context, event)
} catch (e: Exception) {
Meirei.LOGGER.error(e) { "An error occurred in executing the command $command" }
}
return true
}
private fun hasBotMention(content: String, message: Message): Boolean {
val botMention = message.jda.selfUser.asMention
return content == botMention
}
// Validation
private fun validateRateLimits(command: CommandJDA, context: CommandContext, event: MessageReceivedEvent): Boolean {
val isNotRateLimited = if (event.isFromType(ChannelType.PRIVATE)) {
command.isNotUserLimited(event.author.idLong, context.permissions.data)
} else {
command.isNotRateLimited(event.guild.idLong, event.author.idLong, context.permissions.data)
}
if (!isNotRateLimited) {
errorHandler.onRateLimit(context, event)
return false
}
return true
}
private fun validateMentionOnly(context: CommandContext): Boolean {
return context.permissions.data.requireMention == context.hasBotMention
}
private fun validatePermissions(context: CommandContext, event: MessageReceivedEvent): Boolean {
val permissions = context.permissions as PermissionPropertiesJDA
if (context.isDirectMessage) {
if (!permissions.data.allowDmFromSender)
errorHandler.onDirectMessageInvalid(context, event)
else return permissions.data.allowDmFromSender
}
// Check if command requires to be guild owner
val isGuildOwner = event.guild.owner.user.idLong == event.author.idLong
// Check if command requires to be bot owner
val isBotOwner = botOwnerId == event.author.idLong
// Check for required user permissions in current channel
val requiredPerms = EnumSet.copyOf(permissions.level)
val userPerms = event.member.getPermissions(event.textChannel)
requiredPerms.removeAll(userPerms)
val hasUserPerms = requiredPerms.isEmpty() && (!permissions.data.reqGuildOwner || isGuildOwner) && (!permissions.data.reqBotOwner || isBotOwner)
return if (hasUserPerms) {
true
} else {
errorHandler.onMissingPermissions(context, event, requiredPerms)
false
}
}
}
| apache-2.0 |
addonovan/ftc-ext | ftc-ext/src/main/java/com/addonovan/ftcext/control/LinearOpMode.kt | 1 | 894 | package com.addonovan.ftcext.control
/**
* An OpMode that runs linearly. There is no `loop()` method
* as in a regular [OpMode], which is executed at a semiregular
* basis. A LinearOpMode will run exactly as it sounds, linearly.
* Once [runOpMode] returns, the OpMode is finished, the method
* will never be called again.
*
* This is most useful for Autonomous programs.
*
* @see AbstractOpMode
* @see OpMode
*
* @author addonovan
* @since 6/15/16
*/
abstract class LinearOpMode() : AbstractOpMode()
{
//
// Helper
//
/**
* Sleeps for the given amount of time.
*
* @param[milliseconds]
* The time (in milliseconds) to sleep for.
*/
@Suppress( "unused" ) fun sleep( milliseconds: Long ) = Thread.sleep( milliseconds );
//
// Abstract
//
/**
* Runs the OpMode.
*/
abstract fun runOpMode();
}
| mit |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/gradle/LibGDXGradlePropertiesBaseInspection.kt | 1 | 800 | package com.gmail.blueboxware.libgdxplugin.inspections.gradle
import com.intellij.lang.properties.PropertiesInspectionBase
/*
* Copyright 2017 Blue Box Ware
*
* 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.
*/
abstract class LibGDXGradlePropertiesBaseInspection : PropertiesInspectionBase()
| apache-2.0 |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/structureView/SkinTreeChangePreprocessor.kt | 1 | 915 | package com.gmail.blueboxware.libgdxplugin.filetypes.skin.structureView
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.LibGDXSkinLanguage
import com.gmail.blueboxware.libgdxplugin.utils.PsiTreeChangePreprocessorBase
/*
* Copyright 2017 Blue Box Ware
*
* 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.
*/
class SkinTreeChangePreprocessor : PsiTreeChangePreprocessorBase(LibGDXSkinLanguage.INSTANCE)
| apache-2.0 |
wiryls/HomeworkCollectionOfMYLS | 2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/data/UserList.kt | 1 | 4680 | package com.myls.odes.data
import android.os.Parcel
import android.os.Parcelable
import com.myls.odes.utility.Storage
import java.util.*
/**
* Created by myls on 12/8/17.
*
* UserList
*/
data class UserList(val list: MutableList<User> = mutableListOf())
: Parcelable
, Storage.Storable
{
// Parcel
constructor(parcel: Parcel) : this(
mutableListOf<User>().apply {
parcel.readList(this, User::class.java.classLoader)
})
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeList(list)
// [Kotlin parcelable and arrayList of parcelables]
// (https://stackoverflow.com/a/45459675)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<UserList> {
override fun createFromParcel(parcel: Parcel) = UserList(parcel)
override fun newArray(size: Int) = arrayOfNulls<UserList>(size)
}
// data class
data class User(
val info: Info,
var freq: Int = 1,
var date: Long = Calendar.getInstance().timeInMillis,
val dorm: Dorm = Dorm()): Parcelable
{
// Parcel
constructor(parcel: Parcel) : this(
parcel.readParcelable(User::class.java.classLoader),
parcel.readInt(),
parcel.readLong(),
parcel.readParcelable(Dorm::class.java.classLoader))
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeParcelable(info, flags)
parcel.writeInt(freq)
parcel.writeLong(date)
parcel.writeParcelable(dorm, flags)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<User> {
override fun createFromParcel(parcel: Parcel) = User(parcel)
override fun newArray(size: Int) = arrayOfNulls<User>(size)
}
}
data class Dorm(
var pick: String = "",
val fris: MutableList<Friend> = mutableListOf()) : Parcelable
{
// Parcel
constructor(parcel: Parcel) : this(
parcel.readString(),
mutableListOf<Friend>().apply {
parcel.readList(this, Friend::class.java.classLoader)
})
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(pick)
parcel.writeList(fris)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<Dorm> {
override fun createFromParcel(parcel: Parcel) = Dorm(parcel)
override fun newArray(size: Int) = arrayOfNulls<Dorm>(size)
}
// data class
data class Friend(
var stid: String,
var code: String) : Parcelable
{
// Parcel
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString())
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(stid)
parcel.writeString(code)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<Friend> {
override fun createFromParcel(parcel: Parcel) = Friend(parcel)
override fun newArray(size: Int) = arrayOfNulls<Friend>(size)
}
}
}
data class Info(
val stid: String,
var name: String = "",
var gender: String = "",
var grade: String = "",
var code: String = "",
var room: String = "",
var building: String = "",
var location: String = ""): Parcelable
{
// Parcel
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString())
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(stid)
parcel.writeString(name)
parcel.writeString(gender)
parcel.writeString(grade)
parcel.writeString(code)
parcel.writeString(room)
parcel.writeString(building)
parcel.writeString(location)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<Info> {
override fun createFromParcel(parcel: Parcel) = Info(parcel)
override fun newArray(size: Int) = arrayOfNulls<Info>(size)
}
}
}
| mit |
firebase/quickstart-android | analytics/app/src/main/java/com/google/firebase/quickstart/analytics/kotlin/ImageFragment.kt | 2 | 1500 | package com.google.firebase.quickstart.analytics.kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.google.firebase.quickstart.analytics.R
/**
* This fragment displays a featured, specified image.
*/
class ImageFragment : Fragment() {
private var resId: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
resId = it.getInt(ARG_PATTERN)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_main, null)
val imageView = view.findViewById<ImageView>(R.id.imageView)
imageView.setImageResource(resId)
return view
}
companion object {
private const val ARG_PATTERN = "pattern"
/**
* Create a [ImageFragment] displaying the given image.
*
* @param resId to display as the featured image
* @return a new instance of [ImageFragment]
*/
fun newInstance(resId: Int): ImageFragment {
val fragment = ImageFragment()
val args = Bundle()
args.putInt(ARG_PATTERN, resId)
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 |
gradle/gradle | build-logic/jvm/src/main/kotlin/gradlebuild/jvm/extension/UnitTestAndCompileExtension.kt | 3 | 1522 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gradlebuild.jvm.extension
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.kotlin.dsl.*
abstract class UnitTestAndCompileExtension(private val tasks: TaskContainer) {
/**
* Enforces **Java 6** compatibility.
*/
fun usedInWorkers() {
enforceJava6Compatibility()
}
/**
* Enforces **Java 6** compatibility.
*/
fun usedForStartup() {
enforceJava6Compatibility()
}
/**
* Enforces **Java 6** compatibility.
*/
fun usedInToolingApi() {
enforceJava6Compatibility()
}
/**
* Enforces **Java 6** compatibility.
*/
fun enforceJava6Compatibility() {
tasks.withType<JavaCompile>().configureEach {
options.release.set(null)
sourceCompatibility = "6"
targetCompatibility = "6"
}
}
}
| apache-2.0 |
facebook/fresco | vito/provider/src/main/java/com/facebook/fresco/vito/provider/impl/kotlin/KFrescoVitoProvider.kt | 2 | 2871 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.provider.impl.kotlin
import com.facebook.callercontext.CallerContextVerifier
import com.facebook.fresco.vito.core.FrescoController2
import com.facebook.fresco.vito.core.FrescoVitoConfig
import com.facebook.fresco.vito.core.FrescoVitoPrefetcher
import com.facebook.fresco.vito.core.ImagePipelineUtils
import com.facebook.fresco.vito.core.VitoImagePipeline
import com.facebook.fresco.vito.core.impl.DebugOverlayHandler
import com.facebook.fresco.vito.core.impl.FrescoVitoPrefetcherImpl
import com.facebook.fresco.vito.core.impl.KFrescoController
import com.facebook.fresco.vito.core.impl.VitoImagePipelineImpl
import com.facebook.fresco.vito.draweesupport.DrawableFactoryWrapper
import com.facebook.fresco.vito.options.ImageOptionsDrawableFactory
import com.facebook.fresco.vito.provider.FrescoVitoProvider
import com.facebook.fresco.vito.provider.impl.NoOpCallerContextVerifier
import com.facebook.imagepipeline.core.ImagePipeline
import com.facebook.imagepipeline.core.ImagePipelineFactory
import java.util.concurrent.Executor
class KFrescoVitoProvider(
private val vitoConfig: FrescoVitoConfig,
private val frescoImagePipeline: ImagePipeline,
private val imagePipelineUtils: ImagePipelineUtils,
private val uiThreadExecutor: Executor,
private val lightweightBackgroundExecutor: Executor,
private val callerContextVerifier: CallerContextVerifier = NoOpCallerContextVerifier,
private val debugOverlayHandler: DebugOverlayHandler? = null
) : FrescoVitoProvider.Implementation {
private val _imagePipeline: VitoImagePipeline by lazy {
VitoImagePipelineImpl(frescoImagePipeline, imagePipelineUtils)
}
private val _controller: FrescoController2 by lazy {
KFrescoController(
config = vitoConfig,
vitoImagePipeline = _imagePipeline,
uiThreadExecutor = uiThreadExecutor,
lightweightBackgroundThreadExecutor = lightweightBackgroundExecutor,
drawableFactory = getFactory())
.also { it.debugOverlayHandler = debugOverlayHandler }
}
private val _prefetcher: FrescoVitoPrefetcher by lazy {
FrescoVitoPrefetcherImpl(frescoImagePipeline, imagePipelineUtils, callerContextVerifier)
}
override fun getController(): FrescoController2 = _controller
override fun getPrefetcher(): FrescoVitoPrefetcher = _prefetcher
override fun getImagePipeline(): VitoImagePipeline = _imagePipeline
override fun getConfig(): FrescoVitoConfig = vitoConfig
private fun getFactory(): ImageOptionsDrawableFactory? {
return ImagePipelineFactory.getInstance().getAnimatedDrawableFactory(null)?.let {
DrawableFactoryWrapper(it)
}
}
}
| mit |
jayrave/falkon | falkon-mapper-basic/src/test/kotlin/com/jayrave/falkon/mapper/ReadOnlyColumnImplTest.kt | 1 | 2286 | package com.jayrave.falkon.mapper
import com.jayrave.falkon.engine.Type
import com.jayrave.falkon.mapper.testLib.StaticDataProducer
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.*
class ReadOnlyColumnImplTest {
@Test
fun `compute property from non null type`() {
val column: ReadOnlyColumn<UUID> = buildReadOnlyColumnImplForTest(nonNullUuidConverter())
val inputString = UUID.randomUUID().toString()
val dataProducer = StaticDataProducer.createForString(inputString)
assertThat(column.computePropertyFrom(dataProducer)).isEqualTo(UUID.fromString(inputString))
}
@Test
fun `compute property from nullable type with non null value`() {
val column: ReadOnlyColumn<UUID?> = buildReadOnlyColumnImplForTest(nullableUuidConverter())
val inputString = UUID.randomUUID().toString()
val dataProducer = StaticDataProducer.createForString(inputString)
assertThat(column.computePropertyFrom(dataProducer)).isEqualTo(UUID.fromString(inputString))
}
@Test
fun `compute property from nullable type with null value`() {
val column: ReadOnlyColumn<UUID?> = buildReadOnlyColumnImplForTest(nullableUuidConverter())
val dataProducer = StaticDataProducer.createForString(null)
assertThat(column.computePropertyFrom(dataProducer)).isNull()
}
companion object {
private fun nonNullUuidConverter() = NullableToNonNullConverter(nullableUuidConverter())
private fun nullableUuidConverter() = NullableUuidConverter()
private fun <C> buildReadOnlyColumnImplForTest(converter: Converter<C>): ReadOnlyColumn<C> {
return ReadOnlyColumnImpl("test", converter)
}
private class NullableUuidConverter : Converter<UUID?> {
override val dbType: Type = Type.STRING
override fun from(dataProducer: DataProducer): UUID? {
return when (dataProducer.isNull()) {
true -> null
else -> UUID.fromString(dataProducer.getString())
}
}
override fun to(value: UUID?, dataConsumer: DataConsumer) {
dataConsumer.put(value?.toString())
}
}
}
} | apache-2.0 |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/search/discover/AddIndicator.kt | 1 | 1964 | package com.battlelancer.seriesguide.shows.search.discover
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.battlelancer.seriesguide.databinding.LayoutAddIndicatorBinding
/**
* A three state visual indicator with states add, adding and added from [SearchResult].
*/
class AddIndicator(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {
private val binding: LayoutAddIndicatorBinding
init {
binding = LayoutAddIndicatorBinding.inflate(LayoutInflater.from(context), this)
}
override fun onFinishInflate() {
super.onFinishInflate()
binding.imageViewAddIndicatorAdded.visibility = GONE
binding.progressBarAddIndicator.visibility = GONE
}
fun setContentDescriptionAdded(contentDescription: CharSequence?) {
binding.imageViewAddIndicatorAdded.contentDescription = contentDescription
}
fun setOnAddClickListener(onClickListener: OnClickListener?) {
binding.imageViewAddIndicator.setOnClickListener(onClickListener)
}
fun setState(state: Int) {
when (state) {
SearchResult.STATE_ADD -> {
binding.imageViewAddIndicator.visibility = VISIBLE
binding.progressBarAddIndicator.visibility = GONE
binding.imageViewAddIndicatorAdded.visibility = GONE
}
SearchResult.STATE_ADDING -> {
binding.imageViewAddIndicator.visibility = GONE
binding.progressBarAddIndicator.visibility = VISIBLE
binding.imageViewAddIndicatorAdded.visibility = GONE
}
SearchResult.STATE_ADDED -> {
binding.imageViewAddIndicator.visibility = GONE
binding.progressBarAddIndicator.visibility = GONE
binding.imageViewAddIndicatorAdded.visibility = VISIBLE
}
}
}
} | apache-2.0 |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/modules/ApplicationContext.kt | 1 | 164 | package com.battlelancer.seriesguide.modules
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationContext | apache-2.0 |
dkhmelenko/Varis-Android | app-v3/src/main/java/com/khmelenko/lab/varis/dagger/component/BaseComponent.kt | 2 | 1762 | package com.khmelenko.lab.varis.dagger.component
import com.khmelenko.lab.varis.TravisApp
import com.khmelenko.lab.varis.auth.AuthActivityModule
import com.khmelenko.lab.varis.builddetails.BuildDetailsActivityModule
import com.khmelenko.lab.varis.dagger.module.ApplicationModule
import com.khmelenko.lab.varis.dagger.module.NetworkModule
import com.khmelenko.lab.varis.dagger.module.StorageModule
import com.khmelenko.lab.varis.log.LogsParser
import com.khmelenko.lab.varis.network.retrofit.github.GitHubRestClient
import com.khmelenko.lab.varis.network.retrofit.raw.RawClient
import com.khmelenko.lab.varis.network.retrofit.travis.TravisRestClient
import com.khmelenko.lab.varis.repodetails.RepoDetailsActivityModule
import com.khmelenko.lab.varis.repositories.MainActivityModule
import com.khmelenko.lab.varis.repositories.search.SearchResultsActivityModule
import com.khmelenko.lab.varis.storage.AppSettings
import com.khmelenko.lab.varis.storage.CacheStorage
import dagger.Component
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
/**
* Base component
*
* @author Dmytro Khmelenko ([email protected])
*/
@Singleton
@Component(modules = [(NetworkModule::class), (StorageModule::class), (ApplicationModule::class),
(AuthActivityModule::class), (BuildDetailsActivityModule::class), (MainActivityModule::class),
(RepoDetailsActivityModule::class), (SearchResultsActivityModule::class), (AndroidSupportInjectionModule::class)])
interface BaseComponent {
fun inject(app: TravisApp)
fun restClient(): TravisRestClient
fun rawClient(): RawClient
fun gitHubClient(): GitHubRestClient
fun cache(): CacheStorage
fun appSettings(): AppSettings
fun logsParser(): LogsParser
}
| apache-2.0 |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/shows/calendar/UpcomingFragment.kt | 1 | 1003 | package com.battlelancer.seriesguide.shows.calendar
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.battlelancer.seriesguide.databinding.FragmentCalendarUpcomingBinding
import com.battlelancer.seriesguide.shows.ShowsActivityImpl
/**
* A [CalendarFragment2] that displays to be released episodes.
*/
class UpcomingFragment : CalendarFragment2() {
override val tabPosition: Int = ShowsActivityImpl.Tab.UPCOMING.index
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = FragmentCalendarUpcomingBinding.inflate(layoutInflater, container, false)
recyclerView = binding.recyclerViewCalendarUpcoming
textViewEmpty = binding.textViewCalendarUpcomingEmpty
return binding.root
}
override suspend fun updateCalendarQuery() {
viewModel.updateCalendarQuery(true)
}
} | apache-2.0 |
andretietz/retroauth | android-accountmanager/src/main/java/com/andretietz/retroauth/AndroidAccountManagerCredentialStorage.kt | 1 | 3569 | /*
* Copyright (c) 2016 Andre Tietz
*
* 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.andretietz.retroauth
import android.accounts.Account
import android.accounts.AccountManager
import android.app.Application
import android.os.Looper
import android.util.Base64
import android.util.Base64.DEFAULT
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
/**
* This is the implementation of a [CredentialStorage] in Android using the Android [AccountManager]
*/
class AndroidAccountManagerCredentialStorage constructor(
private val application: Application
) : CredentialStorage<Account> {
private val accountManager by lazy { AccountManager.get(application) }
private val executor = Executors.newSingleThreadExecutor()
companion object {
private fun createDataKey(type: String, key: String) = "${type}_$key"
}
override fun getCredentials(
owner: Account,
credentialType: String
): Credentials? {
val future = accountManager.getAuthToken(
owner,
credentialType,
null,
ActivityManager[application].activity,
null,
null
)
var token: String? = if (Looper.myLooper() == Looper.getMainLooper()) {
executor.submit(Callable<String?> {
future.result.getString(AccountManager.KEY_AUTHTOKEN)
}).get(100, TimeUnit.MILLISECONDS)
} else future.result.getString(AccountManager.KEY_AUTHTOKEN)
if (token == null) token = accountManager.peekAuthToken(owner, credentialType)
if (token == null) {
return null
}
val dataKeys = accountManager.getUserData(owner, "keys_${owner.type}_$credentialType")
?.let { Base64.decode(it, DEFAULT).toString() }
?.split(",")
return Credentials(
token,
dataKeys
?.associate {
it to accountManager.getUserData(owner, createDataKey(credentialType, it))
}
)
}
override fun removeCredentials(owner: Account, credentialType: String) {
getCredentials(owner, credentialType)?.let { credential ->
accountManager.invalidateAuthToken(owner.type, credential.token)
val dataKeys = accountManager.getUserData(owner, "keys_${owner.type}_$credentialType")
?.let { Base64.decode(it, DEFAULT).toString() }
?.split(",")
dataKeys?.forEach {
accountManager.setUserData(
owner,
createDataKey(credentialType, it),
null
)
}
}
}
override fun storeCredentials(owner: Account, credentialType: String, credentials: Credentials) {
accountManager.setAuthToken(owner, credentialType, credentials.token)
val data = credentials.data
if (data != null) {
val dataKeys = data.keys
.map { Base64.encodeToString(it.toByteArray(), DEFAULT) }
.joinToString { it }
accountManager.setUserData(owner, "keys_${owner.type}_$credentialType", dataKeys)
data.forEach { (key, value) ->
accountManager.setUserData(owner, createDataKey(credentialType, key), value)
}
}
}
}
| apache-2.0 |
cashapp/turbine | src/commonTest/kotlin/app/cash/turbine/FlowTest.kt | 1 | 18140 | /*
* 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 app.cash.turbine
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineStart.UNDISPATCHED
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.Dispatchers.Unconfined
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.RENDEZVOUS
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
class FlowTest {
@Test fun exceptionsPropagate() = runTest {
val expected = CustomThrowable("hello")
val actual = assertFailsWith<CustomThrowable> {
neverFlow().test {
throw expected
}
}
assertSame(expected, actual)
}
@Test fun cancelStopsFlowCollection() = runTest {
var collecting = false
neverFlow()
.onStart { collecting = true }
.onCompletion { collecting = false }
.test {
assertTrue(collecting)
cancel()
assertFalse(collecting)
}
}
@Test fun cancelAwaitsFlowCompletion() = runTest {
var collecting = false
neverFlow()
.onStart { collecting = true }
.onCompletion {
withContext(NonCancellable) {
yield()
collecting = false
}
}
.test {
assertTrue(collecting)
cancel()
assertFalse(collecting)
}
}
@Test fun endOfBlockStopsFlowCollection() = runTest {
var collecting = false
neverFlow()
.onStart { collecting = true }
.onCompletion { collecting = false }
.test {
assertTrue(collecting)
}
assertFalse(collecting)
}
@Test fun exceptionStopsFlowCollection() = runTest {
var collecting = false
assertFailsWith<RuntimeException> {
neverFlow()
.onStart { collecting = true }
.onCompletion { collecting = false }
.test {
assertTrue(collecting)
throw RuntimeException()
}
}
assertFalse(collecting)
}
@Test fun ignoreRemainingEventsStopsFlowCollection() = runTest {
var collecting = false
neverFlow()
.onStart { collecting = true }
.onCompletion { collecting = false }
.test {
assertTrue(collecting)
cancelAndIgnoreRemainingEvents()
}
assertFalse(collecting)
}
@Test fun expectNoEvents() = runTest {
neverFlow().test {
expectNoEvents()
cancel()
}
}
@Test fun unconsumedItemThrows() = runTest {
val actual = assertFailsWith<AssertionError> {
flow {
emit("item!")
emitAll(neverFlow()) // Avoid emitting complete
}.test { }
}
assertEquals(
"""
|Unconsumed events found:
| - Item(item!)
""".trimMargin(),
actual.message
)
}
@Test fun unconsumedCompleteThrows() = runTest {
val actual = assertFailsWith<AssertionError> {
emptyFlow<Nothing>().test { }
}
assertEquals(
"""
|Unconsumed events found:
| - Complete
""".trimMargin(),
actual.message
)
}
@Test fun unconsumedErrorThrows() = runTest {
val expected = RuntimeException()
val actual = assertFailsWith<AssertionError> {
flow<Nothing> { throw expected }.test { }
}
assertEquals(
"""
|Unconsumed events found:
| - Error(RuntimeException)
""".trimMargin(),
actual.message
)
assertSame(expected, actual.cause)
}
@Test fun unconsumedItemThrowsWithCancel() = runTest {
val actual = assertFailsWith<AssertionError> {
flow {
emit("one")
emit("two")
emitAll(neverFlow()) // Avoid emitting complete
}.test {
// Expect one item to ensure we start collecting and receive both items.
assertEquals("one", awaitItem())
cancel()
}
}
assertEquals(
"""
|Unconsumed events found:
| - Item(two)
""".trimMargin(),
actual.message
)
}
@Test fun unconsumedCompleteThrowsWithCancel() = runTest {
val actual = assertFailsWith<AssertionError> {
flowOf("one").test {
// Expect one item to ensure we start collecting and receive complete.
assertEquals("one", awaitItem())
cancel()
}
}
assertEquals(
"""
|Unconsumed events found:
| - Complete
""".trimMargin(),
actual.message
)
}
@Test fun unconsumedErrorThrowsWithCancel() = runTest {
val expected = RuntimeException()
val actual = assertFailsWith<AssertionError> {
flow {
emit("one")
throw expected
}.test {
// Expect one item to ensure we start collecting and receive the exception.
assertEquals("one", awaitItem())
cancel()
}
}
assertEquals(
"""
|Unconsumed events found:
| - Error(RuntimeException)
""".trimMargin(),
actual.message
)
assertSame(expected, actual.cause)
}
@Test fun unconsumedItemReturnedWithConsumingCancel() = runTest {
flow {
emit("one")
emit("two")
emitAll(neverFlow()) // Avoid emitting complete
}.test {
// Expect one item to ensure we start collecting and receive both items.
assertEquals("one", awaitItem())
val remaining = cancelAndConsumeRemainingEvents()
assertEquals(listOf(Event.Item("two")), remaining)
}
}
@Test fun unconsumedCompleteReturnedWithConsumingCancel() = runTest {
flowOf("one").test {
// Expect one item to ensure we start collecting and receive complete.
assertEquals("one", awaitItem())
val remaining = cancelAndConsumeRemainingEvents()
assertEquals(listOf(Event.Complete), remaining)
}
}
@Test fun unconsumedErrorReturnedWithConsumingCancel() = runTest {
val expected = RuntimeException()
flow {
emit("one")
throw expected
}.test {
// Expect one item to ensure we start collecting and receive the exception.
assertEquals("one", awaitItem())
val remaining = cancelAndConsumeRemainingEvents()
assertEquals(listOf(Event.Error(expected)), remaining)
}
}
@Test fun unconsumedItemCanBeIgnored() = runTest {
flowOf("item!").test {
cancelAndIgnoreRemainingEvents()
}
}
@Test fun unconsumedCompleteCanBeIgnored() = runTest {
emptyFlow<Nothing>().test {
cancelAndIgnoreRemainingEvents()
}
}
@Test fun unconsumedErrorCanBeIgnored() = runTest {
flow<Nothing> { throw RuntimeException() }.test {
cancelAndIgnoreRemainingEvents()
}
}
@Test fun expectItem() = runTest {
val item = Any()
flowOf(item).test {
assertSame(item, awaitItem())
cancelAndIgnoreRemainingEvents()
}
}
@Test fun expectItemButWasCloseThrows() = runTest {
val actual = assertFailsWith<AssertionError> {
emptyFlow<Unit>().test {
awaitItem()
}
}
assertEquals("Expected item but found Complete", actual.message)
}
@Test fun expectItemButWasErrorThrows() = runTest {
val error = CustomThrowable("hi")
val actual = assertFailsWith<AssertionError> {
flow<Unit> { throw error }.test {
awaitItem()
}
}
assertEquals("Expected item but found Error(CustomThrowable)", actual.message)
assertSame(error, actual.cause)
}
@Test fun expectComplete() = runTest {
emptyFlow<Nothing>().test {
awaitComplete()
}
}
@Test fun expectCompleteButWasItemThrows() = runTest {
val actual = assertFailsWith<AssertionError> {
flowOf("item!").test {
awaitComplete()
}
}
assertEquals("Expected complete but found Item(item!)", actual.message)
}
@Test fun expectCompleteButWasErrorThrows() = runTest {
val error = CustomThrowable("hi")
val actual = assertFailsWith<AssertionError> {
flow<Nothing> { throw error }.test {
awaitComplete()
}
}
assertEquals("Expected complete but found Error(CustomThrowable)", actual.message)
assertSame(error, actual.cause)
}
@Test fun expectError() = runTest {
val error = CustomThrowable("hi")
flow<Nothing> { throw error }.test {
assertSame(error, awaitError())
}
}
@Test fun terminalErrorAfterExpectMostRecentItemThrows() = runTest {
val error = RuntimeException("hi")
val throwBarrier = Job()
val message = assertFailsWith<AssertionError> {
flow {
emit("item!")
throwBarrier.join()
throw error
}.test {
expectMostRecentItem()
throwBarrier.complete()
}
}.message
assertEquals("""
|Unconsumed events found:
| - Error(RuntimeException)
""".trimMargin(), message)
}
@Test fun expectErrorButWasItemThrows() = runTest {
val actual = assertFailsWith<AssertionError> {
flowOf("item!").test {
awaitError()
}
}
assertEquals("Expected error but found Item(item!)", actual.message)
}
@Test fun expectErrorButWasCompleteThrows() = runTest {
val actual = assertFailsWith<AssertionError> {
emptyFlow<Nothing>().test {
awaitError()
}
}
assertEquals("Expected error but found Complete", actual.message)
}
@Test fun expectItemEvent() = runTest {
val item = Any()
flowOf(item).test {
val event = awaitEvent()
assertEquals(Event.Item(item), event)
cancelAndIgnoreRemainingEvents()
}
}
@Test fun expectCompleteEvent() = runTest {
emptyFlow<Nothing>().test {
val event = awaitEvent()
assertEquals(Event.Complete, event)
cancelAndIgnoreRemainingEvents()
}
}
@Test fun expectErrorEvent() = runTest {
val exception = CustomThrowable("hi")
flow<Nothing> { throw exception }.test {
val event = awaitEvent()
assertEquals(Event.Error(exception), event)
cancelAndIgnoreRemainingEvents()
}
}
@Test fun expectWaitsForEvents() = runTest {
val flow = MutableSharedFlow<String>()
val position = Channel<Int>(RENDEZVOUS)
// Start undispatched so we suspend inside the test{} block.
launch(start = UNDISPATCHED, context = Unconfined) {
flow.test {
position.send(1)
assertEquals("one", awaitItem())
position.send(2)
assertEquals("two", awaitItem())
position.send(3)
cancel()
}
}
assertEquals(1, position.receive())
flow.emit("one")
assertEquals(2, position.receive())
flow.emit("two")
assertEquals(3, position.receive())
}
@Test fun exceptionsPropagateWhenExpectMostRecentItem() = runTest {
val expected = CustomThrowable("hello")
val actual = assertFailsWith<CustomThrowable> {
flow {
emit(1)
emit(2)
emit(3)
throw expected
}.test {
expectMostRecentItem()
}
}
assertSame(expected, actual)
}
@Test fun expectMostRecentItemButNoItemWasFoundThrows() = runTest {
val actual = assertFailsWith<AssertionError> {
emptyFlow<Any>().test {
expectMostRecentItem()
}
}
assertEquals("No item was found", actual.message)
}
@Test fun expectMostRecentItem() = runTest {
val onTwoSent = CompletableDeferred<Unit>()
val onTwoContinue = CompletableDeferred<Unit>()
val onCompleteSent = CompletableDeferred<Unit>()
val onCompleteContinue = CompletableDeferred<Unit>()
flowOf(1, 2, 3, 4, 5)
.map {
if (it == 3) {
onTwoSent.complete(Unit)
onTwoContinue.await()
}
it
}
.onCompletion {
onCompleteSent.complete(Unit)
onCompleteContinue.await()
}
.test {
onTwoSent.await()
assertEquals(2, expectMostRecentItem())
onTwoContinue.complete(Unit)
onCompleteSent.await()
assertEquals(5, expectMostRecentItem())
onCompleteContinue.complete(Unit)
awaitComplete()
}
}
@Test fun valuesDoNotConflate() = runTest {
val flow = MutableStateFlow(0)
flow.test {
flow.value = 1
flow.value = 2
flow.value = 3
assertEquals(0, awaitItem())
assertEquals(1, awaitItem())
assertEquals(2, awaitItem())
assertEquals(3, awaitItem())
}
}
@Test fun assertNullValuesWithExpectMostRecentItem() = runTest {
flowOf(1, 2, null).test {
assertEquals(null, expectMostRecentItem())
cancelAndIgnoreRemainingEvents()
}
}
@Test fun expectItemsAreSkipped() = runTest {
flowOf(1, 2, 3).test {
skipItems(2)
assertEquals(3, awaitItem())
awaitComplete()
}
}
@Test fun skipItemsThrowsOnComplete() = runTest {
flowOf(1, 2).test {
val message = assertFailsWith<AssertionError> {
skipItems(3)
}.message
assertEquals("Expected 3 items but got 2 items and Complete", message)
}
}
@Test fun expectErrorOnCompletionBeforeAllItemsWereSkipped() = runTest {
flowOf(1).test {
assertFailsWith<AssertionError> {
skipItems(2)
}
}
}
@Test fun expectErrorOnErrorReceivedBeforeAllItemsWereSkipped() = runTest {
val error = CustomThrowable("hi")
flow {
emit(1)
throw error
}.test {
val actual = assertFailsWith<AssertionError> {
skipItems(2)
}
assertSame(error, actual.cause)
}
}
@OptIn(ExperimentalTime::class)
@Test fun turbineSkipsDelaysInRunTest() = runTest {
val took = measureTime {
flow<Nothing> {
delay(5.seconds)
}.test {
awaitComplete()
}
}
assertTrue(took < 5.seconds, "$took > 5s")
}
@Test fun failsOnDefaultTimeout() = runTest {
neverFlow().test {
val actual = assertFailsWith<AssertionError> {
awaitItem()
}
assertEquals("No value produced in 1s", actual.message)
}
}
@Test fun awaitHonorsTestTimeoutNoTimeout() = runTest {
flow<Nothing> {
withContext(Default) {
delay(1100.milliseconds)
}
}.test(timeout = 1500.milliseconds) {
awaitComplete()
}
}
@Test fun awaitHonorsCoroutineContextTimeoutTimeout() = runTest {
neverFlow().test(timeout = 10.milliseconds) {
val actual = assertFailsWith<AssertionError> {
awaitItem()
}
assertEquals("No value produced in 10ms", actual.message)
}
}
@Test fun negativeTurbineTimeoutThrows() = runTest {
val actual = assertFailsWith<IllegalStateException> {
neverFlow().test(timeout = (-10).milliseconds) {
}
}
assertEquals("Turbine timeout must be greater than 0: -10ms", actual.message)
}
@Test fun zeroTurbineTimeoutThrows() = runTest {
val actual = assertFailsWith<IllegalStateException> {
neverFlow().test(timeout = 0.milliseconds) {
}
}
assertEquals("Turbine timeout must be greater than 0: 0s", actual.message)
}
@Test fun expectItemButWasErrorThrowsWithName() = runTest {
val error = CustomThrowable("hi")
val actual = assertFailsWith<AssertionError> {
flow<Unit> { throw error }.test(name = "unit flow") {
awaitItem()
}
}
assertEquals("Expected item for unit flow but found Error(CustomThrowable)", actual.message)
assertSame(error, actual.cause)
}
@Test fun timeoutThrowsWithName() = runTest {
neverFlow().test(timeout = 10.milliseconds, name = "never flow") {
val actual = assertFailsWith<AssertionError> {
awaitItem()
}
assertEquals("No value produced for never flow in 10ms", actual.message)
}
}
@Test fun unconsumedItemThrowsWithName() = runTest {
val actual = assertFailsWith<AssertionError> {
flow {
emit("item!")
emitAll(neverFlow()) // Avoid emitting complete
}.test(name = "item flow") { }
}
assertEquals(
"""
|Unconsumed events found for item flow:
| - Item(item!)
""".trimMargin(),
actual.message
)
}
@Test fun skipItemsThrowsOnCompleteWithName() = runTest {
flowOf(1, 2).test(name = "two item channel") {
val message = assertFailsWith<AssertionError> {
skipItems(3)
}.message
assertEquals("Expected 3 items for two item channel but got 2 items and Complete", message)
}
}
@Test
fun virtualTimeCanBeControlled() = runTest {
flow {
delay(5000)
emit("1")
delay(5000)
emit("2")
}.test {
expectNoEvents()
advanceTimeBy(5000)
expectNoEvents()
runCurrent()
assertEquals("1", awaitItem())
advanceTimeBy(5000)
expectNoEvents()
runCurrent()
assertEquals("2", awaitItem())
awaitComplete()
}
}
}
| apache-2.0 |
AlmasB/FXGL | fxgl/src/main/kotlin/com/almasb/fxgl/gameplay/GameDifficulty.kt | 1 | 442 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.gameplay
/**
* Represents game difficulty. Based on selected difficulty
* a game may change its behavior to provide appropriate level of challenge.
*
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
enum class GameDifficulty {
EASY, MEDIUM, HARD, NIGHTMARE
} | mit |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut08/cameraRelative.kt | 2 | 7077 | package glNext.tut08
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL3
import glNext.*
import glm.*
import glm.mat.Mat4
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.component.Mesh
import uno.glm.MatrixStack
import uno.glsl.programOf
import glm.quat.Quat
/**
* Created by GBarbieri on 10.03.2017.
*/
fun main(args: Array<String>) {
CameraRelative_Next().setup("Tutorial 08 - Camera Relative")
}
class CameraRelative_Next : Framework() {
object OffsetRelative {
val MODEL = 0
val WORLD = 1
val CAMERA = 2
val MAX = 3
}
var theProgram = 0
var modelToCameraMatrixUnif = 0
var cameraToClipMatrixUnif = 0
var baseColorUnif = 0
lateinit var ship: Mesh
lateinit var plane: Mesh
val frustumScale = calcFrustumScale(20.0f)
fun calcFrustumScale(fovDeg: Float) = 1.0f / glm.tan(fovDeg.rad / 2.0f)
val cameraToClipMatrix = Mat4(0.0f)
val camTarget = Vec3(0.0f, 10.0f, 0.0f)
var orientation = Quat(1.0f, 0.0f, 0.0f, 0.0f)
//In spherical coordinates.
val sphereCamRelPos = Vec3(90.0f, 0.0f, 66.0f)
var offset = OffsetRelative.MODEL
public override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
ship = Mesh(gl, javaClass, "tut08/Ship.xml")
plane = Mesh(gl, javaClass, "tut08/UnitPlane.xml")
cullFace {
enable()
cullFace = back
frontFace = cw
}
depth {
test = true
mask = true
func = lEqual
range = 0.0 .. 1.0
}
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut08", "pos-color-local-transform.vert", "color-mult-uniform.frag")
withProgram(theProgram) {
modelToCameraMatrixUnif = "modelToCameraMatrix".location
cameraToClipMatrixUnif = "cameraToClipMatrix".location
baseColorUnif = "baseColor".location
val zNear = 1.0f
val zFar = 600.0f
cameraToClipMatrix[0].x = frustumScale
cameraToClipMatrix[1].y = frustumScale
cameraToClipMatrix[2].z = (zFar + zNear) / (zNear - zFar)
cameraToClipMatrix[2].w = -1.0f
cameraToClipMatrix[3].z = 2f * zFar * zNear / (zNear - zFar)
use { cameraToClipMatrixUnif.mat4 = cameraToClipMatrix }
}
}
public override fun display(gl: GL3) = with(gl) {
clear {
color(0)
depth()
}
val currMatrix = MatrixStack()
val camPos = resolveCamPosition()
currMatrix setMatrix calcLookAtMatrix(camPos, camTarget, Vec3(0.0f, 1.0f, 0.0f))
usingProgram(theProgram) {
currMatrix.apply {
scale(100.0f, 1.0f, 100.0f)
glUniform4f(baseColorUnif, 0.2f, 0.5f, 0.2f, 1.0f)
modelToCameraMatrixUnif.mat4 = top()
plane.render(gl)
} run {
translate(camTarget)
applyMatrix(orientation.toMat4())
rotateX(-90.0f)
glUniform4f(baseColorUnif, 1.0f)
modelToCameraMatrixUnif.mat4 = top()
ship.render(gl, "tint")
}
}
}
fun resolveCamPosition(): Vec3 {
val phi = sphereCamRelPos.x.rad
val theta = (sphereCamRelPos.y + 90.0f).rad
val dirToCamera = Vec3(theta.sin * phi.cos, theta.cos, theta.sin * phi.sin)
return dirToCamera * sphereCamRelPos.z + camTarget
}
fun calcLookAtMatrix(cameraPt: Vec3, lookPt: Vec3, upPt: Vec3): Mat4 {
val lookDir = (lookPt - cameraPt).normalize()
val upDir = upPt.normalize()
val rightDir = (lookDir cross upDir).normalize()
val perpUpDir = rightDir cross lookDir
val rotationMat = Mat4(1.0f)
rotationMat[0] = Vec4(rightDir, 0.0f)
rotationMat[1] = Vec4(perpUpDir, 0.0f)
rotationMat[2] = Vec4(-lookDir, 0.0f)
rotationMat.transpose_()
val translMat = Mat4(1.0f)
translMat[3] = Vec4(-cameraPt, 1.0f)
return rotationMat * translMat
}
public override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
cameraToClipMatrix[0].x = frustumScale * (h / w.f)
cameraToClipMatrix[1].y = frustumScale
usingProgram(theProgram) {cameraToClipMatrixUnif.mat4 = cameraToClipMatrix}
glViewport(w, h)
}
public override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
plane.dispose(gl)
ship.dispose(gl)
}
override fun keyPressed(e: KeyEvent) {
val smallAngleIncrement = 9.0f
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_W -> offsetOrientation(Vec3(1.0f, 0.0f, 0.0f), +smallAngleIncrement)
KeyEvent.VK_S -> offsetOrientation(Vec3(1.0f, 0.0f, 0.0f), -smallAngleIncrement)
KeyEvent.VK_A -> offsetOrientation(Vec3(0.0f, 0.0f, 1.0f), +smallAngleIncrement)
KeyEvent.VK_D -> offsetOrientation(Vec3(0.0f, 0.0f, 1.0f), -smallAngleIncrement)
KeyEvent.VK_Q -> offsetOrientation(Vec3(0.0f, 1.0f, 0.0f), +smallAngleIncrement)
KeyEvent.VK_E -> offsetOrientation(Vec3(0.0f, 1.0f, 0.0f), -smallAngleIncrement)
KeyEvent.VK_SPACE -> {
offset = (++offset) % OffsetRelative.MAX
when (offset) {
OffsetRelative.MODEL -> println("MODEL_RELATIVE")
OffsetRelative.WORLD -> println("WORLD_RELATIVE")
OffsetRelative.CAMERA -> println("CAMERA_RELATIVE")
}
}
KeyEvent.VK_I -> sphereCamRelPos.y -= if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_K -> sphereCamRelPos.y += if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_J -> sphereCamRelPos.x -= if (e.isShiftDown) 1.125f else 11.25f
KeyEvent.VK_L -> sphereCamRelPos.x += if (e.isShiftDown) 1.125f else 11.25f
}
sphereCamRelPos.y = glm.clamp(sphereCamRelPos.y, -78.75f, 10.0f)
}
fun offsetOrientation(axis: Vec3, angDeg: Float) {
axis.normalize()
axis times_ glm.sin(angDeg.rad / 2.0f)
val scalar = glm.cos(angDeg.rad / 2.0f)
val offsetQuat = Quat(scalar, axis)
when (offset) {
OffsetRelative.MODEL -> orientation times_ offsetQuat
OffsetRelative.WORLD -> orientation = offsetQuat * orientation
OffsetRelative.CAMERA -> {
val camPos = resolveCamPosition()
val camMat = calcLookAtMatrix(camPos, camTarget, Vec3(0.0f, 1.0f, 0.0f))
val viewQuat = camMat.toQuat()
val invViewQuat = viewQuat.conjugate()
val worldQuat = invViewQuat * offsetQuat * viewQuat
orientation = worldQuat * orientation
}
}
orientation.normalize_()
}
} | mit |
AsynkronIT/protoactor-kotlin | proto-router/src/main/kotlin/actor/proto/router/BroadcastPoolRouterConfig.kt | 1 | 251 | package actor.proto.router
import actor.proto.Props
internal class BroadcastPoolRouterConfig(poolSize: Int, routeeProps: Props) : PoolRouterConfig(poolSize,routeeProps) {
override fun createRouterState(): RouterState = BroadcastRouterState()
}
| apache-2.0 |
RP-Kit/RPKit | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/listener/PlayerEditBookListener.kt | 1 | 2101 | /*
* 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.characters.bukkit.listener
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.ChatColor
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerEditBookEvent
class PlayerEditBookListener(private val plugin: RPKCharactersBukkit) : Listener {
@EventHandler
fun onPlayerEditBook(event: PlayerEditBookEvent) {
if (!event.isSigning) return
if (!plugin.config.getBoolean("books.change-author-on-sign")) return
val meta = event.newBookMeta
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player) ?: return
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return
var newAuthor = plugin.config.getString("books.author-format") ?: "\${player}"
newAuthor = ChatColor.translateAlternateColorCodes('&', newAuthor)
newAuthor = newAuthor.replace("\${player}", minecraftProfile.name)
newAuthor = newAuthor.replace("\${character}", character.name)
meta.author = newAuthor
event.newBookMeta = meta
}
} | apache-2.0 |
googlecodelabs/android-compose-codelabs | AdvancedStateAndSideEffectsCodelab/app/src/main/java/androidx/compose/samples/crane/util/NetworkUtil.kt | 1 | 1693 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.samples.crane.util
import coil.annotation.ExperimentalCoilApi
import coil.intercept.Interceptor
import coil.request.ImageResult
import coil.size.Size
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
/**
* A Coil [Interceptor] which appends query params to Unsplash urls to request sized images.
*/
@OptIn(ExperimentalCoilApi::class)
object UnsplashSizingInterceptor : Interceptor {
override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
val data = chain.request.data
val size = chain.size
if (data is String &&
data.startsWith("https://images.unsplash.com/photo-")
) {
val url = data.toHttpUrl()
.newBuilder()
.addQueryParameter("w", size.width.toString())
.addQueryParameter("h", size.height.toString())
.build()
val request = chain.request.newBuilder().data(url).build()
return chain.proceed(request)
}
return chain.proceed(chain.request)
}
}
| apache-2.0 |
RP-Kit/RPKit | bukkit/rpk-payment-lib-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/group/RPKPaymentGroupName.kt | 1 | 682 | /*
* Copyright 2021 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.payments.bukkit.group
data class RPKPaymentGroupName(val value: String) | apache-2.0 |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/project/tree/ProjectTree.kt | 2 | 3186 | /*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.project.tree
import com.efficios.jabberwocky.context.ViewGroupContext
import com.efficios.jabberwocky.project.TraceProject
import javafx.scene.control.ContextMenu
import javafx.scene.control.TreeCell
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import org.lttng.scope.application.actions.editProject
import org.lttng.scope.common.jfx.JfxUtils
import org.lttng.scope.common.jfx.ScopeMenuItem
import org.lttng.scope.views.context.ViewGroupContextManager
class ProjectTree : TreeView<String>() {
companion object {
private const val NO_PROJECT = "(no project opened)"
private const val PROJECT_SETUP_ACTION = "Project Setup"
}
private val emptyProjectRootItem = TreeItem(NO_PROJECT)
private val projectRootItem = RootTreeItem()
init {
setCellFactory { ProjectTreeCell() }
/* Setup listeners */
ViewGroupContextManager.getCurrent().registerProjectChangeListener(object : ViewGroupContext.ProjectChangeListener(this) {
override fun newProjectCb(newProject: TraceProject<*, *>?) {
JfxUtils.runLaterAndWait(Runnable {
root = if (newProject == null) {
emptyProjectRootItem
} else {
projectRootItem
}
})
}
})
root = emptyProjectRootItem
}
private inner class RootTreeItem : ProjectTreeItem(NO_PROJECT) {
override val contextMenu: ContextMenu
override fun initForProject(project: TraceProject<*, *>) {
value = project.name
}
override fun clear() {
/* Do not call super.clear() (which clears the children, which we don't want here!) */
}
init {
val projectSetupMenuItem = ScopeMenuItem(PROJECT_SETUP_ACTION) {
getCurrentProject()?.let { editProject(this@ProjectTree, it) }
}
contextMenu = ContextMenu(projectSetupMenuItem)
/* Setup tree skeleton */
children.addAll(TracesTreeItem(),
// BookmarksTreeItem(),
FiltersTreeItem(this@ProjectTree))
}
}
}
private class ProjectTreeCell : TreeCell<String>() {
override fun updateItem(item: String?, empty: Boolean) {
super.updateItem(item, empty)
val treeItem = treeItem
if (empty) {
text = null
graphic = null
contextMenu = null
tooltip = null
} else {
text = getItem()?.toString() ?: ""
graphic = treeItem.graphic
if (treeItem is ProjectTreeItem) {
contextMenu = treeItem.contextMenu
tooltip = treeItem.tooltip
}
}
}
}
| epl-1.0 |
zingmars/Cbox-bot | src/BasePlugin.kt | 1 | 2387 | /**
* Base plugin class to be inherited from
* Created by zingmars on 04.10.2015.
*/
package BotPlugins
import Containers.PluginBufferItem
import Settings
import Logger
import Plugins
import ThreadController
open public class BasePlugin() {
public var settings :Settings? = null
public var logger :Logger? = null
public var handler :Plugins? = null
public var pluginName :String? = null
public var controller :ThreadController? = null
init {
// This is the base class for all CBot plugins
// To make a plugin just extend this class and put it in src/BotPlugins/ (or whatever is defined in your settings file) directory
// Note - your filename must match your class name and it must be inside the BotPlugins package
// To initiate just override pubInit() (you can override this initializer too, but you won't have access to any variables at that point), and to do your logic just override connector.
// Note that your connector override will need to have the PluginBufferItem input for it to receive any messages.
// To send data back just add an element to any of the buffers available in ThreadController, (i.e. BoxBuffer will output anything send to it)
// Note that pubInit and connector both return a boolean value that indicates whether or not the plugin was successful
}
//non-overridable classes
final public fun initiate(settings :Settings, logger: Logger, pluginsHandler :Plugins, controller :ThreadController,pluginName :String) :Boolean
{
this.settings = settings
this.logger = logger
this.handler = pluginsHandler
this.pluginName = pluginName
this.controller = controller
if(this.pubInit()) this.logger?.LogPlugin(pluginName, "Started!")
else {
this.stop()
this.logger?.LogPlugin(pluginName, "failed to load!")
return false
}
return true
}
//overridable classes
open public fun pubInit() :Boolean { return true } //Initializer
open public fun connector(buffer :PluginBufferItem) :Boolean { return true } //Receives data from Plugin controller
open public fun stop() {} //This is run when the plugin is unloaded
open public fun executeCommand(command :String) :String { return "Plugin not configured" } //Execute a command
} | bsd-2-clause |
danirod/rectball | app/src/main/java/es/danirod/rectball/screens/StatisticsScreen.kt | 1 | 4515 | /*
* This file is part of Rectball
* Copyright (C) 2015-2017 Dani Rodríguez
*
* 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 es.danirod.rectball.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.glutils.FrameBuffer
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.viewport.FitViewport
import es.danirod.rectball.Pixmapper.captureScreenshot
import es.danirod.rectball.RectballGame
import es.danirod.rectball.SoundPlayer
import es.danirod.rectball.android.PixmapSharer
import es.danirod.rectball.android.R
import es.danirod.rectball.scene2d.listeners.ScreenPopper
import es.danirod.rectball.scene2d.ui.StatsTable
/**
* Statistics screen.
*/
class StatisticsScreen(game: RectballGame) : AbstractScreen(game) {
private lateinit var statsTable: StatsTable
private lateinit var pane: ScrollPane
private lateinit var backButton: TextButton
private lateinit var shareButton: ImageButton
private fun statsTable(): StatsTable {
val bold = game.skin.get("bold", LabelStyle::class.java)
val normal = game.skin.get("small", LabelStyle::class.java)
return StatsTable(game, bold, normal)
}
public override fun setUpInterface(table: Table) {
statsTable = statsTable()
pane = ScrollPane(statsTable, game.skin).apply {
fadeScrollBars = false
}
backButton = TextButton(game.context.getString(R.string.core_back), game.skin).apply {
addListener(ScreenPopper(game))
}
shareButton = ImageButton(game.skin, "share").apply {
addListener(object : ChangeListener() {
override fun changed(event: ChangeEvent, actor: Actor) {
game.player.playSound(SoundPlayer.SoundCode.SELECT)
val pmap = buildOffscreenTable()
PixmapSharer(game).share(game.context.getString(R.string.sharing_intent_title), "", pmap)
event.cancel()
}
})
}
table.apply {
add(pane).colspan(2).align(Align.topLeft).expand().fill().row()
add(backButton).fillX().expandX().expandY().height(80f).padTop(20f).align(Align.bottom)
add(shareButton).height(80f).padTop(20f).padLeft(10f).align(Align.bottomRight).row()
}
}
override fun getID(): Int = Screens.STATISTICS
private fun buildOffscreenTable(): Pixmap {
/* Build an FBO object where the offscreen table will be rendered. */
val aspectRatio = statsTable.width / statsTable.height
val width = 480
val height = (480 / aspectRatio).toInt()
val fbo = FrameBuffer(Pixmap.Format.RGBA8888, width, height, false)
/* Build a stage and add the virtual new table. */
val stage = Stage(FitViewport(480f, (480f / aspectRatio)))
val table = statsTable()
table.setFillParent(true)
table.pad(10f)
stage.addActor(table)
/* Then virtually render the stage. */
fbo.begin()
Gdx.gl.glClearColor(0.3f, 0.4f, 0.4f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
stage.act()
stage.draw()
val pmap = captureScreenshot(0, 0, width, height)
fbo.end()
fbo.dispose()
return pmap
}
} | gpl-3.0 |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/dao/Reminder.kt | 1 | 501 | package net.perfectdreams.loritta.morenitta.dao
import net.perfectdreams.loritta.morenitta.tables.Reminders
import org.jetbrains.exposed.dao.LongEntity
import org.jetbrains.exposed.dao.LongEntityClass
import org.jetbrains.exposed.dao.id.EntityID
class Reminder(id: EntityID<Long>) : LongEntity(id) {
companion object : LongEntityClass<Reminder>(Reminders)
var userId by Reminders.userId
var channelId by Reminders.channelId
var remindAt by Reminders.remindAt
var content by Reminders.content
} | agpl-3.0 |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/ocr/OCRTranslateData.kt | 1 | 566 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.ocr
import dev.kord.common.entity.Snowflake
import kotlinx.serialization.Serializable
import net.perfectdreams.loritta.cinnamon.discord.interactions.components.data.SingleUserComponentData
import net.perfectdreams.loritta.cinnamon.discord.utils.google.Language
@Serializable
data class OCRTranslateData(
override val userId: Snowflake,
val sourceLanguage: Language,
val targetLanguage: Language,
val isEphemeral: Boolean,
val text: String
) : SingleUserComponentData | agpl-3.0 |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/loritta/PostRaffleStatusRoute.kt | 1 | 3462 | package net.perfectdreams.loritta.morenitta.website.routes.api.v1.loritta
import com.github.salomonbrys.kotson.int
import com.github.salomonbrys.kotson.jsonObject
import com.github.salomonbrys.kotson.long
import com.github.salomonbrys.kotson.obj
import com.github.salomonbrys.kotson.string
import com.google.gson.JsonParser
import net.perfectdreams.loritta.morenitta.commands.vanilla.economy.LoraffleCommand
import net.perfectdreams.loritta.morenitta.threads.RaffleThread
import io.ktor.server.application.*
import io.ktor.server.request.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.SonhosPaymentReason
import net.perfectdreams.loritta.morenitta.website.routes.api.v1.RequiresAPIAuthenticationRoute
import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson
class PostRaffleStatusRoute(loritta: LorittaBot) : RequiresAPIAuthenticationRoute(loritta, "/api/v1/loritta/raffle") {
companion object {
val logger = KotlinLogging.logger {}
}
override suspend fun onAuthenticatedRequest(call: ApplicationCall) {
val json = withContext(Dispatchers.IO) { JsonParser.parseString(call.receiveText()).obj }
val userId = json["userId"].long
val quantity = json["quantity"].int
val localeId = json["localeId"].string
val currentUniqueId = RaffleThread.raffleRandomUniqueId
RaffleThread.buyingOrGivingRewardsMutex.withLock {
if (currentUniqueId != RaffleThread.raffleRandomUniqueId || !RaffleThread.isReady) {
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.STALE_RAFFLE_DATA.toString()
)
)
return@withLock
}
val currentUserTicketQuantity = RaffleThread.userIds.count { it == userId }
if (currentUserTicketQuantity + quantity > LoraffleCommand.MAX_TICKETS_BY_USER_PER_ROUND) {
if (currentUserTicketQuantity == LoraffleCommand.MAX_TICKETS_BY_USER_PER_ROUND) {
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.THRESHOLD_EXCEEDED.toString()
)
)
} else {
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.TOO_MANY_TICKETS.toString(),
"ticketCount" to currentUserTicketQuantity
)
)
}
return
}
val requiredCount = quantity.toLong() * 250
logger.info("$userId irá comprar $quantity tickets por ${requiredCount}!")
val lorittaProfile = loritta.getOrCreateLorittaProfile(userId)
if (lorittaProfile.money >= requiredCount) {
loritta.newSuspendedTransaction {
lorittaProfile.takeSonhosAndAddToTransactionLogNested(
requiredCount,
SonhosPaymentReason.RAFFLE
)
}
for (i in 0 until quantity) {
RaffleThread.userIds.add(userId)
}
RaffleThread.logger.info("${userId} comprou $quantity tickets por ${requiredCount}! (Antes ele possuia ${lorittaProfile.money + requiredCount}) sonhos!")
loritta.raffleThread.save()
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.SUCCESS.toString()
)
)
} else {
call.respondJson(
jsonObject(
"status" to LoraffleCommand.BuyRaffleTicketStatus.NOT_ENOUGH_MONEY.toString(),
"canOnlyPay" to requiredCount - lorittaProfile.money
)
)
}
}
}
} | agpl-3.0 |
darakeon/dfm | android/Lib/src/test/kotlin/com/darakeon/dfm/lib/api/ResponseHandlerTest.kt | 1 | 5150 | package com.darakeon.dfm.lib.api
import com.darakeon.dfm.lib.BuildConfig
import com.darakeon.dfm.lib.R
import com.darakeon.dfm.lib.api.entities.Body
import com.darakeon.dfm.lib.api.entities.Environment
import com.darakeon.dfm.lib.api.entities.Theme
import com.darakeon.dfm.lib.auth.getValue
import com.darakeon.dfm.lib.auth.setValue
import com.darakeon.dfm.lib.utils.ActivityMock
import com.darakeon.dfm.lib.utils.ApiActivity
import com.darakeon.dfm.lib.utils.CallMock
import com.darakeon.dfm.testutils.BaseTest
import com.darakeon.dfm.testutils.TestException
import com.darakeon.dfm.testutils.api.internetError
import com.darakeon.dfm.testutils.api.internetSlow
import com.darakeon.dfm.testutils.api.noBody
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog
import retrofit2.Response
import java.net.ConnectException
import java.net.SocketTimeoutException
@RunWith(RobolectricTestRunner::class)
internal class ResponseHandlerTest: BaseTest() {
private lateinit var activity: ApiActivity
private lateinit var handler: ResponseHandler<ApiActivity, String>
private var result: String? = null
private val waitEnded
get() = activity.waitEnded
@Before
fun setup() {
activity = ActivityMock(ApiActivity::class).create()
handler = ResponseHandler(activity) {
result = it
}
}
@Test
fun onResponse_BodyNull() {
val body: Body<String>? = null
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(
activity.errorText,
`is`(noBody)
)
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onResponse_BodyChildrenNull() {
val body = Body<String>(null, null, null, null)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(
activity.errorText,
`is`("Not identified site error. Contact us.")
)
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onResponse_BodySuccessAndFailed() {
val body = Body("success", null, "confusing result", 0)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(
activity.errorText,
`is`("confusing result")
)
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onResponse_ResponseBodyEnvironment() {
val env = Environment(Theme.LightNature, "pt-BR")
val body = Body("result", env, null, null)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(activity.getValue("Theme").toInt(), `is`(R.style.LightNature))
assertThat(activity.getValue("Language"), `is`("pt_BR"))
assertTrue(waitEnded)
assertThat(result, `is`("result"))
}
@Test
fun onResponse_BodySuccess() {
val body = Body("result", null, null, null)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertTrue(waitEnded)
assertThat(result, `is`("result"))
}
@Test
fun onResponse_ErrorOfTfa() {
val errorCode = activity.resources.getInteger(R.integer.TFA)
val body = Body<String>(null, null, "TFA", errorCode)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
val alert = getLatestAlertDialog()
assertNull(alert)
assertTrue(waitEnded)
assertNull(result)
assertTrue(activity.checkedTFA)
}
@Test
fun onResponse_ErrorOfUninvited() {
val errorCode = activity.resources.getInteger(R.integer.uninvited)
val body = Body<String>(null, null, "TFA", errorCode)
val response = Response.success(body)
activity.setValue("Ticket", "fake")
handler.onResponse(CallMock(), response)
val alert = getLatestAlertDialog()
assertNull(alert)
assertTrue(waitEnded)
assertNull(result)
assertTrue(activity.loggedOut)
}
@Test
fun onResponse_ErrorOfAnotherType() {
val body = Body<String>(null, null, "generic", 273)
val response = Response.success(body)
handler.onResponse(CallMock(), response)
assertThat(activity.errorText, `is`("generic"))
assertTrue(waitEnded)
assertNull(result)
}
@Test(expected = TestException::class)
fun onFailure_ErrorCommonDebug() {
if (!BuildConfig.DEBUG) throw TestException()
handler.onFailure(CallMock(), TestException())
}
@Test
fun onFailure_ErrorCommonRelease() {
if (BuildConfig.DEBUG) return
val error = TestException()
handler.onFailure(CallMock(), error)
assertThat(activity.errorText, `is`(internetError))
assertThat(activity.error, `is`(error))
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onFailure_ErrorOfSocketTimeout() {
handler.onFailure(CallMock(), SocketTimeoutException())
assertThat(
activity.errorText,
`is`(internetSlow)
)
assertTrue(waitEnded)
assertNull(result)
}
@Test
fun onFailure_ErrorOfConnect() {
handler.onFailure(CallMock(), ConnectException())
assertThat(
activity.errorText,
`is`(internetSlow)
)
assertTrue(waitEnded)
assertNull(result)
}
}
| gpl-3.0 |
appnexus/mobile-sdk-android | examples/kotlin/SimpleDemo/app/src/main/java/appnexus/example/kotlinsample/MainApplication.kt | 1 | 366 | package appnexus.example.kotlinsample
import android.app.Application
import android.widget.Toast
import com.appnexus.opensdk.XandrAd
class MainApplication: Application() {
override fun onCreate() {
super.onCreate()
XandrAd.init(10094, this, true) {
Toast.makeText(this, "Init Completed", Toast.LENGTH_SHORT).show()
}
}
} | apache-2.0 |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/tcm/patho/OrganSyndrome.kt | 1 | 48090 | package at.cpickl.gadsu.tcm.patho
import at.cpickl.gadsu.tcm.model.Substances
import at.cpickl.gadsu.tcm.model.YinYang
// TODO unbedingt die zunge+puls in eigenen datacontainer, damit diese nicht included werden koennen!
/*
TODOs:
- manche symtpoms haben Qi/Blut/Yin/Yang bezug, manche starke Zang, manche typisch fuer element
- CLI app schreiben, die auswertung printed; zb welche symptoms nur ein zang betreffen, ...
- 9er gruppe finden (auch zukuenftige beruecksichtigen)
- symptoms mit dynTreats matchen (zunge, puls)
- TCM props implementieren
*/
enum class OrganSyndrome(
// MINOR label LONG vs SHORT
val label: String,
val sqlCode: String,
val description: String = "",
val organ: ZangOrgan,
val part: SyndromePart? = null,
val tendency: MangelUeberfluss,
val externalFactors: List<ExternalPathos> = emptyList(),
val symptoms: List<Symptom>
) {
// LEBER
// =================================================================================================================
// verdauung, emo, mens
// sehnen, naegel, augen
// genitalregion, rippenbogen, kopf, augen (meridianverlauf)
LeBlutXu(
label = "Leber Blut Mangel",
sqlCode = "LeBlutXu",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.BlutXu.symptoms + listOf(
// augen
Symptom.UnscharfesSehen,
Symptom.VerschwommenesSehen,
Symptom.Nachtblindheit,
Symptom.MouchesVolantes,
Symptom.TrockeneAugen,
// sehnen
Symptom.SteifeSehnen,
Symptom.Zittern,
// mens
Symptom.AussetzerMenstruation,
Symptom.VerlaengerterZyklus,
// zunge
Symptom.BlasseZunge,
// puls
Symptom.DuennerPuls // fadenfoermig
)
),
LeYinXu(// wie Blutmangel, aber plus Mangel-Hitze
label = "Leber Yin Mangel",
sqlCode = "LeYinXu",
description = "Symptome ähnlich von Leber Feuer, da das Yin das Yang nicht halten kann und aufsteigt, aber da es ein Mangel ist schwächer ausgeprägt.",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.YinXu.symptoms + listOf(
// augen
Symptom.TrockeneAugen,
Symptom.Nachtblindheit,
// ohren
Symptom.Tinnitus,
// Le yang steigt auf
Symptom.Kopfschmerzen,
Symptom.Gereiztheit,
Symptom.Zornesanfaelle,
Symptom.Laehmung,
Symptom.HalbseitigeLaehmung,
Symptom.Schlaganfall,
// zunge
Symptom.RoteZunge, // TODO should not contain BlasseZunge from LeBlutXu! maybe outsource tongue+pulse symptoms in own variable...
Symptom.WenigBelag,
// puls
Symptom.BeschleunigterPuls,
Symptom.DuennerPuls,
Symptom.SchwacherPuls
)
),
LeBlutStau(
label = "Leber Blut Stau",
sqlCode = "LeBlutStau",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
// misc
Symptom.Knoten,
Symptom.Tumore,
Symptom.LeberVergroesserung,
Symptom.MilzVergroesserung,
Symptom.DunkleGesichtsfarbe,
Symptom.StumpfeGesichtsfarbe,
// schmerz
Symptom.StechenderSchmerz,
Symptom.FixierterSchmerz,
Symptom.SchmerzNachtsSchlimmer,
// mens
Symptom.DunklesMenstruationsblut,
Symptom.ZaehesMenstruationsblut,
Symptom.KlumpenInBlut,
// zunge
Symptom.VioletteZunge,
Symptom.DunkleZunge,
Symptom.BlauVioletteZungenpunkte,
Symptom.GestauteVenen, // MINOR gestaute == unterzungenvenen??
Symptom.GestauteUnterzungenvenen,
// puls
Symptom.RauherPuls
)
),
LeQiStau(
label = "Leber Qi Stau",
description = "Greift MP an.",
sqlCode = "LeQiStau",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
// verdauung
Symptom.VielAppettit,
Symptom.WenigAppetit,
Symptom.VoelleGefuehl,
Symptom.Blaehungen,
Symptom.Aufstossen,
Symptom.Sodbrennen,
Symptom.Brechreiz,
Symptom.Erbrechen,
Symptom.Magenschmerzen,
Symptom.Uebelkeit,
Symptom.MorgendlicheUebelkeit,
Symptom.UnregelmaessigerStuhl,
Symptom.WechselhafteVerdauung,
// meridian
Symptom.SpannungZwerchfell,
Symptom.SchmerzZwerchfell,
Symptom.Seufzen,
Symptom.ThorakalesEngegefuehl,
Symptom.DruckgefuehlBrustbein,
Symptom.BrustspannungPMS,
Symptom.Schulterschmerzen,
Symptom.Nackenschmerzen,
Symptom.Kopfschmerzen,
Symptom.FroschImHals,
// mens
Symptom.Zyklusunregelmaessigkeiten,
Symptom.PMS,
Symptom.Regelkraempfe,
Symptom.UnterbauchziehenPMS,
Symptom.EmotionaleSchwankungenMens,
// emotionen
Symptom.Reizbarkeit,
Symptom.Aufbrausen,
Symptom.Zornesausbrueche,
Symptom.Launisch,
Symptom.Frustration,
Symptom.Depression,
Symptom.UnterdrueckteGefuehle,
// zunge
Symptom.NormaleZunge,
Symptom.RoteZungenspitze,
Symptom.RoterZungenrand,
// puls
Symptom.SaitenfoermigerPuls
)
),
LeFeuer(
label = "Leber Feuer (lodert nach oben)",
sqlCode = "LeFeuer",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.HeftigeKopfschmerzen,
Symptom.KopfschmerzenScheitel,
Symptom.Tinnitus,
Symptom.Hoersturz,
Symptom.Schwindel,
Symptom.RoteBindehaut,
Symptom.RoteSkleren,
Symptom.TrockenerMund,
Symptom.BittererMundgeschmack,
Symptom.Nasenbluten,
Symptom.BlutHusten,
Symptom.BlutErbrechen,
// psycho
Symptom.Zornesausbrueche,
Symptom.Gereiztheit,
Symptom.Gewalttaetig,
// verdauung
Symptom.Magenschmerzen,
Symptom.Sodbrennen,
Symptom.Brechreiz,
Symptom.Erbrechen,
Symptom.Verstopfung,
Symptom.BrennenderDurchfall,
// allg. zeichen ueberfluss-hitze (He-Feuer, holz das feuer uebernaehrt); aehnlich dem LeBlutXu
Symptom.Unruhe,
Symptom.Schlaflosigkeit,
Symptom.Durst,
Symptom.Durchfall,
Symptom.WenigUrin,
Symptom.DunklerUrin,
Symptom.RotesGesicht,
Symptom.RoteAugen,
Symptom.Palpitationen,
// zunge
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.RoterZungenrand,
Symptom.GelberBelag,
// puls
Symptom.SaitenfoermigerPuls,
Symptom.BeschleunigterPuls,
Symptom.KraeftigerPuls
)
),
LeWindHitze(
label = "Leber Wind (Extreme Hitze)",
sqlCode = "LeWindHitze",
description = "Von sehr hohem Fieber. Fieberkrämpfe, Verkrampfungen, Augen nach oben rollen.",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LeWind + listOf(// MINOR + ueberfluss-hitze
Symptom.Kraempfe,
Symptom.Koma,
Symptom.Delirium,
// zunge
Symptom.RoteZunge,
Symptom.ScharlachRoteZunge,
Symptom.TrockenerBelag,
Symptom.GelberBelag,
Symptom.SteifeZunge,
// puls
Symptom.SchnellerPuls,
Symptom.VollerPuls,
Symptom.SaitenfoermigerPuls
)
),
LeWindYangAuf(
label = "Leber Wind (Aufsteigendes Leber Yang)",
description = "Ursache ist Le/Ni Yin-Mangel",
sqlCode = "LeWindLeYang",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.Schwindel,
Symptom.Schwanken,
Symptom.KopfUnwillkuerlichBewegt,
Symptom.Laehmung,
Symptom.HalbseitigeLaehmung,
// psycho
Symptom.Desorientiertheit,
Symptom.Bewusstseinsverlust,
Symptom.Sprachstoerungen,
// zunge
Symptom.RoteZunge,
Symptom.WenigBelag,
Symptom.FehlenderBelag,
// puls
Symptom.BeschleunigterPuls
)
),
LeWindBlutXu(
label = "Leber Wind (Blut Mangel)",
description = "Ursache ist Le/allgemeiner Blut-Mangel",
sqlCode = "LeWindBlutXu",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = LeBlutXu.symptoms + listOf(
Symptom.Tics,
Symptom.Augenzucken,
Symptom.KopfUnwillkuerlichBewegt,
Symptom.Sehstoerungen,
Symptom.Schwindel,
Symptom.Benommenheit,
Symptom.DuennerBelag,
Symptom.WeisserBelag
)
),
LeFeuchteHitze(
label = "Feuchtigkeit und Hitze in Le und Gb",
description = "Ursache ist Le-Qi-Stau.",
sqlCode = "LeFeuchteHitze",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.SchmerzBrustkorb,
Symptom.SchmerzZwerchfell,
Symptom.Durst,
Symptom.Unruhe,
Symptom.Gereiztheit,
Symptom.KonzentrierterUrin,
Symptom.DunklerUrin,
Symptom.Fieber, // niedrig, anhaltend
Symptom.Gelbsucht,
// milz
Symptom.WenigAppetit,
Symptom.Brechreiz,
Symptom.Erbrechen,
Symptom.DurckgefuehlBauch,
Symptom.Blaehungen,
Symptom.BittererMundgeschmack,
// frauen
Symptom.GelberAusfluss,
Symptom.RiechenderAusfluss,
Symptom.JuckreizScheide,
Symptom.Entzuendungsherde, // bereich Le-/Gb-meridian
Symptom.Hautpilz,
Symptom.Herpes,
// maenner
Symptom.Hodenschmerzen,
Symptom.Hodenschwellungen,
Symptom.Ausfluss,
Symptom.Prostatitis,
Symptom.Hautausschlag, // bereich Le-/Gb-meridian
// zunge
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.RoterZungenrand,
Symptom.DickerBelag,
Symptom.GelberBelag,
Symptom.SchmierigerBelag,
// puls
Symptom.BeschleunigterPuls,
Symptom.SaitenfoermigerPuls,
Symptom.SchluepfrigerPuls
)
),
LeKaelteJingLuo(
label = "Kälte im Lebermeridian",
sqlCode = "LeKaltMerid",
organ = ZangOrgan.Liver,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.Unterbauchschmerzen,
Symptom.Kraempfe,
Symptom.Kontraktionen,
Symptom.WaermeErleichtert,
Symptom.Unfruchtbarkeit,
// frau
Symptom.Menstruationskraempfe,
Symptom.Ausfluss,
// mann
Symptom.Impotenz,
Symptom.UntenZiehendeHoden,
// zunge
Symptom.BlasseZunge,
Symptom.WeisserBelag,
Symptom.FeuchterBelag,
// puls
Symptom.VerlangsamterPuls,
Symptom.TieferPuls,
Symptom.SaitenfoermigerPuls
)
),
// HERZ
// =================================================================================================================
HeBlutXu(
label = "He-Blut-Mangel",
sqlCode = "HeBlutXu",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.BlutXu.symptoms + SpecificSymptoms.HeBlutXu
),
HeYinXu(
label = "He-Yin-Mangel",
sqlCode = "HeYinXu",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = SpecificSymptoms.HeBlutXu + GeneralSymptoms.YinXu.symptoms + listOf(
Symptom.MehrDurstSpaeter,
Symptom.Gereiztheit,
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.DuennerBelag,
Symptom.FehlenderBelag,
Symptom.BeschleunigterPuls
)
),
HeQiXu(
label = "He-Qi-Mangel",
sqlCode = "HeQiXu",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.QiXu.symptoms + SpecificSymptoms.HeQiXu
),
HeYangXu(
label = "He-Yang-Mangel",
sqlCode = "HeYangXu",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = SpecificSymptoms.HeQiXu + GeneralSymptoms.YangXu.symptoms + listOf(
Symptom.ThorakalesEngegefuehl,
// zunge
Symptom.FeuchteZunge,
// puls
Symptom.LangsamerPuls
)
),
// MINOR 3 yang xu subtypes got symptoms of HeYangXu as well??
HeYangXuBlutBewegen(
label = "He-Yang-Mangel (Yang kann das Blut nicht ausreichend bewegen)",
sqlCode = "HeYangXuBlutBewegen",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.HeYangXuPulsTongue + listOf(
Symptom.Zyanose,
Symptom.ThorakalesEngegefuehl,
Symptom.MaessigeSchmerzen,
Symptom.Atemnot // belastungs- / ruhedyspnoe
)
),
HeYangXuUndNiYangErschopeft(
label = "He-Yang-Mangel (He/Ni Yang erschöpft)",
sqlCode = "HeYangXuUndNiYangErschopeft",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.HeYangXuPulsTongue + listOf(
Symptom.UrinierenSchwierigkeiten,
Symptom.Oedeme, // oft oben
Symptom.Husten,
Symptom.Wasserretention // ansammlung (in der lunge)
)
),
HeYangXuKollaps(
label = "He-Yang-Mangel (Kollaps, Yang bricht zusammen)",
sqlCode = "HeYangXuKollaps",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.HeYangXuPulsTongue + listOf(
Symptom.KaelteGefuehl, // extremes
Symptom.Zittern,
Symptom.Zyanose,
Symptom.SchweissAusbruch,
Symptom.Bewusstseinsverlust
)
),
HeBlutStau(
label = "Herz Blut Stauung",
sqlCode = "HeBlutStau",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.StechenderSchmerz,
Symptom.FixierterSchmerz,
Symptom.ArmAusstrahlendeSchmerzen,
Symptom.Magenschmerzen,
Symptom.ThorakalesEngegefuehl,
Symptom.Druckgefuehl,
Symptom.KalteExtremitaeten,
Symptom.Kurzatmigkeit,
Symptom.Palpitationen,
Symptom.BlaufaerbungGesicht,
Symptom.BlaufaerbungNaegeln,
Symptom.VioletteZunge,
Symptom.VioletteZungenflecken,
Symptom.DuennerBelag,
Symptom.RauherPuls,
Symptom.HaengenderPuls,
Symptom.SchwacherPuls,
Symptom.UnregelmaessigerPuls,
Symptom.SaitenfoermigerPuls
)
),
HeFeuer(
label = "Loderndes Herz Feuer",
sqlCode = "HeFeuer",
description = "Stärkere variante von He-Yin-Mangel",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.RotesGesicht,
Symptom.Erosionen,
Symptom.Ulzerationen,
Symptom.BittererMundgeschmack,
Symptom.UrinierenBrennen,
Symptom.BlutInUrin,
Symptom.Gewalttaetig,
Symptom.StarkeSchlafstoerungen,
Symptom.MehrDurst,
Symptom.Unruhe,
Symptom.Gereiztheit,
Symptom.Palpitationen,
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.DuennerBelag,
Symptom.GelberBelag,
Symptom.Zungenspalt,
Symptom.BeschleunigterPuls,
Symptom.KraeftigerPuls,
Symptom.UeberflutenderPuls,
Symptom.JagenderPuls
)
),
HeSchleimFeuerVerstoert(
label = "Schleim-Feuer verstört das Herz",
description = "Psychisches Bild, extrovertiert",
sqlCode = "HeSchleimFeuer",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.Extrovertiertheit,
Symptom.Unruhe,
Symptom.Gereiztheit,
Symptom.Verwirrung,
Symptom.VerwirrtesSprechen,
Symptom.GrundlosesLachen,
Symptom.Weinen,
Symptom.Schreien,
Symptom.Gewalttaetig,
Symptom.Schlafstoerungen,
Symptom.ThorakalesEngegefuehl,
Symptom.BittererMundgeschmack,
Symptom.Palpitationen,
Symptom.RoteZunge,
Symptom.RoteZungenspitze,
Symptom.GelberBelag,
Symptom.SchmierigerBelag,
Symptom.Dornen,
Symptom.BeschleunigterPuls,
Symptom.SchluepfrigerPuls,
Symptom.SaitenfoermigerPuls // Le einfluss
)
),
HeSchleimKaelteVerstopft(
label = "Kalter Schleim verstopft die Herzöffnungen",
description = "Psychisches Bild, extrovertiert",
sqlCode = "HeSchleimKaelte",
organ = ZangOrgan.Heart,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.Introvertiertheit,
Symptom.Verwirrung,
Symptom.GetruebteBewusstsein,
Symptom.Lethargie,
Symptom.Depression,
Symptom.Selbstgespraeche,
Symptom.DahinStarren,
Symptom.NichtReden,
Symptom.Bewusstseinsverlust,
Symptom.RasselndeKehle, // beim einatmen
Symptom.BlasseZunge,
Symptom.DickerBelag,
Symptom.WeisserBelag,
Symptom.SchmierigerBelag,
Symptom.VerlangsamterPuls,
Symptom.SchluepfrigerPuls
)
),
// MILZ
// =================================================================================================================
MPQiXu(
label = "Milz Qi Mangel",
sqlCode = "MPQiXu",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.QiXu.symptoms + SpecificSymptoms.MPQiXu
),
MPYangXu(
label = "Milz Yang Mangel",
sqlCode = "MPYangXu",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Mangel,
symptoms = SpecificSymptoms.MPQiXu + GeneralSymptoms.YangXu.symptoms + listOf(
Symptom.KalterBauch,
Symptom.Unterbauchschmerzen,
Symptom.Kraempfe, // durch waerme gelindert
Symptom.Oedeme,
// verdauung
Symptom.WeicherStuhl,
Symptom.WaessrigerStuhl,
Symptom.UnverdauteNahrungInStuhl,
Symptom.HahnenschreiDiarrhoe,
// zunge
Symptom.LeichtBlaeulicheZunge,
Symptom.NasseZunge,
// puls
Symptom.TieferPuls,
Symptom.LangsamerPuls
)
),
MPYangXuAbsinkenQi(
label = "Absinkendes Milz-Qi",
sqlCode = "MPQiAbsinken",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Mangel,
symptoms = MPYangXu.symptoms + listOf(
Symptom.UntenZiehendeBauchorgane,
Symptom.Prolaps, // "Organsenkung" // von bauch- und unterleibsorgane: magen, darm, nieren, blase, uterus, scheide
Symptom.Schweregefuehl,
Symptom.Hernien,
Symptom.Krampfadern,
Symptom.Haemorrhoiden
)
),
MPYangXuBlutUnkontrolle(
label = "Milz kann das Blut nicht kontrollieren",
sqlCode = "MPBlutUnkontrolle",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Mangel,
symptoms = MPYangXu.symptoms + listOf(
Symptom.Petechien,
Symptom.Purpura,
Symptom.BlaueFlecken,
Symptom.Blutsturz,
Symptom.Hypermenorrhoe,
Symptom.Schmierblutung,
Symptom.BlutInUrin,
Symptom.BlutImStuhl
)
),
MPFeuchtKalt(
label = "Kälte und Feuchtigkeit in Milz",
sqlCode = "MPFeuchtKalt",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
// schwere
Symptom.Muedigkeit,
Symptom.Schlappheit,
Symptom.SchwererKopf,
Symptom.SchwereGliedmassen,
// trinken, essen
Symptom.KeinDurst,
Symptom.WenigDurst,
Symptom.KeinAppetit,
Symptom.VerminderterGeschmackssinn,
Symptom.FaderMundgeschmack,
Symptom.BlanderMundgeschmack,
// verdauung
Symptom.VoelleGefuehl,
Symptom.DurckgefuehlBauch,
Symptom.Uebelkeit,
Symptom.Brechreiz,
Symptom.Erbrechen,
Symptom.WeicherStuhl,
Symptom.KlebrigerStuhl,
Symptom.TrueberUrin,
// misc
Symptom.ThorakalesEngegefuehl,
Symptom.Bauchschmerzen, // besser waerme
Symptom.KaelteGefuehl,
Symptom.Ausfluss,
Symptom.Gelbsucht,
// zunge
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.DickerBelag,
Symptom.WeisserBelag,
// puls
Symptom.SchluepfrigerPuls,
Symptom.VerlangsamterPuls
)
),
MPFeuchtHitze(
label = "Hitze und Feuchtigkeit in Milz",
sqlCode = "MPFeuchtHitze",
organ = ZangOrgan.Spleen,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.ThorakalesEngegefuehl,
Symptom.DurckgefuehlBauch,
Symptom.Brechreiz,
Symptom.Uebelkeit,
Symptom.Erbrechen,
Symptom.Schlappheit,
Symptom.Schweregefuehl,
Symptom.WenigUrin,
Symptom.KonzentrierterUrin,
Symptom.TrueberUrin,
Symptom.Durst,
Symptom.Bauchschmerzen,
Symptom.AversionWaerme,
Symptom.WeicherStuhl,
Symptom.StinkenderStuhl,
Symptom.Durchfall,
Symptom.AnalesBrennen,
Symptom.Fieber,
Symptom.Gelbsucht,
Symptom.RoteZunge,
Symptom.GelberBelag,
Symptom.DickerBelag,
Symptom.SchmierigerBelag,
Symptom.BeschleunigterPuls,
Symptom.SchluepfrigerPuls
)
),
// LUNGE
// =================================================================================================================
LuQiXu(
label = "Lu-Qi-Mangel",
sqlCode = "LuQiXu",
description = "Hat etwas von einer Art Depression aber ohne der Trauer.",
organ = ZangOrgan.Lung,
part = SyndromePart.Qi,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.QiXu.symptoms + listOf(
Symptom.Kurzatmigkeit,
Symptom.Husten,
Symptom.DuennerSchleim,
Symptom.VielSchleim,
Symptom.Asthma,
Symptom.FlacheAtmung,
Symptom.WenigLeiseSprechen,
Symptom.EnergieMangel,
Symptom.TrauererloseDepression,
Symptom.LeichtesSchwitzen,
Symptom.Erkaeltungen,
Symptom.AversionKaelte, // MINOR really? eigentlich erst bei YangXu...
Symptom.NormaleZunge,
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.SchwacherPuls,
Symptom.WeicherPuls,
Symptom.LeererPuls
)),
LuYinXu(
label = "Lu-Yin-Mangel",
sqlCode = "LuYinXu",
organ = ZangOrgan.Lung,
part = SyndromePart.Yin,
tendency = MangelUeberfluss.Mangel,
// TODO allg-YinMangel-symptoms + allg-QiMangel-symptoms
symptoms = LuQiXu.symptoms + listOf(
Symptom.Heiserkeit,
Symptom.TrockenerHals,
Symptom.TrockenerHusten,
Symptom.HitzeGefuehlAbends,
Symptom.KeinSchleim,
Symptom.WenigSchleim,
Symptom.KlebrigerSchleim,
Symptom.BlutInSchleim,
Symptom.RoteZunge,
Symptom.TrockeneZunge,
Symptom.WenigBelag,
Symptom.BeschleunigterPuls,
Symptom.DuennerPuls
)),
LuWindKaelteWind(
label = "Wind-Kälte attackiert Lu (Invasion äußerer Wind)",
sqlCode = "LuWind",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LuWindKaelte + listOf(
Symptom.AversionWind,
Symptom.FroestelnStarkerAlsFieber,
Symptom.KratzenderHals,
Symptom.Kopfschmerzen,
Symptom.Schwitzen
)
),
LuWindKaelteKaelte(
label = "Wind-Kälte attackiert Lu (Invasion äußere Kälte)",
sqlCode = "LuKalt",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LuWindKaelte + listOf(
Symptom.AversionKaelte,
Symptom.FroestelnStarkerAlsFieber,
Symptom.KeinSchwitzen,
Symptom.WenigDurst,
Symptom.KeinDurst,
Symptom.Husten,
Symptom.Schnupfen,
Symptom.KlarerSchleim,
Symptom.WaessrigerSchleim,
Symptom.VerstopfteNase,
Symptom.Muskelschmerzen,
Symptom.Kopfschmerzen
)
),
LuWindHitze(
label = "Wind-Hitze attackiert Lu",
sqlCode = "LuHitze",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
// TODO plus symptoms of ExoWind; evtl plus HitzeSymptoms
symptoms = listOf(
Symptom.FieberStaerkerAlsFroesteln,
Symptom.Schwitzen,
Symptom.Husten,
Symptom.GelberSchleim,
Symptom.VerstopfteNase,
Symptom.Schnupfen,
Symptom.Halsschmerzen,
Symptom.RoterHals,
Symptom.RoterRachen,
Symptom.MehrDurst,
Symptom.MoechteKaltesTrinken,
Symptom.RoteZungenspitze,
Symptom.DuennerBelag,
Symptom.GelberBelag,
Symptom.OberflaechlicherPuls,
Symptom.BeschleunigterPuls
)
),
LuTrocken(
label = "Trockenheit attackiert Lu",
sqlCode = "LuTrocken",
description = "Keine wirklichen Hitze Symptome.",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = listOf(
Symptom.TrockenerMund,
Symptom.TrockeneNase,
Symptom.TrockenerRachen,
Symptom.TrockenerHals,
Symptom.TrockenerHusten,
Symptom.Nasenbluten,
Symptom.Heiserkeit,
Symptom.LeichteKopfschmerzen,
// schleim
Symptom.WenigSchleim,
Symptom.KeinSchleim,
Symptom.ZaeherSchleim,
Symptom.BlutInSchleim,
Symptom.RoteZungenspitze,
Symptom.GelberBelag,
Symptom.DuennerBelag,
Symptom.TrockenerBelag,
Symptom.OberflaechlicherPuls,
Symptom.BeschleunigterPuls
)
),
// @LuSchleim generell:
// - MP produziert schleim, Lu lagert ihn
// - ursachen: MP-Qi/Yang-Mangel, Lu-Qi-Mangel
LuSchleimKalt(
label = "Kalte Schleimretention in Lu",
sqlCode = "LuSchleimKalt",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LuSchleim + listOf(
Symptom.WeisserSchleim,
Symptom.TrueberSchleim,
Symptom.Blaesse,
Symptom.Muedigkeit,
Symptom.KaelteGefuehl,
Symptom.WeisserBelag,
Symptom.LangsamerPuls
)
),
LuSchleimHeiss(
label = "Heisse Schleimretention in Lu",
sqlCode = "LuSchleimHeiss",
organ = ZangOrgan.Lung,
tendency = MangelUeberfluss.Ueberfluss,
symptoms = GeneralSymptoms.LuSchleim + listOf(
Symptom.GelberSchleim,
Symptom.Fieber,
Symptom.HitzeZeichen,
Symptom.GelberBelag,
Symptom.BraunerBelag,
Symptom.BeschleunigterPuls
)
),
// NIERE
// =================================================================================================================
NiYinXu(
label = "Nieren Yin Mangel",
sqlCode = "NiYinXu",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.YinXu.symptoms + listOf(
// schmerzen unten
Symptom.SchmerzenLumbalregion,
Symptom.KnieSchmerzen,
Symptom.FersenSchmerzen,
// sex
Symptom.VermehrteLibido,
Symptom.SexuelleTraeme,
Symptom.VerfruehteEjakulation,
Symptom.NaechtlicheEjakulation,
Symptom.MenstruationBeeinflusst,
// ohren
Symptom.Tinnitus,
Symptom.Hoerverlust,
//misc
Symptom.GedaechtnisStoerungen,
Symptom.Schwindel,
// zunge
Symptom.RoterBelag,
Symptom.DuennerBelag,
Symptom.FehlenderBelag,
// puls
Symptom.DuennerPuls,
Symptom.BeschleunigterPuls
)
),
NiYangXu(
label = "Nieren Yang Mangel",
sqlCode = "NiYangXu",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = GeneralSymptoms.YangXu.symptoms + listOf(
Symptom.GedaechtnisStoerungen,
Symptom.Zahnausfall,
Symptom.Oedeme,
// schmerzen unten
Symptom.SchmerzenLumbalregion,
Symptom.KnieSchmerzen,
Symptom.FersenSchmerzen,
// sex
Symptom.VerminderteLibido,
Symptom.Unfruchtbarkeit,
Symptom.Impotenz,
Symptom.Spermatorrhoe,
Symptom.Ausfluss,
// ohren
Symptom.HoervermoegenVermindert,
Symptom.Tinnitus,
// urin
Symptom.KlarerUrin,
Symptom.HellerUrin,
Symptom.ReichlichUrin,
Symptom.WenigUrin,
// MP auch beeinflusst
Symptom.VerdauungAllgemein,
Symptom.BreiigerStuhl,
Symptom.HahnenschreiDiarrhoe,
// zunge
Symptom.BlasseZunge,
Symptom.VergroesserteZunge,
Symptom.DuennerBelag,
Symptom.WeisserBelag,
// puls
Symptom.TieferPuls,
Symptom.SchwacherPuls,
Symptom.VerlangsamterPuls
)
),
NiYangXuUeberfliessenWasser(
label = "Nieren Yang Mangel mit Überfließen des Wassers",
sqlCode = "NiYangXuUeber",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = NiYangXu.symptoms + listOf(
Symptom.Palpitationen, // MINOR hat fix palpitationen! obwohl das eher bei blut-xu vorkommt, vesteh ich nicht
// Lu beeinflusst
Symptom.Husten,
Symptom.Atemnot,
// wasser
Symptom.StarkeOedemeBeine,
Symptom.LungenOedem,
Symptom.Wasserbauch,
// zunge
Symptom.GeschwolleneZunge,
Symptom.DickerBelag,
// puls
Symptom.HaftenderPuls
)
),
NiYangXuFestigkeitXu(
label = "Mangelnde Festigkeit des Nieren Qi",
sqlCode = "NiYangXuFest",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = listOf(// MINOR why not include NiYang symptoms?
// sex
Symptom.Spermatorrhoe,
Symptom.NaechtlicheEjakulation,
Symptom.SexuelleTraeume,
Symptom.VerfruehteEjakulation,
Symptom.Ausfluss,
Symptom.Unfruchtbarkeit,
// urin
Symptom.HaeufigesUrinieren,
Symptom.ReichlichUrin,
Symptom.KlarerUrin,
Symptom.Nachttroepfeln,
Symptom.Harninkontinenz,
// zunge
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
// puls
Symptom.TieferPuls,
Symptom.SchwacherPuls
)
),
NiYangXuQiEinfangen(
label = "Unfähigkeit der Nieren das Qi einzufangen",
sqlCode = "NiYangXuFangen",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = listOf(// MINOR why not include NiYang symptoms?
// Lu
Symptom.Atemnot,
Symptom.Kurzatmigkeit,
Symptom.Asthma,
Symptom.Husten,
Symptom.LeiseSprechen,
Symptom.SchwacheStimme,
Symptom.Infektanfaelligkeit,
// misc
Symptom.KreuzSchmerzen,
Symptom.ReichlichUrin,
Symptom.HellerUrin,
// zunge
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.DuennerBelag,
Symptom.WeisserBelag,
// puls
Symptom.TieferPuls,
Symptom.DuennerPuls,
Symptom.SchwacherPuls,
Symptom.OberflaechlicherPuls,
Symptom.LeererPuls
)
),
NiJingPraenatalXu(
label = "Nieren Jing Mangel (Pränatal)",
sqlCode = "NiJingXuPre",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = listOf(
Symptom.VerzoegerteGeistigeEntwicklung,
Symptom.VerzoegerteKoerperlicheEntwicklung,
Symptom.VerzoegerteKnochenEntwicklung,
Symptom.VeroegertesWachstum,
Symptom.VerzoegerteReifung,
Symptom.GestoerteZahnentwicklung,
Symptom.Hoerstoerung
)
),
NiJingPostnatalXu(
label = "Nieren Jing Mangel (Postnatal)",
sqlCode = "NiJingXuPost",
organ = ZangOrgan.Kidney,
tendency = MangelUeberfluss.Mangel,
symptoms = listOf(
Symptom.VerfruehtesSenium,
// MINOR rename Probleme to Allgemein
Symptom.ProblemeUntererRuecken,
Symptom.ProblemeKnie,
Symptom.ProblemeFussknoechel,
Symptom.ProblemeKnochen,
Symptom.ProblemeZaehne,
Symptom.ProblemeGedaechtnis,
Symptom.ProblemeGehirn,
Symptom.ProblemeOhren,
Symptom.ProblemeHaare
)
)
}
data class GeneralSymptom(
val yy: YinYang,
val substance: Substances? = null,
val symptoms: List<Symptom>
// val mangel = MangelUeberfluss.Mangel
)
object GeneralSymptoms {
val BlutXu = GeneralSymptom(
yy = YinYang.Yin,
substance = Substances.Xue,
symptoms = listOf(
Symptom.FahleBlaesse,
Symptom.Palpitationen,
Symptom.TaubheitsgefuehlExtremitaeten,
// psycho
Symptom.Konzentrationsstoerungen,
Symptom.Schreckhaftigkeit,
Symptom.Schlafstoerungen
)
)
val YinXu = GeneralSymptom(// hat HITZE
yy = YinYang.Yin,
symptoms = BlutXu.symptoms + listOf(
// psycho
Symptom.Unruhe,
Symptom.Nervoesitaet,
// hitze
Symptom.RoteWangenflecken,
Symptom.FuenfZentrenHitze,
Symptom.Nachtschweiss,
Symptom.HitzeGefuehlAbends,
Symptom.TrockenerMund,
Symptom.TrockenerHals,
Symptom.Halsschmerzen, // haeufig, leichte
Symptom.Durst, // mehr? MehrDurstSpaeter?
// verdauung
Symptom.DunklerUrin,
Symptom.KonzentrierterUrin,
Symptom.Verstopfung,
Symptom.Durchfall
))
val QiXu = GeneralSymptom(
yy = YinYang.Yin,
substance = Substances.Qi,
symptoms = listOf(
Symptom.LeuchtendeBlaesse,
Symptom.Muedigkeit,
Symptom.Schwaeche,
Symptom.AnstrengungSchnellErschoepft
))
val YangXu = GeneralSymptom(
// looks cold, feels cold
yy = YinYang.Yin,
symptoms = QiXu.symptoms + listOf(
Symptom.KalteHaende,
Symptom.KalteFuesse,
Symptom.KaelteGefuehl,
Symptom.AversionKaelte,
// MINOR engegefuehl (auch bei NiYangXu?)
// MINOR schmerzen
Symptom.Kontraktionen,
Symptom.Lethargie,
Symptom.Antriebslosigkeit
))
val LeWind = listOf(
Symptom.PloetzlicheBewegungen,
Symptom.UnkoordinierteBewegungen,
Symptom.Zuckungen,
Symptom.Tics,
Symptom.Augenzucken,
Symptom.AllgemeineUnregelmaessigkeiten,
Symptom.OberkoerperStaerkerBetroffen,
Symptom.KopfStaerkerBetroffen,
Symptom.YangLokalisationenStaerkerBetroffen
)
val LuSchleim = listOf(
Symptom.ThorakalesEngegefuehl,
Symptom.VoelleGefuehl,
Symptom.Atemnot,
Symptom.Asthma,
Symptom.Husten,
Symptom.VielSchleim,
Symptom.RasselndeKehle,
Symptom.WenigAppetit,
Symptom.Breichreiz,
Symptom.DickerBelag,
Symptom.FeuchterBelag,
Symptom.SchmierigerBelag,
Symptom.SchluepfrigerPuls,
Symptom.OberflaechlicherPuls
)
val LuWindKaelte = listOf(
Symptom.NormaleZunge,
Symptom.WeisserBelag,
Symptom.VermehrterBelag,
Symptom.DuennerBelag,
Symptom.OberflaechlicherPuls,
Symptom.GespannterPuls,
Symptom.VerlangsamterPuls
)
val HeYangXuPulsTongue = listOf(
Symptom.VersteckterPuls,
Symptom.SchwacherPuls,
Symptom.UnregelmaessigerPuls,
Symptom.RauherPuls,
Symptom.BlaeulicheZunge,
Symptom.GeschwolleneZunge,
Symptom.GestauteUnterzungenvenen // stark geschwollen
)
}
object SpecificSymptoms {
val HeBlutXu = listOf(
Symptom.Schwindel,
Symptom.Aengstlichkeit,
Symptom.VieleTraeume,
Symptom.SchlechteMerkfaehigkeit,
Symptom.BlasseZunge,
Symptom.DuennerPuls
)
val HeQiXu = listOf(
Symptom.Palpitationen,
Symptom.Kurzatmigkeit,
Symptom.StarkesSchwitzen, // va am tag
Symptom.MentaleMuedigkeit,
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.LaengsrissInZunge,
Symptom.SchwacherPuls,
Symptom.LeererPuls,
Symptom.UnregelmaessigerPuls
)
val MPQiXu = listOf(
Symptom.WenigAppetit,
Symptom.VoelleGefuehl,
Symptom.Blaehungen,
Symptom.Aufstossen,
Symptom.LeichteSchmerzenOberbauch,
Symptom.BreiigerStuhl,
Symptom.EnergieMangel,
Symptom.Ausgezehrt,
Symptom.KraftloseMuskeln,
Symptom.OedemeBauch,
Symptom.Zwischenblutung,
Symptom.KurzeMensZyklen,
Symptom.HelleBlutung,
Symptom.ReichlichBlutung,
Symptom.BlasseZunge,
Symptom.GeschwolleneZunge,
Symptom.Zahneindruecke,
Symptom.DuennerBelag,
Symptom.WeisserBelag,
Symptom.SchwacherPuls,
Symptom.WeicherPuls,
Symptom.LeererPuls
)
}
| apache-2.0 |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/quests/QuestDetailViewModel.kt | 1 | 2135 | package com.ghstudios.android.features.quests
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import android.util.Log
import com.ghstudios.android.data.classes.*
import com.ghstudios.android.data.DataManager
import com.ghstudios.android.util.loggedThread
import com.ghstudios.android.util.toList
/**
* A ViewModel for the entirety of quest detail data.
* This should be attached to the activity or fragment owning the viewpager.
*/
class QuestDetailViewModel(app : Application) : AndroidViewModel(app) {
private val dataManager = DataManager.get()
val rewards = MutableLiveData<List<QuestReward>>()
val monsters = MutableLiveData<List<MonsterToQuest>>()
val quest = MutableLiveData<Quest>()
val gatherings = MutableLiveData<List<Gathering>>()
val huntingRewards = MutableLiveData<List<HuntingReward>>()
fun setQuest(questId: Long): Quest? {
if (questId == quest.value?.id) {
return quest.value!!
}
val quest = dataManager.getQuest(questId)
this.quest.value = quest
if (quest == null) {
Log.e(this.javaClass.simpleName, "Quest id is unexpectedly null")
return null
}
loggedThread("Quest Load") {
monsters.postValue(dataManager.queryMonsterToQuestQuest(questId).toList { it.monsterToQuest })
rewards.postValue(dataManager.queryQuestRewardQuest(questId).toList { it.questReward })
if (quest.hasGatheringItem) {
val locationId = quest.location?.id ?: -1
val gatherData = dataManager.queryGatheringForQuest(quest.id, locationId, quest.rank ?: "").toList {
it.gathering
}
gatherings.postValue(gatherData)
}else if(quest.hasHuntingRewardItem){
val rewardData = dataManager.queryHuntingRewardForQuest(quest.id,quest.rank?:"").toList {
it.huntingReward
}
huntingRewards.postValue(rewardData)
}
}
return quest
}
} | mit |
eugeis/ee | ee-lang/src/main/kotlin/ee/lang/gen/ts/TsCommon.kt | 1 | 14546 | package ee.lang.gen.ts
import ee.common.ext.*
import ee.design.EntityI
import ee.lang.*
import ee.lang.gen.java.j
import javax.swing.text.html.parser.Entity
fun <T : TypeI<*>> T.toTypeScriptDefault(c: GenerationContext, derived: String, attr: AttributeI<*>): String {
val baseType = findDerivedOrThis()
return when (baseType) {
n.String, n.Text -> "''"
n.Boolean -> "false"
n.Int -> "0"
n.Long -> "0L"
n.Float -> "0f"
n.Date -> "${c.n(j.util.Date)}()"
n.Path -> "${c.n(j.nio.file.Paths)}.get('')"
n.Blob -> "new ByteArray(0)"
n.Void -> ""
n.Error -> "new Throwable()"
n.Exception -> "new Exception()"
n.Url -> "${c.n(j.net.URL)}('')"
n.Map -> (attr.isNotEMPTY() && attr.isMutable().setAndTrue()).ifElse("new Map()", "new Map()")
n.List -> (attr.isNotEMPTY() && attr.isMutable().setAndTrue()).ifElse("new Array()", "new Array()")
else -> {
if (baseType is LiteralI<*>) {
"${(baseType.findParent(EnumTypeI::class.java) as EnumTypeI<*>).toTypeScript(c, derived,
attr)}.${baseType.toTypeScript()}"
} else if (baseType is EnumTypeI<*>) {
"${c.n(this, derived)}.${baseType.literals().first().toTypeScript()}"
} else if (baseType is CompilationUnitI<*>) {
"new ${c.n(this, derived)}()"
} else {
(this.parent() == n).ifElse("''", { "${c.n(this, derived)}.EMPTY" })
}
}
}
}
fun <T : AttributeI<*>> T.toTypeScriptDefault(c: GenerationContext, derived: String): String =
type().toTypeScriptDefault(c, derived, this)
fun <T : ItemI<*>> T.toTypeScriptEMPTY(c: GenerationContext, derived: String): String =
(this.parent() == n).ifElse("''", { "${c.n(this, derived)}.EMPTY" })
fun <T : AttributeI<*>> T.toTypeScriptEMPTY(c: GenerationContext, derived: String): String =
type().toTypeScriptEMPTY(c, derived)
fun <T : AttributeI<*>> T.toTypeScriptTypeSingle(c: GenerationContext, api: String): String =
type().toTypeScript(c, api, this)
fun <T : AttributeI<*>> T.toTypeScriptTypeDef(c: GenerationContext, api: String): String =
"""${type().toTypeScript(c, api, this)}${isNullable().then("?")}"""
fun <T : AttributeI<*>> T.toTypeScriptCompanionObjectName(c: GenerationContext): String =
""" val ${name().toUnderscoredUpperCase()} = "_${name()}""""
fun <T : CompilationUnitI<*>> T.toTypeScriptExtends(c: GenerationContext, derived: String, api: String): String {
if (superUnit().isNotEMPTY() && derived != api) {
return " extends ${c.n(superUnit(), derived)}, ${c.n(this, api)}"
} else if (superUnit().isNotEMPTY()) {
return " extends ${c.n(superUnit(), derived)}"
} else if (derived != api) {
return " extends ${c.n(this, api)}"
} else {
return ""
}
}
fun <T : TypeI<*>> T.toTypeScriptIfNative(c: GenerationContext, derived: String, attr: AttributeI<*>): String? {
val baseType = findDerivedOrThis()
return when (baseType) {
n.Any -> "any"
n.String -> "string"
n.Boolean -> "boolean"
n.Int -> "number"
n.Long -> "number"
n.Float -> "number"
n.Date -> "Date"
n.TimeUnit -> "string"
n.Path -> "string"
n.Text -> "string"
n.Blob -> "Blob"
n.Exception -> "Error"
n.Error -> "Error"
n.Void -> "void"
n.Url -> "string"
n.UUID -> "string"
n.List -> "Array${toTypeScriptGenericTypes(c, derived, attr)}"
n.Map -> "Map${toTypeScriptGenericTypes(c, derived, attr)}"
else -> {
if (this is LambdaI<*>) operation().toTypeScriptLambda(c, derived) else null
}
}
}
fun TypeI<*>.toTypeScriptGenericTypes(c: GenerationContext, derived: String, attr: AttributeI<*>): String =
generics().joinWrappedToString(", ", "", "<", ">") { it.type().toTypeScript(c, derived, attr) }
fun GenericI<*>.toTypeScript(c: GenerationContext, derived: String): String = c.n(type(), derived)
fun TypeI<*>.toTypeScriptGenerics(c: GenerationContext, derived: String, attr: AttributeI<*>): String =
generics().joinWrappedToString(", ", "", "<", ">") { it.toTypeScript(c, derived, attr) }
fun TypeI<*>.toTypeScriptGenericsClassDef(c: GenerationContext, derived: String, attr: AttributeI<*>): String =
generics().joinWrappedToString(", ", "", "<", ">") {
"${it.name()} : ${it.type().toTypeScript(c, derived, attr)}"
}
fun TypeI<*>.toTypeScriptGenericsMethodDef(c: GenerationContext, derived: String, attr: AttributeI<*>): String =
generics().joinWrappedToString(", ", "", "<", "> ") {
"${it.name()} : ${it.type().toTypeScript(c, derived, attr)}"
}
fun TypeI<*>.toTypeScriptGenericsStar(context: GenerationContext, derived: String): String =
generics().joinWrappedToString(", ", "", "<", "> ") { "*" }
fun OperationI<*>.toTypeScriptGenerics(c: GenerationContext, derived: String): String =
generics().joinWrappedToString(", ", "", "<", "> ") {
"${it.name()} : ${it.type().toTypeScript(c, derived)}"
}
fun <T : TypeI<*>> T.toTypeScript(c: GenerationContext, derived: String,
attr: AttributeI<*> = Attribute.EMPTY): String =
toTypeScriptIfNative(c, derived, attr) ?: "${c.n(this, derived)}${this.toTypeScriptGenericTypes(c, derived, attr)}"
fun <T : AttributeI<*>> T.toTypeScriptValue(c: GenerationContext, derived: String): String {
if (value() != null) {
return when (type()) {
n.String, n.Text -> "\"${value()}\""
n.Boolean, n.Int, n.Long, n.Float, n.Date, n.Path, n.Blob, n.Void -> "${value()}"
else -> {
if (value() is LiteralI<*>) {
val lit = value() as LiteralI<*>
"${(lit.parent() as EnumTypeI<*>).toTypeScript(c, derived, this)}.${lit.toTypeScript()}"
} else {
"${value()}"
}
}
}
} else {
return toTypeScriptDefault(c, derived)
}
}
fun <T : AttributeI<*>> T.toTypeScriptInit(c: GenerationContext, derived: String): String {
if (value() != null) {
return " = ${toTypeScriptValue(c, derived)}"
} else if (isNullable()) {
return " = null"
} else if (isInitByDefaultTypeValue()) {
return " = ${toTypeScriptValue(c, derived)}"
} else {
return ""
}
}
fun <T : AttributeI<*>> T.toTypeScriptInitMember(c: GenerationContext, derived: String): String =
"this.${name()}${toTypeScriptInit(c, derived)}"
fun <T : AttributeI<*>> T.toTypeScriptSignature(c: GenerationContext, derived: String, api: String,
init: Boolean = true): String =
"${name()}: ${toTypeScriptTypeDef(c, api)}${init.then { toTypeScriptInit(c, derived) }}"
fun <T : AttributeI<*>> T.toTypeScriptConstructorMember(c: GenerationContext, derived: String, api: String,
init: Boolean = true): String =
//"${isReplaceable().setAndTrue().ifElse("", "readonly ")}${toTypeScriptSignature(c, derived, api, init)}"
"${toTypeScriptSignature(c, derived, api, init)}"
fun <T : AttributeI<*>> T.toTypeScriptMember(c: GenerationContext, derived: String, api: String,
init: Boolean = true, indent: String): String =
//" ${isReplaceable().setAndTrue().ifElse("", "readonly ")}${toTypeScriptSignature(c, derived, api, init)}"
"${indent}${toTypeScriptSignature(c, derived, api, init)}"
fun List<AttributeI<*>>.toTypeScriptSignature(c: GenerationContext, derived: String, api: String): String =
joinWrappedToString(", ") { it.toTypeScriptSignature(c, derived, api) }
fun List<AttributeI<*>>.toTypeScriptMember(c: GenerationContext, derived: String, api: String): String =
joinWrappedToString(", ") { it.toTypeScriptSignature(c, derived, api) }
fun <T : ConstructorI<*>> T.toTypeScriptPrimary(c: GenerationContext, derived: String, api: String): String {
return if (isNotEMPTY()) """(${params().joinWrappedToString(", ", " ") {
it.toTypeScriptConstructorMember(c, derived, api)
}})${superUnit().toTypeScriptCall(c)}""" else ""
}
fun <T : ConstructorI<*>> T.toTypeScript(c: GenerationContext, derived: String, api: String): String {
return if (isNotEMPTY()) """
constructor(${params().joinWrappedToString(", ", " ") {
it.toTypeScriptSignature(c, derived, api)
}}) {${superUnit().isNotEMPTY().then {
(superUnit() as ConstructorI<*>).toTypeScriptCall(c, (parent() != superUnit().parent()).ifElse("super", "this"))
}} ${paramsWithOut(superUnit()).joinSurroundIfNotEmptyToString("${nL} ", prefix = "{${nL} ") {
it.toTypeScriptAssign(c)
}}${(parent() as CompilationUnitI<*>).props().filter { it.isMeta() }.joinSurroundIfNotEmptyToString("${nL} ",
prefix = "${nL} ") {
it.toTypeScriptInitMember(c, derived)
}}
}""" else ""
}
fun <T : ConstructorI<*>> T.toTypeScriptCall(c: GenerationContext, name: String = "this"): String =
isNotEMPTY().then { " : $name(${params().joinWrappedToString(", ") { it.name() }})" }
fun <T : AttributeI<*>> T.toTypeScriptAssign(c: GenerationContext): String = "this.${name()} = ${name()}"
fun <T : LogicUnitI<*>> T.toTypeScriptCall(c: GenerationContext): String =
isNotEMPTY().then { "(${params().joinWrappedToString(", ") { it.name() }})" }
fun <T : LogicUnitI<*>> T.toTypeScriptCallValue(c: GenerationContext, derived: String): String =
isNotEMPTY().then { "(${params().joinWrappedToString(", ") { it.toTypeScriptValue(c, derived) }})" }
fun <T : LiteralI<*>> T.toTypeScriptCallValue(c: GenerationContext, derived: String): String =
params().isNotEmpty().then { "(${params().joinWrappedToString(", ") { it.toTypeScriptValue(c, derived) }})" }
fun <T : AttributeI<*>> T.toTypeScriptType(c: GenerationContext, derived: String): String =
type().toTypeScript(c, derived, this)
fun List<AttributeI<*>>.toTypeScriptTypes(c: GenerationContext, derived: String): String =
joinWrappedToString(", ") { it.toTypeScriptType(c, derived) }
fun <T : OperationI<*>> T.toTypeScriptLambda(c: GenerationContext, derived: String): String =
"""(${params().toTypeScriptTypes(c, derived)}) -> ${retFirst().toTypeScriptType(c, derived)}"""
fun <T : OperationI<*>> T.toTypeScriptImpl(c: GenerationContext, derived: String, api: String): String {
return """
${toTypeScriptGenerics(c, derived)}${name()}(${params().toTypeScriptSignature(c, derived,
api)}): ${retFirst().toTypeScriptTypeDef(c, api)} {
throw new ReferenceError('Not implemented yet.');
}"""
}
fun <T : ItemI<*>> T.toAngularBasicGenerateComponentPart(c: GenerationContext): String =
"""@${c.n("Component")}({
selector: 'app-${this.name().toLowerCase()}',
templateUrl: './${this.name().toLowerCase()}-basic.component.html',
styleUrls: ['./${this.name().toLowerCase()}-basic.component.scss'],
})
"""
fun <T : ItemI<*>> T.toAngularListOnInit(indent: String): String {
return """${indent}ngOnInit(): void {
this.tableHeader = this.generateTableHeader();
this.${this.name().toLowerCase()}DataService.checkSearchRoute();
if (this.${this.name().toLowerCase()}DataService.isSearch) {
this.${this.name().toLowerCase()}DataService.loadSearchData()
} else {
this.${this.name().toLowerCase()}DataService.dataSources =
new MatTableDataSource(this.${this.name().toLowerCase()}DataService.changeMapToArray(
this.${this.name().toLowerCase()}DataService.retrieveItemsFromCache()));
}
}"""
}
/*when (this.type().props().size) {
0 -> """'${this.name().toCamelCase()}'"""
else -> {
this.type().props().filter { !it.isMeta() }.joinSurroundIfNotEmptyToString(", ") {
it.toTypeScriptTypeProperty(c, this)
}
}
}*/
fun <T : AttributeI<*>> T.toAngularGenerateTableHeader(c: GenerationContext): String {
return when (this.type()) {
is EntityI<*>, is ValuesI<*> -> """'${this.name().toLowerCase()}-entity'"""
else -> {
when (this.type().toTypeScriptIfNative(c, "", this)) {
"boolean", "string", "number", "Date" -> """'${this.name().toCamelCase()}'"""
else -> {
when (this.type().props().size) {
0 -> """'${this.name().toCamelCase()}'"""
else -> {
this.type().props().filter { !it.isMeta() }.joinSurroundIfNotEmptyToString(", ") {
it.toTypeScriptTypeProperty(c, this)
}
}
}
}
}
}
}
}
fun <T : AttributeI<*>> T.toTypeScriptTypeProperty(c: GenerationContext, elementParent: AttributeI<*>): String {
return when (this.type()) {
is EntityI<*>, is ValuesI<*> -> """'${this.name().toLowerCase()}-entity'"""
else -> {
when (this.type().props().size) {
0 -> """'${this.name().toCamelCase()}'"""
else -> {
this.type().props().filter { !it.isMeta() }.joinSurroundIfNotEmptyToString(", ") {
it.toTypeScriptTypeProperty(c, elementParent)
}
}
}
}
}
}
fun <T : AttributeI<*>> T.toTypeScriptInitEmptyProps(c: GenerationContext): String {
return when (this.type().toTypeScriptIfNative(c, "", this)) {
"boolean", "string", "number", "Date" -> ""
else -> {
when (this.type().props().size) {
0 -> ""
else -> {
"""
if (this.${this.parent().name().toLowerCase()}.${this.name().toCamelCase()} === undefined) {
this.${this.parent().name().toLowerCase()}.${this.name().toCamelCase()} = new ${c.n(this.type()).capitalize()}();
}"""
}
}
}
}
}
| apache-2.0 |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/renderer/JsonAdapterFactoryRenderer.kt | 1 | 9094 | package se.ansman.kotshi.renderer
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.moshi.JsonAdapter
import se.ansman.kotshi.*
import se.ansman.kotshi.model.GeneratedAnnotation
import se.ansman.kotshi.model.JsonAdapterFactory
import se.ansman.kotshi.model.render
internal class JsonAdapterFactoryRenderer(
private val factory: JsonAdapterFactory,
private val createAnnotationsUsingConstructor: Boolean
) {
private val nameAllocator = NameAllocator()
fun render(generatedAnnotation: GeneratedAnnotation?, typeSpecModifier: TypeSpec.Builder.() -> Unit): FileSpec {
val annotations = mutableSetOf<AnnotationSpec>()
val properties = mutableSetOf<PropertySpec>()
val createFunction = makeCreateFunction(
typeParam = ParameterSpec(nameAllocator.newName("type"), Types.Java.type),
annotationsParam = ParameterSpec(
nameAllocator.newName("annotations"),
Types.Kotlin.set.parameterizedBy(Types.Kotlin.annotation)
),
moshiParam = ParameterSpec(nameAllocator.newName("moshi"), Types.Moshi.moshi),
annotations = annotations,
properties = properties,
)
return FileSpec.builder(factory.factoryClassName.packageName, factory.factoryClassName.simpleName)
.addFileComment("Code generated by Kotshi. Do not edit.")
.addAnnotation(
AnnotationSpec.builder(Types.Kotlin.suppress)
.addMember("%S", "EXPERIMENTAL_IS_NOT_ENABLED")
.addMember("%S", "REDUNDANT_PROJECTION")
.build()
)
.addType(
TypeSpec.objectBuilder(factory.factoryClassName)
.addModifiers(KModifier.INTERNAL)
.apply { generatedAnnotation?.toAnnotationSpec()?.let(::addAnnotation) }
.apply {
when (factory.usageType) {
JsonAdapterFactory.UsageType.Standalone -> addSuperinterface(Types.Moshi.jsonAdapterFactory)
is JsonAdapterFactory.UsageType.Subclass -> {
if (factory.usageType.parentIsInterface) {
addSuperinterface(factory.usageType.parent)
} else {
superclass(factory.usageType.parent)
}
}
}
}
.addAnnotations(annotations)
.addProperties(properties)
.addFunction(createFunction)
.apply(typeSpecModifier)
.addAnnotation(
AnnotationSpec.builder(Types.Kotlin.optIn)
.addMember("%T::class", Types.Kotshi.internalKotshiApi)
.build()
)
.build()
)
.build()
}
private fun makeCreateFunction(
typeParam: ParameterSpec,
annotationsParam: ParameterSpec,
moshiParam: ParameterSpec,
annotations: MutableSet<AnnotationSpec>,
properties: MutableSet<PropertySpec>,
): FunSpec {
val createSpec = FunSpec.builder("create")
.addModifiers(KModifier.OVERRIDE)
.returns(JsonAdapter::class.asClassName().parameterizedBy(STAR).nullable())
.addParameter(typeParam)
.addParameter(annotationsParam)
.addParameter(moshiParam)
if (factory.isEmpty) {
return createSpec
.addStatement("return null")
.build()
}
val rawType = PropertySpec.builder(nameAllocator.newName("rawType"), Types.Java.clazz.parameterizedBy(STAR))
.initializer("%M(%N)", Functions.Moshi.getRawType, typeParam)
.build()
return createSpec
.addCode("%L", rawType)
.applyIf(factory.manuallyRegisteredAdapters.isNotEmpty()) {
addRegisteredAdapters(typeParam, annotationsParam, moshiParam, rawType, annotations, properties)
}
.addGeneratedAdapters(typeParam, annotationsParam, moshiParam, rawType)
.build()
}
private fun FunSpec.Builder.addRegisteredAdapters(
typeParam: ParameterSpec,
annotationsParam: ParameterSpec,
moshiParam: ParameterSpec,
rawType: PropertySpec,
annotations: MutableSet<AnnotationSpec>,
properties: MutableSet<PropertySpec>,
): FunSpec.Builder = addControlFlow("when") {
for (adapter in factory.manuallyRegisteredAdapters.sorted()) {
addCode("%N·==·%T::class.java", rawType, adapter.targetType.rawType())
if (adapter.qualifiers.isNotEmpty()) {
val qualifiers = PropertySpec
.builder(
nameAllocator.newName(adapter.adapterClassName.simpleName.replaceFirstChar(Char::lowercaseChar) + "Qualifiers"),
Set::class.parameterizedBy(Annotation::class)
)
.addModifiers(KModifier.PRIVATE)
.initializer(CodeBlock.Builder()
.add("%M(⇥", Functions.Kotlin.setOf)
.applyEachIndexed(adapter.qualifiers) { i, qualifier ->
if (i > 0) add(",")
add("\n")
add(qualifier.render(createAnnotationsUsingConstructor))
}
.add("⇤\n)")
.build())
.build()
.also(properties::add)
addCode("·&&·\n⇥%N == %N⇤", annotationsParam, qualifiers)
}
if (adapter.requiresDeepTypeCheck) {
addCode(
"·&&·\n⇥%M(%M<%T>().%M, %N)⇤",
Functions.Kotshi.matches,
Functions.Kotlin.typeOf,
adapter.targetType.unwrapTypeVariables(),
Functions.Kotlin.javaType,
typeParam
)
annotations.add(AnnotationSpec.builder(Types.Kotlin.experimentalStdlibApi).build())
}
addCode("·->« return·")
val constructor = adapter.constructor
if (constructor == null) {
addCode("%T", adapter.adapterTypeName)
} else {
addAdapterConstructorCall(
adapterTypeName = adapter.adapterTypeName,
constructor = adapter.constructor,
moshiParam = moshiParam,
typeParam = typeParam,
)
}
addCode("»\n")
}
}
private fun FunSpec.Builder.addGeneratedAdapters(
typeParam: ParameterSpec,
annotationsParam: ParameterSpec,
moshiParam: ParameterSpec,
rawType: PropertySpec,
): FunSpec.Builder =
if (factory.generatedAdapters.isEmpty()) {
addCode("return·null")
} else {
addStatement("if·(%N.isNotEmpty()) return·null", annotationsParam)
.addCode("\n")
.addControlFlow("return·when·(%N)", rawType) {
for (adapter in factory.generatedAdapters.sorted()) {
addCode("%T::class.java·->«\n", adapter.adapter.targetType.rawType())
addAdapterConstructorCall(
adapterTypeName = adapter.adapter.adapterTypeName,
constructor = adapter.constructor,
moshiParam = moshiParam,
typeParam = typeParam,
)
addCode("»\n")
}
addStatement("else -> null")
}
}
private fun FunSpec.Builder.addAdapterConstructorCall(
adapterTypeName: TypeName,
constructor: KotshiConstructor,
moshiParam: ParameterSpec,
typeParam: ParameterSpec,
): FunSpec.Builder = apply {
addCode("%T(", adapterTypeName.mapTypeArguments { NOTHING })
if (constructor.hasParameters) {
addCode("⇥")
}
if (constructor.moshiParameterName != null) {
addCode("\n%N = %N", constructor.moshiParameterName, moshiParam)
}
if (constructor.typesParameterName != null) {
if (constructor.moshiParameterName != null) {
addCode(",")
}
addCode(
"\n%N = %N.%M",
constructor.typesParameterName,
typeParam,
Functions.Kotshi.typeArgumentsOrFail
)
}
if (constructor.hasParameters) {
addCode("⇤\n")
}
addCode(")")
}
} | apache-2.0 |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/connection/builder/lookup/LookupServers.kt | 2 | 312 | package com.lasthopesoftware.bluewater.client.connection.builder.lookup
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.namehillsoftware.handoff.promises.Promise
interface LookupServers {
fun promiseServerInformation(libraryId: LibraryId): Promise<ServerInfo?>
}
| lgpl-3.0 |
kotlintest/kotlintest | kotest-samples/kotest-samples-gradle/src/test/kotlin/io/kotlintest/samples/gradle/DescribeSpecExampleTest.kt | 1 | 1382 | package io.kotest.samples.gradle
import io.kotest.specs.DescribeSpec
class DescribeSpecExampleTest : DescribeSpec() {
init {
describe("some thing") {
it("test name") {
// test here
}
context("with some context") {
it("test name") {
// test here
}
it("test name 2").config(enabled = false) {
// test here
}
context("with some context") {
it("test name") {
// test here
}
it("test name 2").config(enabled = false) {
// test here
}
}
}
}
describe("some other thing") {
context("with some context") {
it("test name") {
// test here
}
it("test name 2").config(enabled = false) {
// test here
}
context("with some context") {
it("test name") {
// test here
}
it("test name 2").config(enabled = false) {
// test here
}
}
}
}
}
}
| apache-2.0 |
DUCodeWars/TournamentFramework | src/main/java/org/DUCodeWars/framework/server/net/packets/notifications/broadcast/BroadcastNotificationDisqualify.kt | 2 | 1152 | package org.DUCodeWars.framework.server.net.packets.notifications.broadcast
import org.DUCodeWars.framework.server.AbstractGame
import org.DUCodeWars.framework.server.net.PlayerConnection
import org.DUCodeWars.framework.server.net.packets.notifications.InvalidResponseException
import org.DUCodeWars.framework.server.net.packets.notifications.NotificationRequest
import org.DUCodeWars.framework.server.net.packets.notifications.NotificationResponse
class BroadcastNotificationDisqualify<I : NotificationRequest>(
game: AbstractGame,
connections: Iterable<PlayerConnection> = game.players,
requestCreator: (PlayerConnection) -> I)
: BroadcastDisqualify<I, NotificationResponse>(
game,
connections,
requestCreator,
{ _, _, _ ->}
) {
constructor(game: AbstractGame, connections: Iterable<PlayerConnection> = game.players, request: I) : this(game,
connections,
{ request })
} | mit |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/data/feed/FeedRepository.kt | 1 | 2591 | package mil.nga.giat.mage.data.feed
import android.content.Context
import androidx.annotation.WorkerThread
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import mil.nga.giat.mage.network.Resource
import mil.nga.giat.mage.network.api.FeedService
import mil.nga.giat.mage.network.gson.asLongOrNull
import mil.nga.giat.mage.network.gson.asStringOrNull
import mil.nga.giat.mage.sdk.datastore.user.EventHelper
import mil.nga.giat.mage.sdk.utils.ISO8601DateFormatFactory
import java.text.ParseException
import java.util.*
import javax.inject.Inject
class FeedRepository @Inject constructor(
@ApplicationContext private val context: Context,
private val feedLocalDao: FeedLocalDao,
private val feedItemDao: FeedItemDao,
private val feedService: FeedService
) {
suspend fun syncFeed(feed: Feed) = withContext(Dispatchers.IO) {
val resource = try {
val event = EventHelper.getInstance(context).currentEvent
val response = feedService.getFeedItems(event.remoteId, feed.id)
if (response.isSuccessful) {
val content = response.body()!!
saveFeed(feed, content)
Resource.success(content)
} else {
Resource.error(response.message(), null)
}
} catch (e: Exception) {
Resource.error(e.localizedMessage ?: e.toString(), null)
}
val local = FeedLocal(feed.id)
local.lastSync = Date().time
feedLocalDao.upsert(local)
resource
}
@WorkerThread
private fun saveFeed(feed: Feed, content: FeedContent) {
if (!feed.itemsHaveIdentity) {
feedItemDao.removeFeedItems(feed.id)
}
for (item in content.items) {
item.feedId = feed.id
item.timestamp = null
if (feed.itemTemporalProperty != null) {
val temporalElement = item.properties?.asJsonObject?.get(feed.itemTemporalProperty)
item.timestamp = temporalElement?.asLongOrNull() ?: run {
temporalElement?.asStringOrNull()?.let { date ->
try {
ISO8601DateFormatFactory.ISO8601().parse(date)?.time
} catch (ignore: ParseException) { null }
}
}
}
feedItemDao.upsert(item)
}
val itemIds = content.items.map { it.id }
feedItemDao.preserveFeedItems(feed.id, itemIds)
}
} | apache-2.0 |
siempredelao/Distance-From-Me-Android | app/src/main/java/gc/david/dfm/dagger/RootComponent.kt | 1 | 892 | /*
* Copyright (c) 2019 David Aguiar Gonzalez
*
* 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 gc.david.dfm.dagger
import dagger.Component
import gc.david.dfm.DFMApplication
import javax.inject.Singleton
/**
* Created by david on 06.12.16.
*/
@Singleton
@Component(modules = [RootModule::class])
interface RootComponent {
fun inject(application: DFMApplication)
}
| apache-2.0 |
abdoyassen/OnlyU | NoteApp/StartUp/app/src/main/java/com/example/onlyu/startup/AddNotes.kt | 1 | 1731 | package com.example.onlyu.startup
import android.content.ContentValues
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.example.onlyu.R
import kotlinx.android.synthetic.main.activity_add_notes.*
class AddNotes : AppCompatActivity() {
val dbTable="Notes"
var id=0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_notes)
try{
var bundle:Bundle=intent.extras
id=bundle.getInt("ID",0)
if(id!=0) {
etTitle.setText(bundle.getString("name") )
etDes.setText(bundle.getString("des") )
}
}catch (ex:Exception){}
}
fun buAdd(view:View){
var dbManager=DbManager(this)
var values= ContentValues()
values.put("Title",etTitle.text.toString())
values.put("Description",etDes.text.toString())
if(id==0) {
val ID = dbManager.Insert(values)
if (ID > 0) {
Toast.makeText(this, " note is added", Toast.LENGTH_LONG).show()
finish()
} else {
Toast.makeText(this, " cannot add note ", Toast.LENGTH_LONG).show()
}
}else{
var selectionArs= arrayOf(id.toString())
val ID = dbManager.Update(values,"ID=?",selectionArs)
if (ID > 0) {
Toast.makeText(this, " note is added", Toast.LENGTH_LONG).show()
finish()
} else {
Toast.makeText(this, " cannot add note ", Toast.LENGTH_LONG).show()
}
}
}
}
| mit |
f-droid/fdroidclient | libs/sharedTest/src/main/kotlin/org/fdroid/test/DiffUtils.kt | 1 | 2940 | package org.fdroid.test
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import org.fdroid.index.v2.MetadataV2
import org.fdroid.index.v2.PackageVersionV2
import org.fdroid.index.v2.RepoV2
import kotlin.random.Random
object DiffUtils {
/**
* Create a map diff by adding or removing keys. Note that this does not change keys.
*/
fun <T> Map<String, T?>.randomDiff(factory: () -> T): Map<String, T?> = buildMap {
if ([email protected]()) {
// remove random keys
while (Random.nextBoolean()) put([email protected](), null)
// Note: we don't replace random keys, because we can't easily diff inside T
}
// add random keys
while (Random.nextBoolean()) put(TestUtils.getRandomString(), factory())
}
/**
* Removes keys from a JSON object representing a [RepoV2] which need special handling.
*/
fun JsonObject.cleanRepo(): JsonObject {
val keysToFilter = listOf("mirrors", "antiFeatures", "categories", "releaseChannels")
val newMap = filterKeys { it !in keysToFilter }
return JsonObject(newMap)
}
fun RepoV2.clean() = copy(
mirrors = emptyList(),
antiFeatures = emptyMap(),
categories = emptyMap(),
releaseChannels = emptyMap(),
)
/**
* Removes keys from a JSON object representing a [MetadataV2] which need special handling.
*/
fun JsonObject.cleanMetadata(): JsonObject {
val keysToFilter = listOf("icon", "featureGraphic", "promoGraphic", "tvBanner",
"screenshots")
val newMap = filterKeys { it !in keysToFilter }
return JsonObject(newMap)
}
fun MetadataV2.clean() = copy(
icon = null,
featureGraphic = null,
promoGraphic = null,
tvBanner = null,
screenshots = null,
)
/**
* Removes keys from a JSON object representing a [PackageVersionV2] which need special handling.
*/
fun JsonObject.cleanVersion(): JsonObject {
if (!containsKey("manifest")) return this
val keysToFilter = listOf("features", "usesPermission", "usesPermissionSdk23")
val newMap = toMutableMap()
val filteredManifest = newMap["manifest"]!!.jsonObject.filterKeys { it !in keysToFilter }
newMap["manifest"] = JsonObject(filteredManifest)
return JsonObject(newMap)
}
fun PackageVersionV2.clean() = copy(
manifest = manifest.copy(
features = emptyList(),
usesPermission = emptyList(),
usesPermissionSdk23 = emptyList(),
),
)
fun <T> Map<String, T>.applyDiff(diff: Map<String, T?>): Map<String, T> =
toMutableMap().apply {
diff.entries.forEach { (key, value) ->
if (value == null) remove(key)
else set(key, value)
}
}
}
| gpl-3.0 |
wireapp/wire-android | storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/property/KeyValueDaoTest.kt | 1 | 2653 | package com.waz.zclient.storage.userdatabase.property
import androidx.room.Room
import com.waz.zclient.framework.data.property.KeyValueTestDataProvider
import com.waz.zclient.storage.IntegrationTest
import com.waz.zclient.storage.db.UserDatabase
import com.waz.zclient.storage.db.property.KeyValuesDao
import com.waz.zclient.storage.db.property.KeyValuesEntity
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.*
class KeyValueDaoTest : IntegrationTest() {
private lateinit var keyValueDao: KeyValuesDao
private lateinit var userDatabase: UserDatabase
@Before
fun setup() {
userDatabase = Room.inMemoryDatabaseBuilder(
getApplicationContext(),
UserDatabase::class.java
).build()
keyValueDao = userDatabase.keyValuesDao()
}
@After
fun tearDown() {
userDatabase.close()
}
@Test
fun givenAListOfEntries_whenAllKeyValuesIsCalled_thenAssertDataIsTheSameAsInserted(): Unit = runBlocking {
val numberOfItems = 3
val data = KeyValueTestDataProvider.listOfData(numberOfItems)
data.forEach {
keyValueDao.insert(KeyValuesEntity(UUID.randomUUID().toString(), it.value))
}
val storedMessages = keyValueDao.allKeyValues()
assertEquals(storedMessages.first().value, data.first().value)
assertEquals(storedMessages.last().value, data.last().value)
assertEquals(storedMessages.size, numberOfItems)
}
@Test
fun givenAListOfEntries_whenGetBatchIsCalledAndOffsetIs0_thenAssert5ItemIsCollectedAndSizeIs5(): Unit = runBlocking {
insertRandomItems(10)
val storedValues = keyValueDao.nextBatch(0, 5)
assertEquals(storedValues?.size, 5)
assertEquals(keyValueDao.count(), 10)
}
@Test
fun givenAListOfEntries_whenGetBatchIsCalledAndOffsetIs5_thenAssert5ItemIsCollectedAndSizeIs10(): Unit = runBlocking {
insertRandomItems(10)
val storedValues = keyValueDao.nextBatch(5, 5)
assertEquals(storedValues?.size, 5)
assertEquals(keyValueDao.count(), 10)
}
private suspend fun insertRandomItems(numberOfItems: Int) {
repeat(numberOfItems) {
val normalEntity = keyValueEntity()
keyValueDao.insert(normalEntity)
}
}
private fun keyValueEntity(): KeyValuesEntity {
val data = KeyValueTestDataProvider.provideDummyTestData()
return KeyValuesEntity(
key = data.key,
value = data.value
)
}
}
| gpl-3.0 |
wireapp/wire-android | app/src/main/kotlin/com/waz/zclient/feature/backup/folders/FoldersBackupDataSource.kt | 1 | 1185 | package com.waz.zclient.feature.backup.folders
import com.waz.zclient.core.extension.empty
import com.waz.zclient.feature.backup.BackUpDataMapper
import com.waz.zclient.feature.backup.BackUpDataSource
import com.waz.zclient.feature.backup.BackUpIOHandler
import com.waz.zclient.storage.db.folders.FoldersEntity
import kotlinx.serialization.Serializable
import java.io.File
@Serializable
data class FoldersBackUpModel(
val id: String,
val name: String = String.empty(),
val type: Int = 0
)
class FoldersBackupMapper : BackUpDataMapper<FoldersBackUpModel, FoldersEntity> {
override fun fromEntity(entity: FoldersEntity) =
FoldersBackUpModel(id = entity.id, name = entity.name, type = entity.type)
override fun toEntity(model: FoldersBackUpModel) =
FoldersEntity(id = model.id, name = model.name, type = model.type)
}
class FoldersBackupDataSource(
override val databaseLocalDataSource: BackUpIOHandler<FoldersEntity, Unit>,
override val backUpLocalDataSource: BackUpIOHandler<FoldersBackUpModel, File>,
override val mapper: BackUpDataMapper<FoldersBackUpModel, FoldersEntity>
) : BackUpDataSource<FoldersBackUpModel, FoldersEntity>()
| gpl-3.0 |
UKandAndroid/AndroidHelper | app/src/main/java/com/helper/lib/Flow.kt | 1 | 27057 |
package com.helper.lib;
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
typealias SingleCallback = (action: Flow.Action) -> Unit
// Version 3.0.5
// Concurrent execution bug fixed
// ## EXAMPLES ##
// var flow = Flow<String>( flowCode )
// METHOD: registerAction(events = listOf(event1, event2, event3)){} code will be executed when all three events are fired, and then when combined state changes
// METHOD: registerEvents(events = listOf(event1, event2, event3)){} code will be executed every time when an event is fired
// METHOD: waitForEvents(events = listOf(event1, event2, event3)){} code will be executed only once when all three events are fired
// Example 1: flow.registerAction(1, listOf("email_entered", "password_entered", "verify_code_entered") ) action 1 gets called when all those events occur
// : flow.event("email_entered", true, extra(opt), object(opt)) is trigger for the registered event "email_entered",
// : when all three events are triggered with flow.event(...., true), action 1 is executed with bSuccess = true
// : after 3 event true(s), if one event(...., false) sends false, action 1 will be executed with bSuccess = false
// : now action 1 will only trigger again when all onEvents(...., true) are true, i.e the events which sent false, send true again
// var flowCode = object: Flow.ExecuteCode(){
// @override fun onAction(int iAction, boolean bSuccess, int iExtra, Object data){
// when(iAction) {
// 1 -> // this code will run in first example when all events are triggered as true
// 3 -> // this will run when ever run(3) is called
// 4 -> // this will run on ui thread whenever runOnUi(4) is called
// 5 -> // this will run on delayed by 4 secs
// 6(NOT CALLED) -> this wont be called as local callback is provided
// } }
// Example : flow.runOnUi(){} runs code on ui thread
// Example : flow.runRepeat(500){} repeats code until cancelled
// Example : flow.runDelayed(2000){} run code after delay period
// Example : flow.getAction(1) returns action object
// Example : action.getEvents() returns all events associated with the action
// Example : action.getEvent(event) returns selected event
// Example : action.getFiredEvent() returns most recently fired event or null
// Example : action.getWaitingEvent() returns first event that is stopping the action being fired, either its not fired or fired with false
open class Flow<EventType> @JvmOverloads constructor(val tag: String = "", codeBlock: ExecuteCode? = null) : LifecycleObserver {
enum class EventStatus {
WAITING, SUCCESS, FAILURE
}
private var LOG_LEVEL = 4
private var autoIndex = -1
private var bRunning = true
private var hThread: HThread
private val LOG_TAG = "Flow:$tag"
private var listActions = ArrayList<_Action>() // List of registered actions
private var globalCallback: ExecuteCode? = null // Call back for onAction to be executed
// INTERFACE for code execution
interface ExecuteCode {
fun onAction(iAction: Int, bSuccess: Boolean, iExtra: Int, data: Any?)
}
init {
globalCallback = codeBlock
hThread = HThread()
}
fun setLogLevel(level: Int) {
LOG_LEVEL = level
}
fun execute(codeCallback: ExecuteCode) {
globalCallback = codeCallback
}
// STATE METHODS pause, resume, stop the action, should be called to release resources
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
open fun pause() {
loge(1, "Paused !!!: " )
hThread.mHandler.removeCallbacksAndMessages(null)
hThread.mUiHandler.removeCallbacksAndMessages(null)
bRunning = false
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
open fun resume() {
bRunning = true
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
open fun stop() {
loge(1, "Stopped !!! " )
globalCallback = null
try {
for (action in listActions) { action.recycle() }
hThread.mHandler.removeCallbacksAndMessages(null)
hThread.mUiHandler.removeCallbacksAndMessages(null)
hThread.stop()
listActions.clear()
_Event.releasePool()
bRunning = false
} catch (e: Exception) {
}
}
// METHOD sets the type of action callback
// RESULT_CHANGE = When result changes from false to true or true to false
// RESULT_UPDATE = when result updates means all events are fired a
// EVENT_UPDATE = whenever an event associated with action is updated
fun actionRunType(iAction:Int, type: RunType) {
_getAction(iAction)?.runType = type
}
fun getAction(iAction: Int) = _getAction(iAction) as Flow.Action
fun getActionEvents(iAction: Int) = _getAction(iAction)?.getEvents()
fun getActionWaitingEvent(iAction: Int) = _getAction(iAction)?.getWaitingEvent() // Returns first found event that is stopping the action from triggering
fun resetAction(iAction: Int) { _getAction(iAction)?.reset() } // Resets action by resetting all events to initial Waiting state
private fun _getAction(iAction: Int) = listActions.firstOrNull { it.iAction == iAction } // throws NoSuchElementException if action not found
@JvmOverloads
fun runAction(iAction: Int , runOnUi: Boolean = false, bSuccess: Boolean = true, iExtra: Int = 0, obj: Any? = null): Flow<EventType> {
if (runOnUi) hThread.runOnUI(iAction, bSuccess, iExtra, obj) else hThread.run(iAction, bSuccess, iExtra, obj)
return this
}
@JvmOverloads
fun runRepeat(iAction: Int = autoIndex--, runOnUi: Boolean = false, iDelay: Long, callback: SingleCallback? = null): Flow<EventType> {
val delayEvent = "repeat_event_$iAction"
_registerAction(iAction, runOnUi, false, false, true, listOf(delayEvent), callback)
hThread.mHandler.postDelayed((Runnable { this.event(delayEvent, true, 0, iDelay) }), iDelay)
return this
}
fun runOnUi(callback: SingleCallback){
hThread.runOnUI(0, true, 0, _Action(0, events = listOf<String>(), singleCallback = callback))
}
@JvmOverloads
fun runDelayed(iAction: Int = autoIndex--, runOnUi: Boolean = false, iDelay: Long, bSuccess: Boolean = true, iExtra: Int = 0, any: Any? = null, callback: SingleCallback? = null): Flow<EventType> {
val delayEvent = "delay_event_$iAction"
val action = _registerAction(iAction, runOnUi, true, false, false, listOf(delayEvent), callback)
hThread.mHandler.postDelayed((Runnable { action.onEvent(delayEvent, bSuccess, iExtra, any) }), iDelay)
return this
}
@JvmOverloads
fun registerAction(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: List<EventType>, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, false, false, events, singleCallback)
return this
}
@JvmOverloads
fun registerEvents(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: List<EventType>, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, false, false, events, singleCallback)
actionRunType(iAction, RunType.EVENT_UPDATE)
return this
}
@JvmOverloads
fun registerEvents(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: EventType, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, false, false, listOf(events), singleCallback)
actionRunType(iAction, RunType.EVENT_UPDATE)
return this
}
@JvmOverloads
fun registerAction(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: EventType, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, false, false, listOf(events), singleCallback)
return this
}
@JvmOverloads
fun waitForEvents(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: List<EventType>, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, true, false, false, events, singleCallback)
return this
}
@JvmOverloads
fun waitForEvents(iAction: Int = autoIndex--, runOnUi: Boolean = false, events: EventType, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, true, false, false, listOf(events), singleCallback)
return this
}
fun registerActionSequence(iAction: Int, runOnUi: Boolean, events: List<EventType>, singleCallback: SingleCallback? = null): Flow<EventType> {
_registerAction(iAction, runOnUi, false, true, false, events, singleCallback)
return this
}
fun deleteAction(iAction: Int){ cancelAction(iAction) }
fun removeAction(iAction: Int){ cancelAction(iAction) }
fun cancelAction(action: Action){ cancelAction(action.getId()) }
fun cancelAction(iAction: Int) {
val copyList = ArrayList(listActions) // to avoid deleting of event issues while going through list
copyList.firstOrNull { it.iAction == iAction }?.run {
_cancelAction(this)
loge(1,"CANCEL: Action($iAction), removed ")
}
}
private fun _cancelAction(action: _Action){
hThread.mHandler.removeMessages(action.iAction)
hThread.mUiHandler.removeMessages(action.iAction)
action.recycle()
listActions.remove(action)
}
private fun _registerAction(iAction: Int, bUiThread: Boolean, bRunOnce: Boolean, bSequence: Boolean, bRepeat: Boolean, events: List<*>, actionCallback: SingleCallback? = null): _Action{
cancelAction(iAction) // to stop duplication, remove if the action already exists
val actionFlags = setActionFlags(runOnUI = bUiThread, runOnce = bRunOnce, eventSequence = bSequence, repeatAction = bRepeat)
val aAction = _Action(iAction, actionFlags, events, actionCallback)
listActions.add(aAction)
val buf = StringBuffer(400)
for (event in events) {
buf.append(event.toString() + ", ")
}
log(1,"ACTION: $iAction registered EVENTS = { ${buf.removeSuffix(", ")} }")
return aAction
}
// METHODS to send event
@Synchronized
@JvmOverloads
fun event(sEvent: Any, bSuccess: Boolean = true, iExtra: Int = 0, obj: Any? = null) : Boolean {
if (!bRunning)
return false
var eventFired = false
log(2,"EVENT: $sEvent $bSuccess")
val copyList = ArrayList(listActions) // to avoid deleting of event issues while going through list
try {
for (action in copyList) {
if(action.onEvent(sEvent, bSuccess, iExtra, obj).first){
eventFired = true
}
}
} catch (e: IndexOutOfBoundsException) {
loge(e.toString())
} catch (e: NullPointerException){
logw(2,"event() - null pointer exception")
}
return eventFired
}
// METHOD cancel a runDelay or RunRepeated
fun cancelRun(iAction: Int) {
if (!bRunning) return
hThread.mHandler.removeMessages(iAction)
hThread.mUiHandler.removeMessages(iAction)
}
// CLASS for events for action, when all events occur action is triggered
open class Action( internal val iAction: Int) {
protected var listEvents: MutableList<Event<*>> = ArrayList() // List to store Flow.Events needed for this action
protected var iLastStatus = EventStatus.WAITING // Event set status as a whole, waiting, success, non success
protected var lastFiredEvent : Event<*>? = null // last fired event for this action, null if none
fun getId() = iAction
// returns first event that has not been fired or fired with false
fun getFiredEvent() = lastFiredEvent
fun getFiredEventObj() = lastFiredEvent?.obj
fun getEvents() = listEvents as List<Event<*>>
fun isWaitingFor(event: Any) = getWaitingEvent() == event
fun getEvent(event: Any) = getEvents().firstOrNull{ it.event == event }
fun getWaitingEvent() = listEvents.first { !it.isSuccess() }.event // Throws exception if event not found
fun reset() {
iLastStatus = EventStatus.WAITING
for (event in listEvents) {
(event as _Event).resetEvent()
}
}
}
// CLASS for event Pool
open class Event<ActionEvents> { // CONSTRUCTOR - Private
var obj: Any? = null
var extra = 0
var event: ActionEvents? = null
protected var _status :EventStatus = EventStatus.WAITING // WAITING - waiting not fired yet, SUCCESS - fired with success, FAILURE - fired with failure
// Variable for pool
fun isSuccess() = _status == EventStatus.SUCCESS
}
private inner class _Action(
iAction: Int,
private var actionFlags: Int = 0,
events: List<*>,
private var singleCallback: SingleCallback? = null
) : Action(iAction) {
internal var runType: RunType = RunType.RESULT_CHANGE
internal var iEventCount: Int = events.size // How many event are for this action code to be triggered
init {
for (i in 0 until iEventCount) {
listEvents.add(_Event.obtain(events[i])) // get events from events pool
}
}
internal fun getFlag(flag: Int) = Companion.getFlag(actionFlags, flag)
internal fun setFlag(flag: Int) {
Companion.setFlag(actionFlags, flag, true)
}
internal fun clearFlag(flag: Int) {
Companion.setFlag(actionFlags, flag, false)
}
internal fun execute(): Boolean {
if (singleCallback != null) {
singleCallback?.invoke(this as Action)
return true
}
return false
}
internal fun getEventData(events: EventType): Any? {
return listEvents.find { it.event == events }?.obj
}
// METHOD recycles events and clears actions
internal fun recycle() {
singleCallback = null
iEventCount = 0
/*for (event in listEvents) { don't recycle events as sometimes one event can fire multiple actions
(event as _Event).recycle() // and recycling event deletes event when access by 2nd action
}*/
listEvents = ArrayList()
}
// METHOD searches all actions, if any associated with this event
fun onEvent(sEvent: Any, bResult: Boolean, iExtra: Int, obj: Any?): Pair<Boolean, Boolean> {
var iSuccess = 0 // How many successful events has been fired
var iFiredCount = 0 // How many events for this action have been fired
var bEventFound = false
var bActionExecuted = false
for (i in 0 until iEventCount) {
val event = listEvents[i] as _Event
if (sEvent == event.event) { // If event is found in this event list
bEventFound = true
lastFiredEvent = event
event.setData(bResult, iExtra, obj )
} else if (getFlag(FLAG_SEQUENCE) && event.statusIs(EventStatus.WAITING)) { // if its a Sequence action, no event should be empty before current event
if (i != 0) {
(listEvents[i - 1] as _Event).setStatus( EventStatus.WAITING ) // reset last one, so they are always in sequence
}
break
}
when (event.status()) {
EventStatus.FAILURE -> iFiredCount++
EventStatus.SUCCESS -> {
iSuccess++
iFiredCount++ // Add to fired event regard less of success or failure
}
}
if (bEventFound && getFlag(FLAG_SEQUENCE)) break
}
if (bEventFound) { // if event was found in this Action
logw(2,"ACTION: $iAction FIRED on: $sEvent { Total $iEventCount Fired: $iFiredCount Success: $iSuccess }")
if (runType == RunType.EVENT_UPDATE) { // if this action is launched on every event update
bActionExecuted = true
executeAction(bResult, iExtra)
} else if (iFiredCount == iEventCount) { // if all events for action has been fired
val bSuccess = iSuccess == iEventCount // all events registered success
val iCurStatus = if (bSuccess) EventStatus.SUCCESS else EventStatus.FAILURE
when (runType) {
RunType.RESULT_CHANGE -> if (iCurStatus != iLastStatus) { // If there is a change in action status only then run code
bActionExecuted = true
iLastStatus = iCurStatus
executeAction(bSuccess, iSuccess)
}
RunType.RESULT_UPDATE -> if (bSuccess) {
bActionExecuted = true
executeAction(bSuccess, iSuccess)
}
}
}
}
return Pair(bActionExecuted, getFlag(FLAG_RUNONCE))
}
// METHOD executes action code on appropriate thread
private fun executeAction(bSuccess: Boolean, iExtra: Int) {
logw(1,"ACTION: $iAction Executed with $bSuccess ")
if (getFlag(FLAG_RUNonUI)) {
hThread.runOnUI(iAction, bSuccess, iExtra, this as Flow.Action)
} else {
hThread.run(iAction, bSuccess, iExtra, this)
}
}
}
private class _Event<ExternalEvents> private constructor() : Event<ExternalEvents>(){
companion object {
// EVENTS for self use
private var next: _Event<Any>? = null // Reference to next object
private var sPool: _Event<Any>? = null
private var sPoolSize = 0
private const val MAX_POOL_SIZE = 50
private val sPoolSync = Any() // The lock used for synchronization
// METHOD get pool object only through this method, so no direct allocation are made
fun <ExternalEvents> obtain(sId: ExternalEvents?): _Event<*> {
synchronized(sPoolSync) {
if (sPool != null) {
val e = sPool as _Event<ExternalEvents>
e.event = sId
e.setData(EventStatus.WAITING, 0, null)
sPool = next
next = null
sPoolSize --
return e
}
val eve = _Event<ExternalEvents>()
eve.event = sId
return eve
}
}
// METHOD release pool, ready for garbage collection
fun releasePool() {
sPoolSize = 0
sPool = null
}
}
fun status() = _status
fun setStatus(value: EventStatus) { _status = value }
fun statusIs(value: EventStatus) = _status == value
fun resetEvent() {
obj = null
extra = 0
_status = EventStatus.WAITING
}
fun setData(status : EventStatus, ext : Int, data: Any? ) {
_status = status
obj = data
extra = ext
}
fun setData(status : Boolean, ext : Int, data: Any? ) {
_status = if (status) EventStatus.SUCCESS else EventStatus.FAILURE
obj = data
extra = ext
}
// METHOD object added to the pool, to be reused
internal fun recycle() {
synchronized(sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool as _Event<Any>?
sPool = this as _Event<Any>
sPoolSize++
}
}
}
}
// CLASS for thread handler
private inner class HThread internal constructor() : Handler.Callback {
val mHandler: Handler
val mUiHandler: Handler
var ACTION_FAIL = 0
var ACTION_SUCCESS = 1
@JvmOverloads
fun run(iStep: Int, bRunUI: Boolean = false) {
if (bRunUI) {
runOnUI(iStep, true, 0, null)
} else {
run(iStep, true, 0, null)
}
}
fun run(iAction: Int, bSuccess: Boolean, iExtra: Int, obj: Any?) {
if (bRunning) {
val msg = Message.obtain()
msg.what = iAction
msg.arg1 = iExtra
msg.arg2 = if (bSuccess) ACTION_SUCCESS else ACTION_FAIL
msg.obj = obj
mHandler.sendMessage(msg)
}
}
fun runOnUI(iAction: Int, bSuccess: Boolean, iExtra: Int, obj: Any?) {
if (bRunning) {
val msg = Message.obtain()
msg.what = iAction
msg.arg1 = iExtra
msg.arg2 = if (bSuccess) ACTION_SUCCESS else ACTION_FAIL
msg.obj = obj
mUiHandler.sendMessage(msg)
}
}
// METHOD MESSAGE HANDLER
override fun handleMessage(msg: Message): Boolean {
if (msg.obj !is Flow<*>._Action) { // called directly with runAction() action probably does not exist
globalCallback?.onAction(msg.what, msg.arg2 == ACTION_SUCCESS, msg.arg1, msg.obj)
} else { // is Flow Action with events
val action = msg.obj as Flow<EventType>._Action
if (action.getFlag(FLAG_REPEAT)) { // If its a repeat action, we have to post it again
val event = action.getEvents()[0] // get delay event for data
hThread.mHandler.postDelayed((Runnable { action.onEvent(event.event!!, !event.isSuccess(), ++event.extra, event.obj) }), event.obj as Long)
// posting action.onEvent() not Flow.event(), to keep event local to its own action
}
if (!action.execute()) { // if there is no specific callback for action, call generic call back
globalCallback?.onAction(msg.what, msg.arg2 == ACTION_SUCCESS, msg.arg1, msg.obj as Flow.Action)
}
if (action.getFlag(FLAG_RUNONCE)) {
loge(2,"REMOVING: Action(${action.iAction}, runOnce) as its executed")
_cancelAction(action) // Recycle if its flagged for it
}
}
return true
}
fun stop() {
mHandler.removeCallbacksAndMessages(null)
mUiHandler.removeCallbacksAndMessages(null)
mHandler.looper.quit()
}
init {
val ht = HandlerThread("BGThread_ ${++iThreadCount}")
ht.start()
mHandler = Handler(ht.looper, this)
mUiHandler = Handler(Looper.getMainLooper(), this)
}
}
// METHOD for logging
private fun log(sLog: String) {
log(3, sLog)
}
private fun loge(sLog: String?) {
loge(3, sLog)
}
private fun logw(sLog: String?) {
logw(3, sLog)
}
private fun log(iLevel: Int, sLog: String) {
if (iLevel <= LOG_LEVEL) {
Log.d(LOG_TAG, sLog)
}
}
private fun loge(iLevel: Int, sLog: String?) {
if (iLevel <= LOG_LEVEL) {
Log.e(LOG_TAG, sLog)
}
}
private fun logw(iLevel: Int, sLog: String?) {
if (iLevel <= LOG_LEVEL) {
Log.w(LOG_TAG, sLog)
}
}
enum class RunType {
EVENT_UPDATE, // action will be invoked for each event update
RESULT_CHANGE, // action will be invoked when combined result for events changes e.g true to false or false to true
RESULT_UPDATE // action will be invoked once combined result is achieved, then every time after an event changes
}
companion object {
private var iThreadCount = 0
private const val FLAG_SUCCESS = 0x00000001
private const val FLAG_RUNonUI = 0x00000002
private const val FLAG_REPEAT = 0x00000004
private const val FLAG_RUNONCE = 0x00000008
private const val FLAG_SEQUENCE = 0x00000010
// METHODS for packing data for repeat event
private fun addExtraInt(iValue: Int, iData: Int): Int {
return iValue or (iData shl 8)
}
private fun getExtraInt(iValue: Int): Int {
return iValue shr 8
}
private fun getFlag(iValue: Int, iFlag: Int): Boolean {
return iValue and iFlag == iFlag
}
private fun setFlag(iValue: Int, iFlag: Int, bSet: Boolean = true): Int {
return if (bSet) {
iValue or iFlag
} else {
iValue and iFlag.inv()
}
}
private fun setActionFlags(runOnUI: Boolean = false, runOnce: Boolean = false, eventSequence: Boolean = false, repeatAction: Boolean = false): Int {
var intFlags: Int = 0
intFlags = setFlag(intFlags, FLAG_RUNonUI, runOnUI)
intFlags = setFlag(intFlags, FLAG_RUNONCE, runOnce)
intFlags = setFlag(intFlags, FLAG_SEQUENCE, eventSequence)
intFlags = setFlag(intFlags, FLAG_REPEAT, repeatAction)
return intFlags
}
}
}
| gpl-2.0 |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/list/InternalPagedListDataSourceTest.kt | 1 | 4089 | package org.wordpress.android.fluxc.list
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId
import org.wordpress.android.fluxc.model.list.datasource.InternalPagedListDataSource
import org.wordpress.android.fluxc.model.list.datasource.ListItemDataSourceInterface
import kotlin.test.assertEquals
private const val NUMBER_OF_ITEMS = 71
private const val IS_LIST_FULLY_FETCHED = false
private val testListDescriptor = TestListDescriptor()
private val testStartAndEndPosition = Pair(5, 10)
internal class InternalPagedListDataSourceTest {
private val remoteItemIds = mock<List<RemoteId>>()
private val mockIdentifiers = mock<List<TestListIdentifier>>()
private val mockItemDataSource = mock<ListItemDataSourceInterface<TestListDescriptor, TestListIdentifier, String>>()
@Before
fun setup() {
whenever(remoteItemIds.size).thenReturn(NUMBER_OF_ITEMS)
whenever(mockIdentifiers.size).thenReturn(NUMBER_OF_ITEMS)
val mockSublist = mock<List<TestListIdentifier>>()
whenever(mockIdentifiers.subList(any(), any())).thenReturn(mockSublist)
whenever(
mockItemDataSource.getItemIdentifiers(
listDescriptor = testListDescriptor,
remoteItemIds = remoteItemIds,
isListFullyFetched = IS_LIST_FULLY_FETCHED
)
).thenReturn(mockIdentifiers)
}
/**
* Tests that item identifiers are cached when a new instance of [InternalPagedListDataSource] is created.
*
* Caching the item identifiers is how we ensure that this component will provide consistent data to
* `PositionalDataSource` so it's very important that we have this test. Since we don't have access to
* `InternalPagedListDataSource.itemIdentifiers` private property, we have to test the internal implementation
* which is more likely to break. However, in this specific case, we DO want the test to break if the internal
* implementation changes.
*/
@Test
fun `init calls getItemIdentifiers`() {
createInternalPagedListDataSource(mockItemDataSource)
verify(mockItemDataSource).getItemIdentifiers(eq(testListDescriptor), any(), any())
}
@Test
fun `total size uses getItemIdentifiers' size`() {
val internalDataSource = createInternalPagedListDataSource(mockItemDataSource)
assertEquals(
NUMBER_OF_ITEMS, internalDataSource.totalSize, "InternalPagedListDataSource should not change the" +
"number of items in a list and should propagate that to its ListItemDataSourceInterface"
)
}
@Test
fun `getItemsInRange creates the correct sublist of the identifiers`() {
val internalDataSource = createInternalPagedListDataSource(mockItemDataSource)
val (startPosition, endPosition) = testStartAndEndPosition
internalDataSource.getItemsInRange(startPosition, endPosition)
verify(mockIdentifiers).subList(startPosition, endPosition)
}
@Test
fun `getItemsInRange propagates the call to getItemsAndFetchIfNecessary correctly`() {
val internalDataSource = createInternalPagedListDataSource(dataSource = mockItemDataSource)
val (startPosition, endPosition) = testStartAndEndPosition
internalDataSource.getItemsInRange(startPosition, endPosition)
verify(mockItemDataSource).getItemsAndFetchIfNecessary(eq(testListDescriptor), any())
}
private fun createInternalPagedListDataSource(
dataSource: TestListItemDataSource
): TestInternalPagedListDataSource {
return InternalPagedListDataSource(
listDescriptor = testListDescriptor,
remoteItemIds = remoteItemIds,
isListFullyFetched = IS_LIST_FULLY_FETCHED,
itemDataSource = dataSource
)
}
}
| gpl-2.0 |
xfournet/intellij-community | python/src/com/jetbrains/python/testing/PyTestsShared.kt | 1 | 30377 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.testing
import com.intellij.execution.ExecutionException
import com.intellij.execution.Location
import com.intellij.execution.PsiLocation
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.execution.configurations.*
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.testframework.AbstractTestProxy
import com.intellij.execution.testframework.sm.runner.SMTestLocator
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMExternalizerUtil.readField
import com.intellij.openapi.util.JDOMExternalizerUtil.writeField
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.QualifiedName
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.util.ThreeState
import com.jetbrains.extensions.asPsiElement
import com.jetbrains.extensions.asVirtualFile
import com.jetbrains.extensions.getQName
import com.jetbrains.extensions.isWellFormed
import com.jetbrains.extenstions.ModuleBasedContextAnchor
import com.jetbrains.extenstions.QNameResolveContext
import com.jetbrains.extenstions.getElementAndResolvableName
import com.jetbrains.extenstions.resolveToElement
import com.jetbrains.python.PyBundle
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyFunction
import com.jetbrains.python.psi.PyQualifiedNameOwner
import com.jetbrains.python.psi.types.TypeEvalContext
import com.jetbrains.python.run.*
import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant
import com.jetbrains.python.run.targetBasedConfiguration.TargetWithVariant
import com.jetbrains.python.run.targetBasedConfiguration.createRefactoringListenerIfPossible
import com.jetbrains.reflection.DelegationProperty
import com.jetbrains.reflection.Properties
import com.jetbrains.reflection.Property
import com.jetbrains.reflection.getProperties
import jetbrains.buildServer.messages.serviceMessages.ServiceMessage
import jetbrains.buildServer.messages.serviceMessages.TestStdErr
import jetbrains.buildServer.messages.serviceMessages.TestStdOut
import java.util.regex.Matcher
/**
* New configuration factories
*/
val factories: Array<PythonConfigurationFactoryBase> = arrayOf(
PyUnitTestFactory,
PyTestFactory,
PyNoseTestFactory,
PyTrialTestFactory)
/**
* Accepts text that may be wrapped in TC message. Unwarps it and removes TC escape code.
* Regular text is unchanged
*/
fun processTCMessage(text: String): String {
val parsedMessage = ServiceMessage.parse(text.trim()) ?: return text // Not a TC message
return when (parsedMessage) {
is TestStdOut -> parsedMessage.stdOut // TC with stdout
is TestStdErr -> parsedMessage.stdErr // TC with stderr
else -> "" // TC with out of any output
}
}
internal fun getAdditionalArgumentsPropertyName() = com.jetbrains.python.testing.PyAbstractTestConfiguration::additionalArguments.name
/**
* If runner name is here that means test runner only can run inheritors for TestCase
*/
val RunnersThatRequireTestCaseClass = setOf(PythonTestConfigurationsModel.PYTHONS_UNITTEST_NAME)
/**
* Checks if element could be test target
* @param testCaseClassRequired see [PythonUnitTestUtil] docs
*/
fun isTestElement(element: PsiElement, testCaseClassRequired: ThreeState, typeEvalContext: TypeEvalContext) = when (element) {
is PyFile -> PythonUnitTestUtil.isTestFile(element, testCaseClassRequired, typeEvalContext)
is com.intellij.psi.PsiDirectory -> element.name.contains("test", true) || element.children.any {
it is PyFile && PythonUnitTestUtil.isTestFile(it, testCaseClassRequired, typeEvalContext)
}
is PyFunction -> PythonUnitTestUtil.isTestFunction(element,
testCaseClassRequired, typeEvalContext)
is com.jetbrains.python.psi.PyClass -> {
PythonUnitTestUtil.isTestClass(element, testCaseClassRequired, typeEvalContext)
}
else -> false
}
/**
* Since runners report names of tests as qualified name, no need to convert it to PSI and back to string.
* We just save its name and provide it again to rerun
* TODO: Doc derived problem
*/
private class PyTargetBasedPsiLocation(val target: ConfigurationTarget,
element: PsiElement) : PsiLocation<PsiElement>(element) {
override fun equals(other: Any?): Boolean {
if (other is PyTargetBasedPsiLocation) {
return target == other.target
}
return false
}
override fun hashCode(): Int {
return target.hashCode()
}
}
/**
* @return factory chosen by user in "test runner" settings
*/
private fun findConfigurationFactoryFromSettings(module: Module): ConfigurationFactory {
val name = TestRunnerService.getInstance(module).projectConfiguration
val factories = PythonTestConfigurationType.getInstance().configurationFactories
val configurationFactory = factories.find { it.name == name }
return configurationFactory ?: factories.first()
}
// folder provided by python side. Resolve test names versus it
private val PATH_URL = java.util.regex.Pattern.compile("^python<([^<>]+)>$")
/**
* Resolves url into element
*/
fun getElementByUrl(url: String,
module: Module,
evalContext: TypeEvalContext): Location<out PsiElement>? {
val protocol = VirtualFileManager.extractProtocol(url) ?: return null
return getElementByUrl(protocol,
VirtualFileManager.extractPath(url),
module,
evalContext)
}
private fun getElementByUrl(protocol: String,
path: String,
module: Module,
evalContext: TypeEvalContext,
matcher: Matcher = PATH_URL.matcher(protocol)): Location<out PsiElement>? {
val folder = if (matcher.matches()) {
LocalFileSystem.getInstance().findFileByPath(matcher.group(1))
}
else {
null
}
val qualifiedName = QualifiedName.fromDottedString(path)
// Assume qname id good and resolve it directly
val element = qualifiedName.resolveToElement(QNameResolveContext(ModuleBasedContextAnchor(module),
evalContext = evalContext,
folderToStart = folder,
allowInaccurateResult = true))
return if (element != null) {
// Path is qualified name of python test according to runners protocol
// Parentheses are part of generators / parametrized tests
// Until https://github.com/JetBrains/teamcity-messages/issues/121 they are disabled,
// so we cut them out of path not to provide unsupported targets to runners
val pathNoParentheses = QualifiedName.fromComponents(
qualifiedName.components.filter { !it.contains('(') }).toString()
PyTargetBasedPsiLocation(ConfigurationTarget(pathNoParentheses, PyRunTargetVariant.PYTHON), element)
}
else {
null
}
}
object PyTestsLocator : SMTestLocator {
override fun getLocation(protocol: String,
path: String,
project: Project,
scope: GlobalSearchScope): List<Location<out PsiElement>> {
if (scope !is ModuleWithDependenciesScope) {
return listOf()
}
val matcher = PATH_URL.matcher(protocol)
if (!matcher.matches()) {
// special case: setup.py runner uses unittest configuration but different (old) protocol
// delegate to old protocol locator until setup.py moved to separate configuration
val oldLocation = PythonUnitTestTestIdUrlProvider.INSTANCE.getLocation(protocol, path, project, scope)
if (oldLocation.isNotEmpty()) {
return oldLocation
}
}
return getElementByUrl(protocol, path, scope.module, TypeEvalContext.codeAnalysis(project, null), matcher)?.let {
listOf(it)
} ?: listOf()
}
}
abstract class PyTestExecutionEnvironment<T : PyAbstractTestConfiguration>(configuration: T,
environment: ExecutionEnvironment)
: PythonTestCommandLineStateBase<T>(configuration, environment) {
override fun getTestLocator(): SMTestLocator = PyTestsLocator
override fun getTestSpecs(): MutableList<String> = java.util.ArrayList(configuration.getTestSpec())
override fun generateCommandLine(patchers: Array<out CommandLinePatcher>?): GeneralCommandLine {
val line = super.generateCommandLine(patchers)
line.workDirectory = java.io.File(configuration.workingDirectorySafe)
return line
}
}
abstract class PyAbstractTestSettingsEditor(private val sharedForm: PyTestSharedForm)
: SettingsEditor<PyAbstractTestConfiguration>() {
override fun resetEditorFrom(s: PyAbstractTestConfiguration) {
// usePojoProperties is true because we know that Form is java-based
AbstractPythonRunConfiguration.copyParams(s, sharedForm.optionsForm)
s.copyTo(getProperties(sharedForm, usePojoProperties = true))
}
override fun applyEditorTo(s: PyAbstractTestConfiguration) {
AbstractPythonRunConfiguration.copyParams(sharedForm.optionsForm, s)
s.copyFrom(getProperties(sharedForm, usePojoProperties = true))
}
override fun createEditor(): javax.swing.JComponent = sharedForm.panel
}
/**
* Default target path (run all tests ion project folder)
*/
private val DEFAULT_PATH = ""
/**
* Target depends on target type. It could be path to file/folder or python target
*/
data class ConfigurationTarget(@ConfigField override var target: String,
@ConfigField override var targetType: PyRunTargetVariant) : TargetWithVariant {
fun copyTo(dst: ConfigurationTarget) {
// TODO: do we have such method it in Kotlin?
dst.target = target
dst.targetType = targetType
}
/**
* Validates configuration and throws exception if target is invalid
*/
fun checkValid() {
if (targetType != PyRunTargetVariant.CUSTOM && target.isEmpty()) {
throw RuntimeConfigurationWarning("Target not provided")
}
if (targetType == PyRunTargetVariant.PYTHON && !isWellFormed()) {
throw RuntimeConfigurationError("Provide a qualified name of function, class or a module")
}
}
fun asPsiElement(configuration: PyAbstractTestConfiguration) =
asPsiElement(configuration, configuration.getWorkingDirectoryAsVirtual())
fun generateArgumentsLine(configuration: PyAbstractTestConfiguration): List<String> =
when (targetType) {
PyRunTargetVariant.CUSTOM -> emptyList()
PyRunTargetVariant.PYTHON -> getArgumentsForPythonTarget(configuration)
PyRunTargetVariant.PATH -> listOf("--path", target.trim())
}
private fun getArgumentsForPythonTarget(configuration: PyAbstractTestConfiguration): List<String> {
val element = asPsiElement(configuration) ?: throw ExecutionException(
"Can't resolve $target. Try to remove configuration and generate it again")
if (element is PsiDirectory) {
// Directory is special case: we can't run it as package for now, so we run it as path
return listOf("--path", element.virtualFile.path)
}
val context = TypeEvalContext.userInitiated(configuration.project, null)
val qNameResolveContext = QNameResolveContext(
contextAnchor = ModuleBasedContextAnchor(configuration.module!!),
evalContext = context,
folderToStart = LocalFileSystem.getInstance().findFileByPath(configuration.workingDirectorySafe),
allowInaccurateResult = true
)
val qualifiedNameParts = QualifiedName.fromDottedString(target.trim()).tryResolveAndSplit(qNameResolveContext)
?: throw ExecutionException("Can't find file where $target declared. " +
"Make sure it is in project root")
// We can't provide element qname here: it may point to parent class in case of inherited functions,
// so we make fix file part, but obey element(symbol) part of qname
if (!configuration.shouldSeparateTargetPath()) {
// Here generate qname instead of file/path::element_name
// Try to set path relative to work dir (better than path from closest root)
// If we can resolve element by this path relative to working directory then use it
val qNameInsideOfDirectory = qualifiedNameParts.getElementNamePrependingFile()
val elementAndName = qNameInsideOfDirectory.getElementAndResolvableName(qNameResolveContext.copy(allowInaccurateResult = false))
if (elementAndName != null) {
// qNameInsideOfDirectory may contain redundant elements like subtests so we use name that was really resolved
// element.qname can't be used because inherited test resolves to parent
return listOf("--target", elementAndName.name.toString())
}
// Use "full" (path from closest root) otherwise
val name = (element.containingFile as? PyFile)?.getQName()?.append(qualifiedNameParts.elementName) ?: throw ExecutionException(
"Can't get importable name for ${element.containingFile}. Is it a python file in project?")
return listOf("--target", name.toString())
}
else {
// Here generate file/path::element_name
val pyTarget = qualifiedNameParts.elementName
val elementFile = element.containingFile.virtualFile
val workingDir = elementFile.fileSystem.findFileByPath(configuration.workingDirectorySafe)
val fileSystemPartOfTarget = (if (workingDir != null) VfsUtil.getRelativePath(elementFile, workingDir)
else null)
?: elementFile.path
if (pyTarget.componentCount == 0) {
// If python part is empty we are launching file. To prevent junk like "foo.py::" we run it as file instead
return listOf("--path", fileSystemPartOfTarget)
}
return listOf("--target", "$fileSystemPartOfTarget::$pyTarget")
}
}
/**
* @return directory which target is situated
*/
fun getElementDirectory(configuration: PyAbstractTestConfiguration): VirtualFile? {
if (target == DEFAULT_PATH) {
//This means "current directory", so we do not know where is it
// getting vitualfile for it may return PyCharm working directory which is not what we want
return null
}
val fileOrDir = asVirtualFile() ?: asPsiElement(configuration)?.containingFile?.virtualFile ?: return null
return if (fileOrDir.isDirectory) fileOrDir else fileOrDir.parent
}
}
/**
* To prevent legacy configuration options from clashing with new names, we add prefix
* to use for writing/reading xml
*/
private val Property.prefixedName: String
get() = "_new_" + this.getName()
/**
* Parent of all new test configurations.
* All config-specific fields are implemented as properties. They are saved/restored automatically and passed to GUI form.
*
*/
abstract class PyAbstractTestConfiguration(project: Project,
configurationFactory: ConfigurationFactory,
private val runnerName: String)
: AbstractPythonTestRunConfiguration<PyAbstractTestConfiguration>(project, configurationFactory), PyRerunAwareConfiguration,
RefactoringListenerProvider {
@DelegationProperty
val target = ConfigurationTarget(DEFAULT_PATH, PyRunTargetVariant.PATH)
@ConfigField
var additionalArguments = ""
val testFrameworkName = configurationFactory.name!!
/**
* @see [RunnersThatRequireTestCaseClass]
*/
fun isTestClassRequired() = if (RunnersThatRequireTestCaseClass.contains(runnerName)) {
ThreeState.YES
}
else {
ThreeState.NO
}
@Suppress("LeakingThis") // Legacy adapter is used to support legacy configs. Leak is ok here since everything takes place in one thread
@DelegationProperty
val legacyConfigurationAdapter = PyTestLegacyConfigurationAdapter(this)
/**
* For real launch use [getWorkingDirectorySafe] instead
*/
internal fun getWorkingDirectoryAsVirtual(): VirtualFile? {
if (!workingDirectory.isNullOrEmpty()) {
return LocalFileSystem.getInstance().findFileByPath(workingDirectory)
}
return null
}
override fun getWorkingDirectorySafe(): String {
val dirProvidedByUser = super.getWorkingDirectory()
if (!dirProvidedByUser.isNullOrEmpty()) {
return dirProvidedByUser
}
return target.getElementDirectory(this)?.path ?: super.getWorkingDirectorySafe()
}
override fun getRefactoringElementListener(element: PsiElement?): RefactoringElementListener? {
if (element == null) return null
var renamer = CompositeRefactoringElementListener(PyWorkingDirectoryRenamer(getWorkingDirectoryAsVirtual(), this))
createRefactoringListenerIfPossible(element, target.asPsiElement(this), target.asVirtualFile(), { target.target = it })?.let {
renamer = renamer.plus(it)
}
return renamer
}
override fun checkConfiguration() {
super.checkConfiguration()
if (!isFrameworkInstalled()) {
throw RuntimeConfigurationWarning(
PyBundle.message("runcfg.testing.no.test.framework", testFrameworkName))
}
target.checkValid()
}
/**
* Check if framework is available on SDK
*/
abstract fun isFrameworkInstalled(): Boolean
override fun isIdTestBased() = true
private fun getPythonTestSpecByLocation(location: Location<*>): List<String> {
if (location is PyTargetBasedPsiLocation) {
return location.target.generateArgumentsLine(this)
}
if (location !is PsiLocation) {
return emptyList()
}
if (location.psiElement !is PyQualifiedNameOwner) {
return emptyList()
}
val qualifiedName = (location.psiElement as PyQualifiedNameOwner).qualifiedName ?: return emptyList()
// Resolve name as python qname as last resort
return ConfigurationTarget(qualifiedName, PyRunTargetVariant.PYTHON).generateArgumentsLine(this)
}
override fun getTestSpec(location: Location<*>,
failedTest: com.intellij.execution.testframework.AbstractTestProxy): String? {
val list = getPythonTestSpecByLocation(location)
if (list.isEmpty()) {
return null
}
else {
return list.joinToString(" ")
}
}
override fun getTestSpecsForRerun(scope: com.intellij.psi.search.GlobalSearchScope,
locations: MutableList<Pair<Location<*>, AbstractTestProxy>>): List<String> {
val result = java.util.ArrayList<String>()
// Set used to remove duplicate targets
locations.map { it.first }.distinctBy { it.psiElement }.map { getPythonTestSpecByLocation(it) }.filterNotNull().forEach {
result.addAll(it)
}
return result + generateRawArguments(true)
}
fun getTestSpec(): List<String> {
return target.generateArgumentsLine(this) + generateRawArguments()
}
/**
* raw arguments to be added after "--" and passed to runner directly
*/
private fun generateRawArguments(forRerun: Boolean = false): List<String> {
val rawArguments = additionalArguments + " " + getCustomRawArgumentsString(forRerun)
if (rawArguments.isNotBlank()) {
return listOf("--") + com.intellij.util.execution.ParametersListUtil.parse(rawArguments, false, true)
}
return emptyList()
}
override fun suggestedName() =
when (target.targetType) {
PyRunTargetVariant.PATH -> {
val name = target.asVirtualFile()?.name
"$testFrameworkName in " + (name ?: target.target)
}
PyRunTargetVariant.PYTHON -> {
"$testFrameworkName for " + target.target
}
else -> {
testFrameworkName
}
}
/**
* @return configuration-specific arguments
*/
protected open fun getCustomRawArgumentsString(forRerun: Boolean = false) = ""
fun reset() {
target.target = DEFAULT_PATH
target.targetType = PyRunTargetVariant.PATH
additionalArguments = ""
}
fun copyFrom(src: Properties) {
src.copyTo(getConfigFields())
}
fun copyTo(dst: Properties) {
getConfigFields().copyTo(dst)
}
override fun writeExternal(element: org.jdom.Element) {
// Write legacy config to preserve it
legacyConfigurationAdapter.writeExternal(element)
// Super is called after to overwrite legacy settings with new one
super.writeExternal(element)
val gson = com.google.gson.Gson()
getConfigFields().properties.forEach {
val value = it.get()
if (value != null) {
// No need to write null since null is default value
writeField(element, it.prefixedName, gson.toJson(value))
}
}
}
override fun readExternal(element: org.jdom.Element) {
super.readExternal(element)
val gson = com.google.gson.Gson()
getConfigFields().properties.forEach {
val fromJson: Any? = gson.fromJson(readField(element, it.prefixedName), it.getType())
if (fromJson != null) {
it.set(fromJson)
}
}
legacyConfigurationAdapter.readExternal(element)
}
private fun getConfigFields() = getProperties(this, ConfigField::class.java)
/**
* Checks if element could be test target for this config.
* Function is used to create tests by context.
*
* If yes, and element is [PsiElement] then it is [PyRunTargetVariant.PYTHON].
* If file then [PyRunTargetVariant.PATH]
*/
fun couldBeTestTarget(element: PsiElement): Boolean {
// TODO: PythonUnitTestUtil logic is weak. We should give user ability to launch test on symbol since user knows better if folder
// contains tests etc
val context = TypeEvalContext.userInitiated(element.project, element.containingFile)
return isTestElement(element, isTestClassRequired(), context)
}
/**
* There are 2 ways to provide target to runner:
* * As full qname (package1.module1.Class1.test_foo)
* * As filesystem path (package1/module1.py::Class1.test_foo) full or relative to working directory
*
* Second approach is prefered if this flag is set. It is generally better because filesystem path does not need __init__.py
*/
internal open fun shouldSeparateTargetPath(): Boolean = true
}
abstract class PyAbstractTestFactory<out CONF_T : PyAbstractTestConfiguration> : PythonConfigurationFactoryBase(
PythonTestConfigurationType.getInstance()) {
override abstract fun createTemplateConfiguration(project: Project): CONF_T
}
/**
* Only one producer is registered with EP, but it uses factory configured by user to produce different configs
*/
object PyTestsConfigurationProducer : AbstractPythonTestConfigurationProducer<PyAbstractTestConfiguration>(
PythonTestConfigurationType.getInstance()) {
override val configurationClass = PyAbstractTestConfiguration::class.java
override fun cloneTemplateConfiguration(context: ConfigurationContext): RunnerAndConfigurationSettings {
return cloneTemplateConfigurationStatic(context, findConfigurationFactoryFromSettings(context.module))
}
override fun createConfigurationFromContext(context: ConfigurationContext?): ConfigurationFromContext? {
// Since we need module, no need to even try to create config with out of it
context?.module ?: return null
return super.createConfigurationFromContext(context)
}
override fun findOrCreateConfigurationFromContext(context: ConfigurationContext?): ConfigurationFromContext? {
if (!isNewTestsModeEnabled()) {
return null
}
return super.findOrCreateConfigurationFromContext(context)
}
// test configuration is always prefered over regular one
override fun shouldReplace(self: ConfigurationFromContext,
other: ConfigurationFromContext) = other.configuration is PythonRunConfiguration
override fun isPreferredConfiguration(self: ConfigurationFromContext?,
other: ConfigurationFromContext) = other.configuration is PythonRunConfiguration
override fun setupConfigurationFromContext(configuration: PyAbstractTestConfiguration?,
context: ConfigurationContext?,
sourceElement: Ref<PsiElement>?): Boolean {
if (sourceElement == null || configuration == null) {
return false
}
val element = sourceElement.get() ?: return false
if (element.containingFile !is PyFile && element !is PsiDirectory) {
return false
}
val location = context?.location
configuration.module = context?.module
configuration.isUseModuleSdk = true
if (location is PyTargetBasedPsiLocation) {
location.target.copyTo(configuration.target)
}
else {
val targetForConfig = PyTestsConfigurationProducer.getTargetForConfig(configuration,
element) ?: return false
targetForConfig.first.copyTo(configuration.target)
// Directory may be set in Default configuration. In that case no need to rewrite it.
if (configuration.workingDirectory.isNullOrEmpty()) {
configuration.workingDirectory = targetForConfig.second
}
}
configuration.setGeneratedName()
return true
}
/**
* Inspects file relative imports, finds farthest and returns folder with imported file
*/
private fun getDirectoryForFileToBeImportedFrom(file: PyFile): PsiDirectory? {
val maxRelativeLevel = file.fromImports.map { it.relativeLevel }.max() ?: 0
var elementFolder = file.parent ?: return null
for (i in 1..maxRelativeLevel) {
elementFolder = elementFolder.parent ?: return null
}
return elementFolder
}
/**
* Creates [ConfigurationTarget] to make configuration work with provided element.
* Also reports working dir what should be set to configuration to work correctly
* @return [target, workingDirectory]
*/
private fun getTargetForConfig(configuration: PyAbstractTestConfiguration,
baseElement: PsiElement): Pair<ConfigurationTarget, String?>? {
var element = baseElement
// Go up until we reach top of the file
// asking configuration about each element if it is supported or not
// If element is supported -- set it as configuration target
do {
if (configuration.couldBeTestTarget(element)) {
when (element) {
is PyQualifiedNameOwner -> { // Function, class, method
val module = configuration.module ?: return null
val elementFile = element.containingFile as? PyFile ?: return null
val workingDirectory = getDirectoryForFileToBeImportedFrom(elementFile) ?: return null
val context = QNameResolveContext(ModuleBasedContextAnchor(module),
evalContext = TypeEvalContext.userInitiated(configuration.project,
null),
folderToStart = workingDirectory.virtualFile)
val parts = element.tryResolveAndSplit(context) ?: return null
val qualifiedName = parts.getElementNamePrependingFile(workingDirectory)
return Pair(ConfigurationTarget(qualifiedName.toString(), PyRunTargetVariant.PYTHON),
workingDirectory.virtualFile.path)
}
is PsiFileSystemItem -> {
val virtualFile = element.virtualFile
val path = virtualFile
val workingDirectory = when (element) {
is PyFile -> getDirectoryForFileToBeImportedFrom(element)
is PsiDirectory -> element
else -> return null
}?.virtualFile?.path ?: return null
return Pair(ConfigurationTarget(path.path, PyRunTargetVariant.PATH), workingDirectory)
}
}
}
element = element.parent ?: break
}
while (element !is PsiDirectory) // if parent is folder, then we are at file level
return null
}
override fun isConfigurationFromContext(configuration: PyAbstractTestConfiguration,
context: ConfigurationContext?): Boolean {
val location = context?.location
if (location is PyTargetBasedPsiLocation) {
// With derived classes several configurations for same element may exist
return location.target == configuration.target
}
val psiElement = context?.psiLocation ?: return false
val targetForConfig = PyTestsConfigurationProducer.getTargetForConfig(configuration,
psiElement) ?: return false
return configuration.target == targetForConfig.first
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
/**
* Mark run configuration field with it to enable saving, resotring and form iteraction
*/
annotation class ConfigField
| apache-2.0 |
artfable/telegram-api-java | src/test/kotlin/com/artfable/telegram/api/AbstractCallbackBehaviourTest.kt | 1 | 1965 | package com.artfable.telegram.api
import com.artfable.telegram.api.keyboard.InlineKeyboardBtn
import com.artfable.telegram.api.service.TelegramSender
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.mockito.Mockito.mock
/**
* @author aveselov
* @since 15/08/2020
*/
internal class AbstractCallbackBehaviourTest {
@Test
fun parse_matchedUpdate() {
val update = Update(1L, callbackQuery = CallbackQuery(2L, data = "key-value"))
val callbackBehaviour = createBehaviour { value, callbackQuery ->
assertEquals("value", value)
assertEquals(update.callbackQuery, callbackQuery)
}
assertTrue(callbackBehaviour.parse(update))
}
@Test
fun parse_matchedUpdateEmpty() {
val update = Update(1L, callbackQuery = CallbackQuery(2L, data = "key"))
val callbackBehaviour = createBehaviour { value, callbackQuery ->
assertEquals("", value)
assertEquals(update.callbackQuery, callbackQuery)
}
assertTrue(callbackBehaviour.parse(update))
}
@Test
fun parse_otherKey() {
val update = Update(1L, callbackQuery = CallbackQuery(2L, data = "key2-value"))
val callbackBehaviour = createBehaviour { _, _ -> throw IllegalArgumentException() }
assertFalse(callbackBehaviour.parse(update))
}
@Test
fun createBtn() {
val callbackBehaviour = createBehaviour()
assertEquals(InlineKeyboardBtn("text", "key-value"), callbackBehaviour.createBtn("text", "value"))
}
private fun createBehaviour(parse: (value: String, callbackQuery: CallbackQuery?) -> Unit = { _, _ -> }): AbstractCallbackBehaviour {
return object : AbstractCallbackBehaviour("key") {
override fun parse(value: String, callbackQuery: CallbackQuery?) {
parse.invoke(value, callbackQuery)
}
}
}
}
| mit |
AIDEA775/UNCmorfi | app/src/main/java/com/uncmorfi/shared/StorageHelper.kt | 1 | 1203 | package com.uncmorfi.shared
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import java.io.IOException
fun Context.saveToStorage(file: String, bitmap: Bitmap?) {
if (bitmap != null) {
try {
val out = this.openFileOutput(file, Context.MODE_PRIVATE)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
out.close()
Log.i("MemoryHelper", "Written $file success")
} catch (e: IOException) {
e.printStackTrace()
Log.e("MemoryHelper", "Error writing barcode in internal memory")
}
}
}
fun Context.readBitmapFromStorage(file: String): Bitmap? {
val bitmap: Bitmap
try {
bitmap = BitmapFactory.decodeStream(this.openFileInput(file))
} catch (e: IOException) {
Log.i("MemoryHelper", "Error reading barcode in internal memory")
return null
}
return bitmap
}
fun Context.deleteFileInStorage(file: String) {
val result = this.deleteFile(file)
if (result)
Log.i("MemoryHelper", "Deleted file $file")
else
Log.e("MemoryHelper", "Error deleting file $file")
}
| gpl-3.0 |
chrisbanes/tivi | common/ui/compose/src/main/java/app/tivi/common/compose/Layout.kt | 1 | 2888 | /*
* Copyright 2021 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 app.tivi.common.compose
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.isFinite
object Layout {
val bodyMargin: Dp
@Composable get() = when (LocalConfiguration.current.screenWidthDp) {
in 0..599 -> 16.dp
in 600..904 -> 32.dp
in 905..1239 -> 0.dp
in 1240..1439 -> 200.dp
else -> 0.dp
}
val gutter: Dp
@Composable get() = when (LocalConfiguration.current.screenWidthDp) {
in 0..599 -> 8.dp
in 600..904 -> 16.dp
in 905..1239 -> 16.dp
in 1240..1439 -> 32.dp
else -> 32.dp
}
val bodyMaxWidth: Dp
@Composable get() = when (LocalConfiguration.current.screenWidthDp) {
in 0..599 -> Dp.Infinity
in 600..904 -> Dp.Infinity
in 905..1239 -> 840.dp
in 1240..1439 -> Dp.Infinity
else -> 1040.dp
}
val columns: Int
@Composable get() = when (LocalConfiguration.current.screenWidthDp) {
in 0..599 -> 4
in 600..904 -> 8
else -> 12
}
}
fun Modifier.bodyWidth() = fillMaxWidth()
.wrapContentWidth(align = Alignment.CenterHorizontally)
.composed {
val bodyMaxWidth = Layout.bodyMaxWidth
if (bodyMaxWidth.isFinite) widthIn(max = bodyMaxWidth) else this
}
.composed {
padding(
WindowInsets.systemBars
.only(WindowInsetsSides.Horizontal)
.asPaddingValues()
)
}
| apache-2.0 |
actions-on-google/actions-on-google-java | src/test/kotlin/com/google/actions/api/AogResponseTest.kt | 1 | 26856 | /*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.actions.api
import com.google.actions.api.impl.AogResponse
import com.google.actions.api.response.ResponseBuilder
import com.google.actions.api.response.helperintent.*
import com.google.api.services.actions_fulfillment.v2.model.*
import com.google.gson.Gson
import com.google.gson.JsonObject
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertNotNull
import org.junit.jupiter.api.assertThrows
import org.testng.annotations.Test
class AogResponseTest {
@Test
fun testBasicResponse() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add("this is a test");
val response = responseBuilder.buildAogResponse()
assertNotNull(response)
val asJson = response.toJson()
assertNotNull(Gson().fromJson(asJson, JsonObject::class.java))
assertEquals("actions.intent.TEXT", response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0)
?.intent)
}
@Test
fun testAskConfirmation() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val confirmation = Confirmation().setConfirmationText("Are you sure?")
val jsonOutput = responseBuilder
.add(confirmation)
.build()
.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val dialogSpec = inputValueData.get("dialogSpec").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.ConfirmationValueSpec",
inputValueData.get("@type").asString)
assertEquals("Are you sure?",
dialogSpec.get("requestConfirmationText").asString)
}
@Test
fun testAskDateTime() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val dateTimePrompt = DateTimePrompt()
.setDatePrompt("What date?")
.setDateTimePrompt("What date and time?")
.setTimePrompt("What time?")
val jsonOutput = responseBuilder
.add(dateTimePrompt)
.build()
.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val dialogSpec = inputValueData.get("dialogSpec").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.DateTimeValueSpec",
inputValueData.get("@type").asString)
assertEquals("What date?",
dialogSpec.get("requestDateText").asString)
assertEquals("What time?",
dialogSpec.get("requestTimeText").asString)
assertEquals("What date and time?",
dialogSpec.get("requestDatetimeText").asString)
}
@Test
fun testAskPermission() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder
.add(Permission()
.setPermissions(arrayOf(PERMISSION_NAME,
PERMISSION_DEVICE_PRECISE_LOCATION))
.setContext("To get your name"))
val response = responseBuilder.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.PermissionValueSpec",
inputValueData.get("@type").asString)
assertEquals("To get your name",
inputValueData.get("optContext").asString)
assertEquals("NAME",
inputValueData.get("permissions").asJsonArray
.get(0).asString)
}
@Test
fun testAskPlace() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val requestPrompt = "Where do you want to have lunch?"
val permissionPrompt = "To find lunch locations"
responseBuilder
.add(Place()
.setRequestPrompt(requestPrompt)
.setPermissionContext(permissionPrompt))
val response = responseBuilder.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val dialogSpec = inputValueData.get("dialog_spec").asJsonObject
val extension = dialogSpec.get("extension").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.PlaceValueSpec",
inputValueData.get("@type").asString)
assertEquals(requestPrompt,
extension.get("requestPrompt").asString)
assertEquals(permissionPrompt,
extension.get("permissionContext").asString)
}
@Test
fun testAskSignIn() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(SignIn())
val response = responseBuilder
.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertNotNull(inputValueData)
}
@Test
fun testAskSignInWithContext() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(SignIn()
.setContext("For testing purposes"))
val response = responseBuilder
.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertNotNull(inputValueData)
assertEquals("For testing purposes",
inputValueData.get("optContext").asString)
}
@Test
fun testListSelect() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val items = ArrayList<ListSelectListItem>()
items.add(ListSelectListItem().setTitle("Android"))
items.add(ListSelectListItem().setTitle("Actions on Google"))
items.add(ListSelectListItem().setTitle("Flutter"))
val response = responseBuilder
.add("placeholder")
.add(SelectionList().setTitle("Topics").setItems(items))
.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val listSelect = inputValueData.get("listSelect").asJsonObject
assertNotNull(listSelect)
assertEquals("Android", listSelect.get("items")
.asJsonArray.get(0)
.asJsonObject
.get("title").asString)
}
@Test
fun testListSelectWithoutSimpleResponse() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val items = ArrayList<ListSelectListItem>()
items.add(ListSelectListItem().setTitle("Android"))
items.add(ListSelectListItem().setTitle("Actions on Google"))
items.add(ListSelectListItem().setTitle("Flutter"))
val response = responseBuilder
.add(SelectionList().setTitle("Topics").setItems(items))
.build()
assertThrows<Exception> {
response.toJson()
}
}
@Test
fun testCarouselSelect() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val items = ArrayList<CarouselSelectCarouselItem>()
items.add(CarouselSelectCarouselItem().setTitle("Android"))
items.add(CarouselSelectCarouselItem().setTitle("Actions on Google"))
items.add(CarouselSelectCarouselItem().setTitle("Flutter"))
val response = responseBuilder
.add("placeholder")
.add(SelectionCarousel().setItems(items))
.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
val carouselSelect = inputValueData.get("carouselSelect")
.asJsonObject
assertNotNull(carouselSelect)
assertEquals("Android", carouselSelect.get("items")
.asJsonArray.get(0)
.asJsonObject
.get("title").asString)
}
@Test
fun testCarouselSelectWithoutSimpleResponse() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val items = ArrayList<CarouselSelectCarouselItem>()
items.add(CarouselSelectCarouselItem().setTitle("Android"))
items.add(CarouselSelectCarouselItem().setTitle("Actions on Google"))
items.add(CarouselSelectCarouselItem().setTitle("Flutter"))
val response = responseBuilder
.add(SelectionCarousel().setItems(items))
.build()
assertThrows<Exception> {
response.toJson()
}
}
@Test
fun testConversationDataIsSet() {
val data = HashMap<String, Any>()
data["favorite_color"] = "white"
val responseBuilder = ResponseBuilder(usesDialogflow = false,
conversationData = data)
responseBuilder
.add("this is a test")
val aogResponse = responseBuilder.build() as AogResponse
val jsonOutput = aogResponse.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val serializedValue = jsonObject.get("conversationToken").asString
assertEquals("white",
gson.fromJson(serializedValue, JsonObject::class.java)
.get("data").asJsonObject
.get("favorite_color").asString)
}
@Test
fun testUserStorageIsSet() {
val map = HashMap<String, Any>()
map["favorite_color"] = "white"
val responseBuilder = ResponseBuilder(usesDialogflow = false,
userStorage = map)
responseBuilder
.add("this is a test")
val aogResponse = responseBuilder.build()
val jsonOutput = aogResponse.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val serializedValue = jsonObject.get("userStorage").asString
assertEquals("white",
gson.fromJson(serializedValue, JsonObject::class.java)
.get("data").asJsonObject
.get("favorite_color").asString)
}
@Test
fun testNewSurfaceHelperIntent() {
val capability = Capability.SCREEN_OUTPUT.value
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(NewSurface()
.setCapability(capability)
.setContext("context")
.setNotificationTitle("notification title"))
val response = responseBuilder.buildAogResponse()
val intent = response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0) as ExpectedIntent
assertEquals("actions.intent.NEW_SURFACE", intent.intent)
val capabilitiesArray =
intent.inputValueData["capabilities"] as Array<String>
assertEquals(capability, capabilitiesArray[0])
}
@Test
fun testRegisterDailyUpdate() {
val updateIntent = "intent.foo"
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(RegisterUpdate().setIntent(updateIntent))
val response = responseBuilder.buildAogResponse()
val intent = response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0) as ExpectedIntent
assertEquals("actions.intent.REGISTER_UPDATE", intent.intent)
assertEquals(updateIntent, intent.inputValueData["intent"])
}
@Test
fun testAddSuggestions() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder
.add("this is a test")
.addSuggestions(arrayOf("one", "two", "three"))
val response = responseBuilder.buildAogResponse()
assertEquals("one", response.appResponse
?.expectedInputs?.get(0)
?.inputPrompt
?.richInitialPrompt
?.suggestions?.get(0)
?.title)
assertEquals("actions.intent.TEXT", response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0)
?.intent)
}
@Test
fun testCompletePurchase() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder
.add("placeholder")
.add(CompletePurchase().setSkuId(SkuId()
.setId("PRODUCT_SKU_ID")
.setSkuType("INAPP")
.setPackageName("play.store.package.name"))
.setDeveloperPayload("OPTIONAL_DEVELOPER_PAYLOAD"))
val response = responseBuilder.build()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.transactions.v3.CompletePurchaseValueSpec",
inputValueData.get("@type").asString)
val skuId = inputValueData.get("skuId").asJsonObject
assertEquals("PRODUCT_SKU_ID", skuId.get("id").asString)
assertEquals("INAPP", skuId.get("skuType").asString)
assertEquals("play.store.package.name", skuId.get("packageName").asString)
assertEquals("OPTIONAL_DEVELOPER_PAYLOAD",
inputValueData.get("developerPayload").asString)
}
@Test
fun testDigitalPurchaseCheck() {
println("testDigitalPurchaseCheck")
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(DigitalPurchaseCheck())
val response = responseBuilder.build()
val jsonOutput = response.toJson()
val intent = response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0) as ExpectedIntent
assertEquals("actions.intent.DIGITAL_PURCHASE_CHECK", intent.intent)
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.transactions.v3.DigitalPurchaseCheckSpec",
inputValueData.get("@type").asString)
}
@Test
fun testTransactionRequirementsCheck() {
val orderOptions = OrderOptions().setRequestDeliveryAddress(false)
val actionProvidedPaymentOptions = ActionProvidedPaymentOptions().setDisplayName("VISA-1234")
.setPaymentType("PAYMENT_CARD")
val paymentOptions = PaymentOptions()
.setActionProvidedOptions(actionProvidedPaymentOptions)
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(TransactionRequirements()
.setOrderOptions(orderOptions)
.setPaymentOptions(paymentOptions))
val response = responseBuilder.buildAogResponse()
val jsonOutput = response.toJson()
val intent = response.appResponse
?.expectedInputs?.get(0)
?.possibleIntents?.get(0) as ExpectedIntent
assertEquals("actions.intent.TRANSACTION_REQUIREMENTS_CHECK", intent.intent)
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertNotNull(inputValueData)
}
@Test
fun testDeliveryAddress() {
val reason = "Reason"
val options = DeliveryAddressValueSpecAddressOptions()
.setReason(reason)
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(DeliveryAddress()
.setAddressOptions(options))
val response = responseBuilder.buildAogResponse()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.DeliveryAddressValueSpec",
inputValueData.get("@type").asString)
val addressOptions = inputValueData.get("addressOptions").asJsonObject
assertEquals(reason, addressOptions.get("reason").asString)
}
@Test
fun testTransactionDecision() {
val orderOptions = OrderOptions().setRequestDeliveryAddress(true)
val paymentType = "PAYMENT_CARD"
val paymentDisplayName = "VISA-1234"
val actionProvidedPaymentOptions = ActionProvidedPaymentOptions()
.setPaymentType(paymentType)
.setDisplayName(paymentDisplayName)
val paymentOptions = PaymentOptions()
.setActionProvidedOptions(actionProvidedPaymentOptions)
val merchantId = "merchant_id"
val merchantName = "merchant_name"
val merchant = Merchant().setId(merchantId).setName(merchantName)
val amount = Money()
.setCurrencyCode("USD")
.setUnits(1L)
.setNanos(990000000)
val price = Price().setAmount(amount).setType("ACTUAL")
val lineItemName = "item_name"
val lineItemId = "item_id"
val lineItemType = "REGULAR"
val lineItem = LineItem().setName(lineItemName)
.setId(lineItemId)
.setPrice(price).setQuantity(1).setType(lineItemType)
val cart = Cart()
.setMerchant(merchant)
.setLineItems(listOf(lineItem))
val totalAmount = Money().setCurrencyCode("USD").setNanos(1)
.setUnits(99L)
val totalPrice = Price().setAmount(totalAmount).setType("ESTIMATE")
val orderId = "order_id"
val proposedOrder = ProposedOrder().setId(orderId)
.setCart(cart).setTotalPrice(totalPrice)
val responseBuilder = ResponseBuilder(usesDialogflow = false)
responseBuilder.add(TransactionDecision()
.setOrderOptions(orderOptions)
.setPaymentOptions(paymentOptions)
.setProposedOrder(proposedOrder))
val response = responseBuilder.buildAogResponse()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertEquals("type.googleapis.com/google.actions.v2.TransactionDecisionValueSpec",
inputValueData.get("@type").asString)
val orderOptionsJson = inputValueData.get("orderOptions").asJsonObject
assertEquals(true, orderOptionsJson.get("requestDeliveryAddress").asBoolean)
val actionProvidedOptionsJson = inputValueData
.get("paymentOptions").asJsonObject
.get("actionProvidedOptions").asJsonObject
assertEquals(paymentDisplayName, actionProvidedOptionsJson.get("displayName").asString)
assertEquals(paymentType, actionProvidedOptionsJson.get("paymentType").asString)
val proposedOrderJson = inputValueData.get("proposedOrder").asJsonObject
assertNotNull(proposedOrderJson)
assertEquals(orderId, proposedOrderJson.get("id").asString)
val cartJson = proposedOrderJson.get("cart").asJsonObject
assertNotNull(cartJson)
val lineItemsJson = cartJson.get("lineItems").asJsonArray
assertNotNull(lineItemsJson)
assert(lineItemsJson.size() == 1)
val lineItemJson = lineItemsJson.get(0).asJsonObject
assertEquals(lineItemId, lineItemJson.get("id").asString)
assertEquals(lineItemName, lineItemJson.get("name").asString)
assertEquals(lineItemType, lineItemJson.get("type").asString)
}
@Test
fun testOrderUpdate() {
val responseBuilder = ResponseBuilder(usesDialogflow = false)
val orderId = "order_id"
val actionOrderId = "action_order_id"
val actionUrl = "http://example.com/customer-service"
val actionTitle = "Customer Service"
val actionType = "CUSTOMER_SERVICE"
val notificationText = "Notification text."
val notificationTitle = "Notification Title"
val orderState = "CREATED"
val orderLabel = "Order created"
val orderUpdate = OrderUpdate().setActionOrderId(actionOrderId)
.setOrderState(
OrderState().setLabel(orderLabel).setState(orderState))
.setReceipt(Receipt().setConfirmedActionOrderId(orderId))
.setOrderManagementActions(
listOf(OrderUpdateAction()
.setButton(Button().setOpenUrlAction(OpenUrlAction()
.setUrl(actionUrl))
.setTitle(actionTitle))
.setType(actionType)))
.setUserNotification(OrderUpdateUserNotification()
.setText(notificationText).setTitle(notificationTitle))
responseBuilder.add(StructuredResponse().setOrderUpdate(orderUpdate))
val response = responseBuilder
.add("placeholder text")
.buildAogResponse()
val jsonOutput = response.toJson()
val gson = Gson()
val jsonObject = gson.fromJson(jsonOutput, JsonObject::class.java)
val inputValueData = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("possibleIntents").asJsonArray.get(0).asJsonObject
.get("inputValueData").asJsonObject
assertNotNull(inputValueData)
val richInitialPrompt = jsonObject
.get("expectedInputs").asJsonArray.get(0).asJsonObject
.get("inputPrompt").asJsonObject.get("richInitialPrompt").asJsonObject
val items = richInitialPrompt.get("items").asJsonArray
assertNotNull(items)
assert(items.size() == 2)
val structuredResponse = items.get(0).asJsonObject.get("structuredResponse").asJsonObject
assertNotNull(structuredResponse)
val orderUpdateJson = structuredResponse.get("orderUpdate").asJsonObject
assertNotNull(orderUpdateJson)
val orderStateJson = orderUpdateJson.get("orderState").asJsonObject
assertEquals(orderState, orderStateJson.get("state").asString)
assertEquals(orderLabel, orderStateJson.get("label").asString)
val orderManagementUpdateActions = orderUpdateJson.get("orderManagementActions").asJsonArray
assertNotNull(orderManagementUpdateActions)
assert(orderManagementUpdateActions.size() == 1)
val updateAction = orderManagementUpdateActions.get(0).asJsonObject
assertEquals(actionType, updateAction.get("type").asString)
val button = updateAction.get("button").asJsonObject
assertEquals(actionTitle, button.get("title").asString)
assertEquals(actionUrl, button.get("openUrlAction").asJsonObject.get("url").asString)
}
}
| apache-2.0 |
wuseal/JsonToKotlinClass | api/src/test/kotlin/wu/seal/jsontokotlinclass/server/GenerateControllerTest.kt | 1 | 9409 | package wu.seal.jsontokotlinclass.server
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import wu.seal.jsontokotlin.PropertyTypeStrategy
import wu.seal.jsontokotlinclass.server.controllers.GenerateController
import wu.seal.jsontokotlinclass.server.models.routes.generate.GenerateRequest
import wu.seal.jsontokotlin.DefaultValueStrategy as DefaultValueStrategy1
import wu.seal.jsontokotlin.TargetJsonConverter as TargetJsonConverter1
class GenerateControllerTest {
lateinit var mockMvc: MockMvc
lateinit var objectMapper: ObjectMapper
@Before
fun setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(
GenerateController()
).build()
this.objectMapper = ObjectMapper()
}
@Test
fun simpleTest() {
val request = GenerateRequest(
"""
{"name":"theapache64"}
""".trimIndent(),
className = "Person",
annotationLib = TargetJsonConverter1.MoShi.name,
defaultValueStrategy = DefaultValueStrategy1.AvoidNull.name,
propertyTypeStrategy = PropertyTypeStrategy.Nullable.name,
indent = 8,
commentsEnabled = true,
createAnnotationOnlyWhenNeededEnabled = false,
enableVarProperties = true,
forceInitDefaultValueWithOriginJsonValueEnabled = false,
forcePrimitiveTypeNonNullableEnabled = true,
innerClassModelEnabled = true,
keepAnnotationOnClassAndroidXEnabled = false,
keepAnnotationOnClassEnabled = true,
mapTypeEnabled = true,
orderByAlphabeticEnabled = true,
parcelableSupportEnabled = false,
propertyAndAnnotationInSameLineEnabled = false,
classSuffix = null,
packageName = null,
parentClassTemplate = null,
propertyPrefix = null,
propertySuffix = null
)
val requestJson = objectMapper.writeValueAsString(request)
mockMvc.perform(post("/generate").content(requestJson).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk)
.andExpect(content().string("{\"data\":{\"code\":\"data class Person(\\n val name: String\\n)\"},\"error\":false,\"error_code\":-1,\"message\":\"OK\"}"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
}
@Test
fun complexTest() {
val controller = GenerateController()
val request = GenerateRequest(
"""
{
"glossary":{
"title":"example glossary",
"GlossDiv":{
"title":"S",
"GlossList":{
"GlossEntry":{
"ID":"SGML",
"SortAs":"SGML",
"GlossTerm":"Standard Generalized Markup Language",
"Acronym":"SGML",
"Abbrev":"ISO 8879:1986",
"GlossDef":{
"para":"A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso":[
"GML",
"XML"
]
},
"GlossSee":"markup"
}
}
}
}
}
""".trimIndent(),
className = "Example",
annotationLib = TargetJsonConverter1.MoShi.name,
defaultValueStrategy = DefaultValueStrategy1.AvoidNull.name,
propertyTypeStrategy = PropertyTypeStrategy.Nullable.name,
indent = 8,
commentsEnabled = true,
createAnnotationOnlyWhenNeededEnabled = false,
enableVarProperties = true,
forceInitDefaultValueWithOriginJsonValueEnabled = false,
forcePrimitiveTypeNonNullableEnabled = true,
innerClassModelEnabled = true,
keepAnnotationOnClassAndroidXEnabled = false,
keepAnnotationOnClassEnabled = true,
mapTypeEnabled = true,
orderByAlphabeticEnabled = true,
parcelableSupportEnabled = false,
propertyAndAnnotationInSameLineEnabled = false,
classSuffix = "MyClassSuffix",
packageName = "com.my.package.name",
parentClassTemplate = null,
propertyPrefix = "prop_prefix_",
propertySuffix = "_prop_suffix"
)
val response = controller.generate(request)
val actualOutput = ObjectMapper().writeValueAsString(response)
println(actualOutput)
val expectedOutput = """
{"data":{"code":"package com.my.package.name\n\n\nimport com.squareup.moshi.Json\nimport android.support.annotation.Keep\n\n@Keep\ndata class ExampleMyClassSuffix(\n @Json(name = \"glossary\")\n var prop_prefix_GlossaryProp_prefix_: GlossaryMyClassSuffix? = GlossaryMyClassSuffix()\n) {\n @Keep\n data class GlossaryMyClassSuffix(\n @Json(name = \"GlossDiv\")\n var prop_prefix_GlossDivProp_prefix_: GlossDivMyClassSuffix? = GlossDivMyClassSuffix(),\n @Json(name = \"title\")\n var prop_prefix_TitleProp_prefix_: String? = \"\" // example glossary\n ) {\n @Keep\n data class GlossDivMyClassSuffix(\n @Json(name = \"GlossList\")\n var prop_prefix_GlossListProp_prefix_: GlossListMyClassSuffix? = GlossListMyClassSuffix(),\n @Json(name = \"title\")\n var prop_prefix_TitleProp_prefix_: String? = \"\" // S\n ) {\n @Keep\n data class GlossListMyClassSuffix(\n @Json(name = \"GlossEntry\")\n var prop_prefix_GlossEntryProp_prefix_: GlossEntryMyClassSuffix? = GlossEntryMyClassSuffix()\n ) {\n @Keep\n data class GlossEntryMyClassSuffix(\n @Json(name = \"Abbrev\")\n var prop_prefix_AbbrevProp_prefix_: String? = \"\", // ISO 8879:1986\n @Json(name = \"Acronym\")\n var prop_prefix_AcronymProp_prefix_: String? = \"\", // SGML\n @Json(name = \"GlossDef\")\n var prop_prefix_GlossDefProp_prefix_: GlossDefMyClassSuffix? = GlossDefMyClassSuffix(),\n @Json(name = \"GlossSee\")\n var prop_prefix_GlossSeeProp_prefix_: String? = \"\", // markup\n @Json(name = \"GlossTerm\")\n var prop_prefix_GlossTermProp_prefix_: String? = \"\", // Standard Generalized Markup Language\n @Json(name = \"ID\")\n var prop_prefix_IDProp_prefix_: String? = \"\", // SGML\n @Json(name = \"SortAs\")\n var prop_prefix_SortAsProp_prefix_: String? = \"\" // SGML\n ) {\n @Keep\n data class GlossDefMyClassSuffix(\n @Json(name = \"GlossSeeAlso\")\n var prop_prefix_GlossSeeAlsoProp_prefix_: List<String?>? = listOf(),\n @Json(name = \"para\")\n var prop_prefix_ParaProp_prefix_: String? = \"\" // A meta-markup language, used to create markup languages such as DocBook.\n )\n }\n }\n }\n }\n}"},"error":false,"error_code":-1,"message":"OK"}
""".trimIndent()
assertEquals(expectedOutput, actualOutput)
}
} | gpl-3.0 |
android/privacy-sandbox-samples | Fledge/FledgeKotlin/app/src/main/java/com/example/adservices/samples/fledge/sampleapp/AdSelectionWrapper.kt | 1 | 9589 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.adservices.samples.fledge.sampleapp
import android.adservices.adselection.AdSelectionConfig
import android.adservices.adselection.AdSelectionOutcome
import android.adservices.adselection.AddAdSelectionOverrideRequest
import android.adservices.adselection.ReportImpressionRequest
import android.adservices.common.AdSelectionSignals
import android.adservices.common.AdTechIdentifier
import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.annotation.RequiresApi
import com.example.adservices.samples.fledge.clients.AdSelectionClient
import com.example.adservices.samples.fledge.clients.TestAdSelectionClient
import com.google.common.util.concurrent.FutureCallback
import com.google.common.util.concurrent.Futures
import java.util.concurrent.Executor
import java.util.function.Consumer
import java.util.stream.Collectors
/**
* Wrapper for the FLEDGE Ad Selection API. This wrapper is opinionated and makes several
* choices such as running impression reporting immediately after every successful ad auction or leaving
* the ad signals empty to limit the complexity that is exposed the user.
*
* @param buyers A list of buyers for the auction.
* @param seller The name of the seller for the auction
* @param decisionUri The URI to retrieve the seller scoring and reporting logic from
* @param trustedScoringUri The URI to retrieve the trusted scoring signals
* @param context The application context.
* @param executor An executor to use with the FLEDGE API calls.
*/
@RequiresApi(api = 34)
class AdSelectionWrapper(
buyers: List<AdTechIdentifier>, seller: AdTechIdentifier, decisionUri: Uri, trustedScoringUri: Uri, context: Context,
executor: Executor
) {
private var adSelectionConfig: AdSelectionConfig
private val adClient: AdSelectionClient
private val executor: Executor
private val overrideClient: TestAdSelectionClient
/**
* Runs ad selection and passes a string describing its status to the input receivers. If ad
* selection succeeds, also report impressions.
* @param statusReceiver A consumer function that is run after ad selection and impression reporting
* with a string describing how the auction and reporting went.
* @param renderUriReceiver A consumer function that is run after ad selection with a message describing the render URI
* or lack thereof.
*/
fun runAdSelection(statusReceiver: Consumer<String>, renderUriReceiver: Consumer<String>) {
try {
Futures.addCallback(adClient.selectAds(adSelectionConfig),
object : FutureCallback<AdSelectionOutcome?> {
override fun onSuccess(adSelectionOutcome: AdSelectionOutcome?) {
statusReceiver.accept("Ran ad selection! ID: " + adSelectionOutcome!!.adSelectionId)
renderUriReceiver.accept("Would display ad from " + adSelectionOutcome.renderUri)
reportImpression(adSelectionOutcome.adSelectionId,
statusReceiver)
}
override fun onFailure(e: Throwable) {
statusReceiver.accept("Error when running ad selection: " + e.message)
renderUriReceiver.accept("Ad selection failed -- no ad to display")
Log.e(TAG, "Exception during ad selection", e)
}
}, executor)
} catch (e: Exception) {
statusReceiver.accept("Got the following exception when trying to run ad selection: $e")
renderUriReceiver.accept("Ad selection failed -- no ad to display")
Log.e(TAG, "Exception calling runAdSelection", e)
}
}
/**
* Helper function of [.runAdSelection]. Runs impression reporting.
*
* @param adSelectionId The auction to report impression on.
* @param statusReceiver A consumer function that is run after impression reporting
* with a string describing how the auction and reporting went.
*/
fun reportImpression(
adSelectionId: Long,
statusReceiver: Consumer<String>
) {
val request = ReportImpressionRequest(adSelectionId, adSelectionConfig)
Futures.addCallback(adClient.reportImpression(request),
object : FutureCallback<Void?> {
override fun onSuccess(unused: Void?) {
statusReceiver.accept("Reported impressions from ad selection")
}
override fun onFailure(e: Throwable) {
statusReceiver.accept("Error when reporting impressions: " + e.message)
Log.e(TAG, e.toString(), e)
}
}, executor)
}
/**
* Overrides remote info for an ad selection config.
*
* @param decisionLogicJS The overriding decision logic javascript
* @param statusReceiver A consumer function that is run after the API call and returns a
* string indicating the outcome of the call.
*/
fun overrideAdSelection(statusReceiver: Consumer<String?>, decisionLogicJS: String?, trustedScoringSignals: AdSelectionSignals?) {
val request = AddAdSelectionOverrideRequest(adSelectionConfig, decisionLogicJS!!, trustedScoringSignals!!);
Futures.addCallback(overrideClient.overrideAdSelectionConfigRemoteInfo(request),
object : FutureCallback<Void?> {
override fun onSuccess(unused: Void?) {
statusReceiver.accept("Added override for ad selection")
}
override fun onFailure(e: Throwable) {
statusReceiver.accept("Error when adding override for ad selection " + e.message)
Log.e(TAG, e.toString(), e)
}
}, executor)
}
/**
* Resets all ad selection overrides.
*
* @param statusReceiver A consumer function that is run after the API call and returns a
* string indicating the outcome of the call.
*/
fun resetAdSelectionOverrides(statusReceiver: Consumer<String?>) {
Futures.addCallback(overrideClient.resetAllAdSelectionConfigRemoteOverrides(),
object : FutureCallback<Void?> {
override fun onSuccess(unused: Void?) {
statusReceiver.accept("Reset ad selection overrides")
}
override fun onFailure(e: Throwable) {
statusReceiver.accept("Error when resetting all ad selection overrides " + e.message)
Log.e(TAG, e.toString(), e)
}
}, executor)
}
/**
* Resets the {code adSelectionConfig} with the new decisionUri associated with this `AdSelectionWrapper`.
* To be used when switching back and forth between dev overrides/mock server states.
*
* @param buyers the list of buyers to be used
* @param seller the seller to be users
* @param decisionUri the new {@code Uri} to be used
* @param trustedScoringUri the scoring signal uri to be used.
*/
fun resetAdSelectionConfig(
buyers: List<AdTechIdentifier>,
seller: AdTechIdentifier,
decisionUri: Uri,
trustedScoringUri: Uri) {
adSelectionConfig = AdSelectionConfig.Builder()
.setSeller(seller)
.setDecisionLogicUri(decisionUri)
.setCustomAudienceBuyers(buyers)
.setAdSelectionSignals(AdSelectionSignals.EMPTY)
.setSellerSignals(AdSelectionSignals.EMPTY)
.setPerBuyerSignals(buyers.stream()
.collect(Collectors.toMap(
{ buyer: AdTechIdentifier -> buyer },
{ AdSelectionSignals.EMPTY })))
.setTrustedScoringSignalsUri(trustedScoringUri)
.build()
}
/**
* Initializes the ad selection wrapper with a specific seller, list of buyers, and decision
* endpoint.
*/
init {
adSelectionConfig = AdSelectionConfig.Builder()
.setSeller(seller)
.setDecisionLogicUri(decisionUri)
.setCustomAudienceBuyers(buyers)
.setAdSelectionSignals(AdSelectionSignals.EMPTY)
.setSellerSignals(AdSelectionSignals.EMPTY)
.setPerBuyerSignals(buyers.stream()
.collect(Collectors.toMap(
{ buyer: AdTechIdentifier -> buyer },
{ AdSelectionSignals.EMPTY })))
.setTrustedScoringSignalsUri(trustedScoringUri)
.build()
adClient = AdSelectionClient.Builder().setContext(context).setExecutor(executor).build()
overrideClient = TestAdSelectionClient.Builder()
.setContext(context)
.setExecutor(executor)
.build()
this.executor = executor
}
} | apache-2.0 |
Jire/Strukt | src/main/kotlin/org/jire/strukt/Strukts.kt | 1 | 6450 | /*
* Copyright 2020 Thomas Nappo (Jire)
*
* 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.jire.strukt
import org.jire.strukt.internal.*
import java.io.File
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSubclassOf
interface Strukts {
val type: KClass<*>
var size: Long
var nextIndex: Long
val fields: List<Field>
fun addField(field: Field)
fun free(): Boolean
fun allocate(): Long
fun free(address: Long): Boolean
fun free(strukt: Strukt) = free(strukt.address)
operator fun invoke() = allocate()
fun byteField(default: Byte, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): ByteField =
InternalByteField(type, this, threadSafeType, default)
fun shortField(default: Short, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): ShortField =
InternalShortField(type, this, threadSafeType, default)
fun intField(default: Int, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): IntField =
InternalIntField(type, this, threadSafeType, default)
fun longField(default: Long, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): LongField =
InternalLongField(type, this, threadSafeType, default)
fun floatField(default: Float, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): FloatField =
InternalFloatField(type, this, threadSafeType, default)
fun doubleField(default: Double, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): DoubleField =
InternalDoubleField(type, this, threadSafeType, default)
fun charField(default: Char, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): CharField =
InternalCharField(type, this, threadSafeType, default)
fun booleanField(default: Boolean, threadSafeType: ThreadSafeType = ThreadSafeType.NONE): BooleanField =
InternalBooleanField(type, this, threadSafeType, default)
fun <E : Enum<E>> enumField(
default: E,
threadSafeType: ThreadSafeType = ThreadSafeType.NONE,
values: Array<E> = default.javaClass.enumConstants
): EnumField<E> =
InternalEnumField(type, this, threadSafeType, default, values)
operator fun invoke(default: Byte) = byteField(default)
operator fun invoke(default: Short) = shortField(default)
operator fun invoke(default: Int) = intField(default)
operator fun invoke(default: Long) = longField(default)
operator fun invoke(default: Float) = floatField(default)
operator fun invoke(default: Double) = doubleField(default)
operator fun invoke(default: Char) = charField(default)
operator fun invoke(default: Boolean) = booleanField(default)
operator fun <E : Enum<E>> invoke(default: E, values: Array<E> = default.javaClass.enumConstants) =
enumField(default, values = values)
operator fun Byte.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(byteField(this, prop.threadSafeType))
operator fun Short.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(shortField(this, prop.threadSafeType))
operator fun Int.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(intField(this, prop.threadSafeType))
operator fun Long.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(longField(this, prop.threadSafeType))
operator fun Float.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(floatField(this, prop.threadSafeType))
operator fun Double.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(doubleField(this, prop.threadSafeType))
operator fun Char.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(charField(this, prop.threadSafeType))
operator fun Boolean.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(booleanField(this, prop.threadSafeType))
operator fun <E : Enum<E>> E.provideDelegate(thisRef: Strukts, prop: KProperty<*>) =
FieldDelegate(enumField(this, prop.threadSafeType))
fun toString(address: Long): String
fun toString(strukt: Strukt) = toString(strukt.address)
companion object {
private val KProperty<*>.threadSafeType
get() = annotations
.firstOrNull { it::class.isSubclassOf(ThreadSafe::class) }
?.let { it as ThreadSafe }?.threadSafeType
?: ThreadSafeType.NONE
class FieldDelegate<F : Field>(val delegatedTo: F) {
operator fun getValue(strukts: Strukts, property: KProperty<*>) = delegatedTo
}
const val DEFAULT_ELASTIC_CAPACITY = 1024L
const val DEFAULT_ELASTIC_GROWTH_FACTOR = 2.0
@JvmStatic
fun fixed(type: KClass<*>, capacity: Long): Strukts = FixedStrukts(type, capacity, null)
@JvmStatic
fun fixed(type: Class<*>, capacity: Long): Strukts = fixed(type.kotlin, capacity)
@JvmStatic
fun fixed(type: KClass<*>, capacity: Long, persistedTo: File): Strukts =
FixedStrukts(type, capacity, persistedTo)
@JvmStatic
fun fixed(type: Class<*>, capacity: Long, persistedTo: File): Strukts =
fixed(type.kotlin, capacity, persistedTo)
@JvmStatic
fun fixed(type: KClass<*>, capacity: Long, persistedToPathname: String): Strukts =
FixedStrukts(type, capacity, File(persistedToPathname))
@JvmStatic
fun fixed(type: Class<*>, capacity: Long, persistedToPathname: String): Strukts =
fixed(type.kotlin, capacity, persistedToPathname)
@JvmStatic
fun pointed(type: KClass<*>): Strukts = PointedStrukts(type)
@JvmStatic
fun pointed(type: Class<*>): Strukts = pointed(type.kotlin)
@JvmStatic
@JvmOverloads
fun elastic(
type: KClass<*>,
initialCapacity: Long = DEFAULT_ELASTIC_CAPACITY,
growthFactor: Double = DEFAULT_ELASTIC_GROWTH_FACTOR
): Strukts = ElasticStrukts(type, initialCapacity, growthFactor)
@JvmStatic
@JvmOverloads
fun elastic(
type: Class<*>,
initialCapacity: Long = DEFAULT_ELASTIC_CAPACITY,
growthFactor: Double = DEFAULT_ELASTIC_GROWTH_FACTOR
): Strukts = elastic(type.kotlin, initialCapacity, growthFactor)
}
} | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.