repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/ClosedHistory.kt
1
2748
/* ParaTask Copyright (C) 2017 Nick Robinson> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.project import javafx.scene.input.KeyCodeCombination import uk.co.nickthecoder.paratask.Tool /** * Remembers tabs that have been closed, so that they can be opened again. */ class ClosedHistory { val items = mutableListOf<ClosedTab>() fun remember(projectTab: ProjectTab) { val closedTab = ClosedTab(projectTab) items.add(closedTab) } fun canRestore(): Boolean { return items.isNotEmpty() } fun restore(projectTabs: ProjectTabs) { val closedTab = items.removeAt(items.size - 1) closedTab.createTab(projectTabs) } } class ClosedTab(projectTab: ProjectTab) { val leftHistory: Pair<List<History.Moment>, Int> val rightHistory: Pair<List<History.Moment>, Int>? val tabTemplate: String val tabShortcut: KeyCodeCombination? // The index of the tab. 0 for the first tab etc. val index: Int init { projectTab.left.history.push(projectTab.left.toolPane.tool) projectTab.right?.history?.push(projectTab.right?.toolPane?.tool!!) leftHistory = projectTab.left.history.save() rightHistory = projectTab.right?.history?.save() tabTemplate = projectTab.tabTemplate tabShortcut = projectTab.tabShortcut index = projectTab.projectTabs.indexOf(projectTab) } fun createTab(projectTabs: ProjectTabs): ProjectTab { val leftTool = createTool(leftHistory) val tab = projectTabs.addTool(index, leftTool) tab.tabTemplate = tabTemplate tab.tabShortcut = tabShortcut leftTool.toolPane?.halfTab?.history?.restore(leftHistory.first, leftHistory.second) rightHistory?.let { val rightTool = createTool(it) tab.split(rightTool) rightTool.toolPane?.halfTab?.history?.restore(rightHistory.first, rightHistory.second) } return tab } private fun createTool(history: Pair<List<History.Moment>, Int>): Tool { val moment = history.first[history.second] return moment.tool } }
gpl-3.0
62de34260953b755862c9277d26df5ed
28.548387
98
0.700873
4.234206
false
false
false
false
rcgroot/open-gpstracker-ng
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/activityrecognition/ActivityRecognitionIntentService.kt
1
2032
package nl.sogeti.android.gpstracker.ng.features.activityrecognition import android.app.IntentService import android.content.Intent import android.net.Uri import com.google.android.gms.location.ActivityTransitionResult import com.google.android.gms.location.DetectedActivity import nl.sogeti.android.gpstracker.ng.features.trackedit.TrackTypeDescriptions import nl.sogeti.android.gpstracker.ng.features.trackedit.TrackTypeDescriptions.Companion.VALUE_TYPE_BIKE import nl.sogeti.android.gpstracker.ng.features.trackedit.TrackTypeDescriptions.Companion.VALUE_TYPE_CAR import nl.sogeti.android.gpstracker.ng.features.trackedit.TrackTypeDescriptions.Companion.VALUE_TYPE_DEFAULT import nl.sogeti.android.gpstracker.ng.features.trackedit.TrackTypeDescriptions.Companion.VALUE_TYPE_RUN import nl.sogeti.android.gpstracker.ng.features.trackedit.TrackTypeDescriptions.Companion.VALUE_TYPE_WALK import nl.sogeti.android.gpstracker.ng.features.trackedit.saveTrackType internal const val EXTRA_TRACK_URI = "EXTRA_TRACK_URI" class ActivityRecognitionIntentService : IntentService("ActivityRecognitionIntentService") { override fun onHandleIntent(intent: Intent?) { val result = ActivityTransitionResult.extractResult(intent) val trackUri = intent?.getParcelableExtra<Uri>(EXTRA_TRACK_URI) if (result != null && trackUri != null) { val trackType = when (result.transitionEvents.last().activityType) { DetectedActivity.WALKING -> TrackTypeDescriptions.trackTypeForContentType(VALUE_TYPE_WALK) DetectedActivity.RUNNING -> TrackTypeDescriptions.trackTypeForContentType(VALUE_TYPE_RUN) DetectedActivity.ON_BICYCLE -> TrackTypeDescriptions.trackTypeForContentType(VALUE_TYPE_BIKE) DetectedActivity.IN_VEHICLE -> TrackTypeDescriptions.trackTypeForContentType(VALUE_TYPE_CAR) else -> TrackTypeDescriptions.trackTypeForContentType(VALUE_TYPE_DEFAULT) } trackUri.saveTrackType(trackType) } } }
gpl-3.0
df2b7297d6a4b3cd5b4aa80ed797bfb3
58.764706
109
0.786909
4.398268
false
false
false
false
aglne/mycollab
mycollab-services/src/main/java/com/mycollab/module/project/domain/SimpleBug.kt
3
3246
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.project.domain import com.mycollab.common.i18n.OptionI18nEnum.StatusI18nEnum import com.mycollab.core.arguments.NotBindable import com.mycollab.core.utils.StringUtils import com.mycollab.core.utils.StringUtils.isBlank import java.time.LocalDate /** * @author MyCollab Ltd. * @since 1.0 */ class SimpleBug : BugWithBLOBs() { var loguserFullName: String = "" get() = if (isBlank(field)) { StringUtils.extractNameFromEmail(createduser) } else field var loguserAvatarId: String? = null var assignUserAvatarId: String? = null var assignuserFullName: String = "" get() { if (isBlank(field)) { val displayName = assignuser return StringUtils.extractNameFromEmail(displayName) } return field } var projectname: String? = null var projectShortName: String? = null var numComments: Int? = null var billableHours: Double? = null var nonBillableHours: Double? = null var numFollowers: Int? = null @NotBindable var affectedVersions: List<Version>? = null @NotBindable var fixedVersions: List<Version>? = null @NotBindable var components: List<Component>? = null var comment: String? = null var milestoneName: String? = null val isCompleted: Boolean get() = isCompleted(this) val isOverdue: Boolean get() = isOverdue(this) var ticketKey:Int? = null val dueDateRoundPlusOne: LocalDate? get() { return duedate?.plusDays(1) } var parentTicketKey: Int? = null var parentTicketId: Int? = null var parentTicketType: String? = null enum class Field { selected, components, fixedVersions, affectedVersions, loguserFullName, assignuserFullName, milestoneName; fun equalTo(value: Any): Boolean = name == value } companion object { private const val serialVersionUID = 1L @JvmStatic fun isCompleted(bug: BugWithBLOBs): Boolean = StatusI18nEnum.Verified.name == bug.status @JvmStatic fun isOverdue(bug: BugWithBLOBs): Boolean { if (StatusI18nEnum.Verified.name == bug.status) { return false } return when { bug.duedate != null -> { LocalDate.now().isAfter(bug.duedate) } else -> false } } } }
agpl-3.0
1b364cf41bcad103d8e16b2b8ed0cc94
27.217391
96
0.636055
4.385135
false
false
false
false
cbeust/kobalt
kobalt/src/Build.kt
1
11511
import com.beust.kobalt.* import com.beust.kobalt.api.Project import com.beust.kobalt.api.annotation.Task import com.beust.kobalt.plugin.application.application import com.beust.kobalt.plugin.java.javaCompiler import com.beust.kobalt.plugin.kotlin.kotlinCompiler import com.beust.kobalt.plugin.packaging.assemble import com.beust.kobalt.plugin.publish.autoGitTag import com.beust.kobalt.plugin.publish.bintray import com.beust.kobalt.plugin.publish.github import org.apache.maven.model.Developer import org.apache.maven.model.License import org.apache.maven.model.Model import org.apache.maven.model.Scm import java.io.File import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream val bs = buildScript { repos("https://dl.bintray.com/cbeust/maven") } object Versions { val kotlin = "1.3.50" val okhttp = "3.9.1" val okio = "1.13.0" val retrofit = "2.3.0" val gson = "2.8.2" val guice = "4.2.2" val maven = "3.5.2" val mavenResolver = "1.1.0" val slf4j = "1.7.3" val aether = "1.0.2.v20150114" val testng = "6.12" val jcommander = "1.72" // JUnit 5 val junit = "4.12" val junitPlatform = "1.1.0" val junitJupiter = "5.1.0" } fun mavenResolver(vararg m: String) = m.map { "org.apache.maven.resolver:maven-resolver-$it:${Versions.mavenResolver}" } .toTypedArray() fun aether(vararg m: String) = m.map { "org.eclipse.aether:aether-$it:${Versions.aether}" } .toTypedArray() val wrapper = project { name = "kobalt-wrapper" group = "com.beust" artifactId = name version = readVersion() directory = "modules/wrapper" javaCompiler { args("-source", "1.7", "-target", "1.7") } assemble { jar { } jar { name = projectName + ".jar" manifest { attributes("Main-Class", "com.beust.kobalt.wrapper.Main") } } } application { mainClass = "com.beust.kobalt.wrapper.Main" } bintray { publish = true sign = true } pom = createPom(name, "Wrapper for Kobalt") } val kobaltPluginApi = project { name = "kobalt-plugin-api" group = "com.beust" artifactId = name version = readVersion() directory = "modules/kobalt-plugin-api" description = "A build system in Kotlin" url = "https://beust.com/kobalt" pom = createPom(name, "A build system in Kotlin") dependencies { compile( "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}", "com.google.inject:guice:${Versions.guice}", "com.google.inject.extensions:guice-assistedinject:4.1.0", "javax.inject:javax.inject:1", "com.google.guava:guava:27.0.1-jre", "org.apache.maven:maven-model:${Versions.maven}", "io.reactivex:rxjava:1.3.3", "com.squareup.okio:okio:${Versions.okio}", "com.google.code.gson:gson:${Versions.gson}", "com.squareup.okhttp3:okhttp:${Versions.okhttp}", "com.squareup.retrofit2:retrofit:${Versions.retrofit}", "com.squareup.retrofit2:converter-gson:${Versions.retrofit}", "com.beust:jcommander:${Versions.jcommander}", "org.eclipse.jgit:org.eclipse.jgit:4.9.0.201710071750-r", "org.slf4j:slf4j-simple:${Versions.slf4j}", *mavenResolver("api", "spi", "util", "impl", "connector-basic", "transport-http", "transport-file"), "org.apache.maven:maven-aether-provider:3.3.9", "org.testng.testng-remote:testng-remote:1.3.2", "org.testng:testng:${Versions.testng}", "org.junit.platform:junit-platform-surefire-provider:${Versions.junitPlatform}", "org.junit.platform:junit-platform-runner:${Versions.junitPlatform}", "org.junit.platform:junit-platform-engine:${Versions.junitPlatform}", "org.junit.platform:junit-platform-console:${Versions.junitPlatform}", "org.junit.jupiter:junit-jupiter-engine:${Versions.junitJupiter}", "org.junit.vintage:junit-vintage-engine:${Versions.junitJupiter}", "org.apache.commons:commons-compress:1.15", "commons-io:commons-io:2.6", // Java 9 "javax.xml.bind:jaxb-api:2.3.0" ) exclude(*aether("impl", "spi", "util", "api")) } assemble { mavenJars { fatJar = true manifest { attributes("Main-Class", "com.beust.kobalt.MainKt") } } } kotlinCompiler { args("nowarn") } bintray { publish = true } } val kobaltApp = project(kobaltPluginApi, wrapper) { name = "kobalt" group = "com.beust" artifactId = name version = readVersion() dependencies { // Used by the plugins compile("org.jetbrains.kotlin:kotlin-compiler-embeddable:${Versions.kotlin}") // Used by the main app compile( "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}", "com.github.spullara.mustache.java:compiler:0.9.5", "javax.inject:javax.inject:1", "com.google.inject:guice:${Versions.guice}", "com.google.inject.extensions:guice-assistedinject:${Versions.guice}", "com.beust:jcommander:${Versions.jcommander}", "org.apache.maven:maven-model:${Versions.maven}", "com.google.code.findbugs:jsr305:3.0.2", "com.google.code.gson:gson:${Versions.gson}", "com.squareup.retrofit2:retrofit:${Versions.retrofit}", "com.squareup.retrofit2:converter-gson:${Versions.retrofit}", // "com.squareup.okhttp3:okhttp-ws:3.4.2", "biz.aQute.bnd:biz.aQute.bndlib:3.5.0", *mavenResolver("spi"), "com.squareup.okhttp3:logging-interceptor:3.9.0", "com.sparkjava:spark-core:2.6.0", "org.codehaus.groovy:groovy:2.4.12", // Java 9 "javax.xml.bind:jaxb-api:2.3.0", "com.sun.xml.bind:jaxb-impl:2.3.0", "com.sun.xml.bind:jaxb-core:2.3.0", "com.sun.activation:javax.activation:1.2.0" // "org.eclipse.jetty:jetty-server:${Versions.jetty}", // "org.eclipse.jetty:jetty-servlet:${Versions.jetty}", // "org.glassfish.jersey.core:jersey-server:${Versions.jersey}", // "org.glassfish.jersey.containers:jersey-container-servlet-core:${Versions.jersey}", // "org.glassfish.jersey.containers:jersey-container-jetty-http:${Versions.jersey}", // "org.glassfish.jersey.media:jersey-media-moxy:${Versions.jersey}", // "org.wasabi:wasabi:0.1.182" ) } dependenciesTest { compile("org.jetbrains.kotlin:kotlin-test:${Versions.kotlin}", "org.testng:testng:${Versions.testng}", "org.assertj:assertj-core:3.8.0", *mavenResolver("util") ) } assemble { mavenJars { fatJar = true manifest { attributes("Main-Class", "com.beust.kobalt.MainKt") } } zip { val dir = "kobalt-$version" val files = listOf( "dist", "$dir/bin", "kobaltw", "dist", "$dir/bin", "kobaltw.bat", "$buildDirectory/libs", "$dir/kobalt/wrapper", "$projectName-$version.jar", "modules/wrapper/$buildDirectory/libs", "$dir/kobalt/wrapper", "$projectName-wrapper.jar") (0 .. files.size - 1 step 3).forEach { i -> include(from(files[i]), to(files[i + 1]), files[i + 2]) } // Package the sources val currentDir = Paths.get(".").toAbsolutePath().normalize().toString() zipFolders("$currentDir/$buildDirectory/libs/all-sources/$projectName-$version-sources.jar", "$currentDir/$directory/src/main/kotlin", "$currentDir/${kobaltPluginApi.directory}/src/main/kotlin") include(from("$buildDirectory/libs/all-sources"), to("$dir/kobalt/wrapper"), "$projectName-$version-sources.jar") } } kotlinCompiler { args("nowarn") } bintray { publish = true } github { file("$buildDirectory/libs/$name-$version.zip", "$name/$version/$name-$version.zip") } test { args("-log", "2", "src/test/resources/testng.xml") } autoGitTag { enabled = true } } fun zipFolders(zipFilePath: String, vararg foldersPath: String) { val zip = Paths.get(zipFilePath) Files.deleteIfExists(zip) Files.createDirectories(zip.parent) val zipPath = Files.createFile(zip) ZipOutputStream(Files.newOutputStream(zipPath)).use { foldersPath.map {Paths.get(it)}.forEach { folderPath -> Files.walk(folderPath) .filter { path -> !Files.isDirectory(path) } .forEach { path -> val zipEntry = ZipEntry(folderPath.relativize(path).toString()) try { it.putNextEntry(zipEntry) Files.copy(path, it) it.closeEntry() } catch (e: Exception) { } } } } } fun readVersion() : String { val localFile = listOf("src/main/resources/kobalt.properties", homeDir("kotlin", "kobalt", "src/main/resources/kobalt.properties")).first { File(it).exists() } with(java.util.Properties()) { load(java.io.FileReader(localFile)) return getProperty("kobalt.version") } } @Task(name = "copyVersionForWrapper", reverseDependsOn = arrayOf("assemble"), runAfter = arrayOf("clean")) fun taskCopyVersionForWrapper(project: Project) : TaskResult { if (project.name == "kobalt-wrapper") { val toString = "modules/wrapper/kobaltBuild/classes" File(toString).mkdirs() val from = Paths.get("src/main/resources/kobalt.properties") val to = Paths.get("$toString/kobalt.properties") // Only copy if necessary so we don't break incremental compilation if (! to.toFile().exists() || (from.toFile().readLines() != to.toFile().readLines())) { Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING) } } return TaskResult() } fun createPom(projectName: String, projectDescription: String) = Model().apply { name = projectName description = projectDescription url = "https://beust.com/kobalt" licenses = listOf(License().apply { name = "Apache-2.0" url = "https://www.apache.org/licenses/LICENSE-2.0" }) scm = Scm().apply { url = "https://github.com/cbeust/kobalt" connection = "https://github.com/cbeust/kobalt.git" developerConnection = "[email protected]:cbeust/kobalt.git" } developers = listOf(Developer().apply { name = "Cedric Beust" email = "[email protected]" }) }
apache-2.0
7a86424daa77de695a334b2310f6dacc
34.309816
125
0.575797
3.894114
false
false
false
false
mibac138/ArgParser
core/src/main/kotlin/com/github/mibac138/argparser/parser/OrderedParserRegistry.kt
1
2104
/* * Copyright (c) 2017 Michał Bączkowski * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.mibac138.argparser.parser /** * Must be `>= 0` */ typealias Position = Int /** * Created by mibac138 on 07-05-2017. */ interface OrderedParserRegistry : ParserRegistry { /** * * @param position must be `>= 0`, otherwise a exception will be thrown (commonly `ArrayIndexOutOfBoundsException`) */ fun registerParser(position: Position, parser: Parser) /** * * @param position must be `>= 0`, otherwise a exception will be thrown (commonly `ArrayIndexOutOfBoundsException`) */ fun removeParser(position: Position) } fun <T : OrderedParserRegistry> T.withOrderedParsers(vararg parsers: Pair<Position, Parser>): T { for ((pos, parser) in parsers) registerParser(pos, parser) return this } fun <T : OrderedParserRegistry> T.withOrderedParsers(vararg parsers: Parser, offset: Position = 0): T { for (i in 0 until parsers.size) registerParser(i + offset, parsers[i]) return this }
mit
852b085c2ae567d9507f33714f4f06cf
34.644068
119
0.722169
4.298569
false
false
false
false
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/base/widget/ScrollbarSetter.kt
1
1986
package yuku.alkitab.base.widget import android.graphics.drawable.Drawable import android.os.Build import android.view.View import androidx.recyclerview.widget.RecyclerView import yuku.alkitab.base.util.AppLog import java.lang.reflect.Field import java.lang.reflect.Method private const val TAG = "ScrollbarSetter" object ScrollbarSetter { class ReflectionHolder( val scrollCacheField: Field, val scrollBarField: Field, val setVerticalThumbDrawable: Method ) private val reflectionHolder: ReflectionHolder? by lazy { try { val scrollCacheField = View::class.java.getDeclaredField("mScrollCache") scrollCacheField.isAccessible = true val scrollCacheClass = scrollCacheField.type val scrollBarField = scrollCacheClass.getDeclaredField("scrollBar") scrollBarField.isAccessible = true val scrollBarClass = scrollBarField.type val setVerticalThumbDrawable = scrollBarClass.getDeclaredMethod("setVerticalThumbDrawable", Drawable::class.java) setVerticalThumbDrawable.isAccessible = true ReflectionHolder(scrollCacheField, scrollBarField, setVerticalThumbDrawable) } catch (e: Exception) { AppLog.e(TAG, "reflection init error", e) null } } fun RecyclerView.setVerticalThumb(drawable: Drawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { this.verticalScrollbarThumbDrawable = drawable } else { val reflectionHolder = reflectionHolder ?: return try { val scrollCache = reflectionHolder.scrollCacheField.get(this) val scrollBar = reflectionHolder.scrollBarField.get(scrollCache) reflectionHolder.setVerticalThumbDrawable.invoke(scrollBar, drawable) } catch (e: Exception) { AppLog.e(TAG, "reflection call error", e) } } } }
apache-2.0
06d59db62d3418582c7b474d8df004c6
37.192308
125
0.676234
4.774038
false
false
false
false
edvin/tornadofx
src/main/java/tornadofx/Rest.kt
1
26125
package tornadofx import javafx.application.Platform import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.scene.control.ProgressBar.INDETERMINATE_PROGRESS import javafx.scene.control.Tooltip import org.apache.http.HttpEntity import org.apache.http.HttpHost import org.apache.http.auth.AuthScope import org.apache.http.auth.UsernamePasswordCredentials import org.apache.http.client.config.RequestConfig import org.apache.http.client.methods.* import org.apache.http.client.protocol.HttpClientContext import org.apache.http.entity.InputStreamEntity import org.apache.http.entity.StringEntity import org.apache.http.impl.auth.BasicScheme import org.apache.http.impl.client.* import org.apache.http.util.EntityUtils import tornadofx.Rest.Request.Method.* import java.io.Closeable import java.io.InputStream import java.io.StringReader import java.net.* import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets.UTF_8 import java.security.MessageDigest import java.util.* import java.util.concurrent.atomic.AtomicLong import java.util.zip.DeflaterInputStream import java.util.zip.GZIPInputStream import javax.json.Json import javax.json.JsonArray import javax.json.JsonObject import javax.json.JsonValue import kotlin.collections.HashMap open class Rest : Controller() { companion object { var engineProvider: (Rest) -> Engine = ::HttpURLEngine val ongoingRequests = FXCollections.observableArrayList<Request>() val atomicseq = AtomicLong() fun useApacheHttpClient() { engineProvider = ::HttpClientEngine } } var engine = engineProvider(this) var baseURI: String? = null var proxy: Proxy? = null var authContext: AuthContext? = null fun setBasicAuth(username: String, password: String) { engine.setBasicAuth(username, password) } fun setDigestAuth(username: String, password: String) { engine.setDigestAuth(username, password) } fun reset() = engine.reset() fun get(path: String, data: JsonValue? = null, processor: (Request) -> Unit = {}) = execute(GET, path, data, processor) fun get(path: String, data: JsonModel, processor: (Request) -> Unit = {}) = get(path, JsonBuilder().apply { data.toJSON(this) }.build(), processor) fun put(path: String, data: JsonValue? = null, processor: (Request) -> Unit = {}) = execute(PUT, path, data, processor) fun put(path: String, data: JsonModel, processor: (Request) -> Unit = {}) = put(path, JsonBuilder().apply { data.toJSON(this) }.build(), processor) fun put(path: String, data: InputStream, processor: (Request) -> Unit = {}) = execute(PUT, path, data, processor) fun patch(path: String, data: JsonValue? = null, processor: (Request) -> Unit = {}) = execute(PATCH, path, data, processor) fun patch(path: String, data: JsonModel, processor: (Request) -> Unit = {}) = patch(path, JsonBuilder().apply { data.toJSON(this) }.build(), processor) fun patch(path: String, data: InputStream, processor: (Request) -> Unit = {}) = execute(PATCH, path, data, processor) fun post(path: String, data: JsonValue? = null, processor: (Request) -> Unit = {}) = execute(POST, path, data, processor) fun post(path: String, data: JsonModel, processor: (Request) -> Unit = {}) = post(path, JsonBuilder().apply { data.toJSON(this) }.build(), processor) fun post(path: String, data: InputStream, processor: (Request) -> Unit = {}) = execute(POST, path, data, processor) fun delete(path: String, data: JsonValue? = null, processor: (Request) -> Unit = {}) = execute(DELETE, path, data, processor) fun delete(path: String, data: JsonModel, processor: (Request) -> Unit = {}) = delete(path, JsonBuilder().apply { data.toJSON(this) }.build(), processor) fun getURI(path: String): URI { try { val asURI = URI.create(path.replace(" ", "%20")) if (asURI.isAbsolute) return asURI val uri = StringBuilder() if (baseURI != null) uri.append(baseURI) if (uri.toString().endsWith("/") && path.startsWith("/")) uri.append(path.substring(1)) else if (!uri.toString().endsWith("/") && !path.startsWith("/")) uri.append("/").append(path) else uri.append(path) return URI(uri.toString().replace(" ", "%20")) } catch (ex: URISyntaxException) { throw RuntimeException(ex) } } fun execute(method: Request.Method, target: String, data: Any? = null, processor: (Request) -> Unit = {}): Response { var request: Rest.Request? = null try { request = engine.request(atomicseq.addAndGet(1), method, getURI(target), data) processor(request) Platform.runLater { ongoingRequests.add(request) } return request.execute() } catch (t: Throwable) { throw RestException("Failed to execute request", request, null, t) } } abstract class Engine { var requestInterceptor: ((Request) -> Unit)? = null @Deprecated("Renamed to requestInterceptor", ReplaceWith("requestInterceptor")) var authInterceptor: ((Request) -> Unit)? get() = requestInterceptor; set(value) { requestInterceptor = value } var responseInterceptor: ((Response) -> Unit)? = null abstract fun request(seq: Long, method: Request.Method, uri: URI, entity: Any? = null): Request abstract fun reset() abstract fun setBasicAuth(username: String, password: String) abstract fun setDigestAuth(username: String, password: String) } interface Request { enum class Method { GET, PUT, POST, DELETE, PATCH } val seq: Long val method: Method val uri: URI val entity: Any? var properties: MutableMap<Any, Any> fun addHeader(name: String, value: String) fun getHeader(name: String): String? fun execute(): Response fun reset() } interface Response : Closeable { enum class Status(val code: Int) { Continue(100), SwitchingProtocols(101), Processing(102), OK(200), Created(201), Accepted(202), NonAuthoritativeInformation(203), NoContent(204), ResetContent(205), PartialContent(206), MultiStatus(207), AlreadyReported(208), IMUsed(226), MultipleChoices(300), MovedPermanently(301), Found(302), SeeOther(303), NotModified(304), UseProxy(305), TemporaryRedirect(307), PermanentRedirect(308), BadRequest(400), Unauthorized(401), PaymentRequired(402), Forbidden(403), NotFound(404), MethodNotAllowed(405), NotAcceptable(406), ProxyAuthenticationRequired(407), RequestTimeout(408), Conflict(409), Gone(410), LengthRequired(411), PreconditionFailed(412), PayloadTooLarge(413), URITooLong(414), UnsupportedMediaType(415), RangeNotSatisfiable(416), ExpectationFailed(417), IAmATeapot(418), MisdirectedRequest(421), UnprocessableEntity(422), Locked(423), FailedDependency(424), UpgradeRequired(426), PreconditionRequired(428), TooManyRequests(429), RequestHeaderFieldsTooLarge(431), UnavailableForLegalReasons(451), InternalServerError(500), NotImplemented(501), BadGateway(502), ServiceUnavailable(503), GatewayTimeout(504), HTTPVersionNotSupported(505), VariantAlsoNegotiates(506), InsufficientStorage(507), LoopDetected(508), NotExtended(510), NetworkAuthenticationRequired(511), Unknown(0) } val request: Request val statusCode: Int val status: Status get() = Status.values().find { it.code == statusCode } ?: Status.Unknown val reason: String fun text(): String? fun consume(): Response val headers: Map<String, List<String>> fun header(name: String): String? = headers.get(name)?.first() fun list(): JsonArray { try { val content = text() if (content.isNullOrEmpty()) return Json.createArrayBuilder().build() return when (val json = Json.createReader(StringReader(content)).use { it.read() }) { is JsonArray -> json is JsonObject -> Json.createArrayBuilder().add(json).build() else -> throw IllegalArgumentException("Unknown json result value") } } catch (t: Throwable) { throw RestException("JsonArray parsing failed", request, this, t) } finally { consume() } } fun one(): JsonObject { try { val content = text() if (content.isNullOrEmpty()) return Json.createObjectBuilder().build() return when (val json = Json.createReader(StringReader(content)).use { it.read() }) { is JsonArray -> { if (json.isEmpty()) return Json.createObjectBuilder().build() else return json.getJsonObject(0) } is JsonObject -> json else -> throw IllegalArgumentException("Unknown json result value") } } catch (t: Throwable) { throw RestException("JsonObject parsing failed", request, this, t) } finally { consume() } } fun content(): InputStream fun bytes(): ByteArray fun ok() = statusCode == 200 } } open class HttpURLEngine(val rest: Rest) : Rest.Engine() { override fun reset() { requestInterceptor = null } override fun request(seq: Long, method: Rest.Request.Method, uri: URI, entity: Any?) = HttpURLRequest(this, seq, method, uri, entity) override fun setBasicAuth(username: String, password: String) { rest.authContext = HttpURLBasicAuthContext(username, password) } override fun setDigestAuth(username: String, password: String) { rest.authContext = DigestAuthContext(username, password) } } internal fun MessageDigest.concat(vararg values: String): String { reset() update(values.joinToString(":").toByteArray(StandardCharsets.ISO_8859_1)) return digest().hex } val Rest.Response.digestParams: Map<String, String>? get() { fun String.clean() = trim('\t', ' ', '"') return headers["WWW-Authenticate"]?.first { it.startsWith("Digest ") } ?.substringAfter("Digest ") ?.split(",") ?.associate { val (name, value) = it.split("=", limit = 2) name.clean() to value.clean() } } private val HexChars = "0123456789abcdef".toCharArray() val ByteArray.hex get() = map(Byte::toInt).joinToString("") { "${HexChars[(it and 0xF0).ushr(4)]}${HexChars[it and 0x0F]}" } class HttpURLRequest(val engine: HttpURLEngine, override val seq: Long, override val method: Rest.Request.Method, override val uri: URI, override val entity: Any?) : Rest.Request { lateinit var connection: HttpURLConnection val headers = mutableMapOf<String, String>() init { reset() } override fun reset() { val url = uri.toURL() connection = (if (engine.rest.proxy != null) url.openConnection(engine.rest.proxy) else url.openConnection()) as HttpURLConnection headers += "Accept-Encoding" to "gzip, deflate" headers += "Content-Type" to "application/json" headers += "Accept" to "application/json" headers += "User-Agent" to "TornadoFX/Java ${System.getProperty("java.version")}" headers += "Connection" to "Keep-Alive" } override fun execute(): Rest.Response { engine.rest.authContext?.interceptRequest(this) engine.requestInterceptor?.invoke(this) for ((key, value) in headers) connection.addRequestProperty(key, value) connection.requestMethod = method.toString() if (entity != null) { if (headers["Content-Type"] == null) connection.addRequestProperty("Content-Type", "application/json") connection.doOutput = true val data = when (entity) { is JsonModel -> entity.toJSON().toString().toByteArray(UTF_8) is JsonValue -> entity.toString().toByteArray(UTF_8) is InputStream -> entity.readBytes() else -> throw IllegalArgumentException("Don't know how to handle entity of type ${entity.javaClass}") } connection.addRequestProperty("Content-Length", data.size.toString()) connection.connect() connection.outputStream.write(data) connection.outputStream.flush() connection.outputStream.close() } else { connection.connect() } val response = HttpURLResponse(this) if (connection.doOutput) response.bytes() val modifiedResponse = engine.rest.authContext?.interceptResponse(response) ?: response engine.responseInterceptor?.invoke(modifiedResponse) return modifiedResponse } override fun addHeader(name: String, value: String) { headers[name] = value } override fun getHeader(name: String) = headers[name] override var properties: MutableMap<Any, Any> = HashMap() } class HttpURLResponse(override val request: HttpURLRequest) : Rest.Response { override val statusCode: Int get() = request.connection.responseCode private var bytesRead: ByteArray? = null override fun close() { consume() } override fun consume(): Rest.Response = apply{ try { if (bytesRead == null) { bytes() return this } with(request.connection) { if (doInput) content().close() } } catch (ignored: Throwable) { ignored.printStackTrace() } Platform.runLater { Rest.ongoingRequests.remove(request) } } override val reason: String get() = request.connection.responseMessage override fun text() = bytes().toString(UTF_8) override fun content() = request.connection.errorStream ?: request.connection.inputStream override fun bytes(): ByteArray { bytesRead?.let { return it } try { val unwrapped = when (request.connection.contentEncoding) { "gzip" -> GZIPInputStream(content()) "deflate" -> DeflaterInputStream(content()) else -> content() } bytesRead = unwrapped.readBytes() } catch (error: Exception) { bytesRead = ByteArray(0) throw error } finally { consume() } return bytesRead!! } override val headers get() = request.connection.headerFields } open class HttpClientEngine(val rest: Rest) : Rest.Engine() { lateinit var client: CloseableHttpClient lateinit var context: HttpClientContext init { reset() } override fun request(seq: Long, method: Rest.Request.Method, uri: URI, entity: Any?) = HttpClientRequest(this, client, seq, method, uri, entity) override fun setBasicAuth(username: String, password: String) { requireNotNull(rest.baseURI){"You must configure the baseURI first."} val uri = URI.create(rest.baseURI) val scheme = if (uri.scheme == null) "http" else uri.scheme val port = if (uri.port > -1) uri.port else if (scheme == "http") 80 else 443 val host = HttpHost(uri.host, port, scheme) val credsProvider = BasicCredentialsProvider().apply { setCredentials(AuthScope(host), UsernamePasswordCredentials(username, password)) } context.authCache = BasicAuthCache() context.authCache.put(host, BasicScheme()) client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build() } override fun setDigestAuth(username: String, password: String) { rest.authContext = DigestAuthContext(username, password) } override fun reset() { client = HttpClientBuilder.create().build() context = HttpClientContext.create() } } class HttpClientRequest(val engine: HttpClientEngine, val client: CloseableHttpClient, override val seq: Long, override val method: Rest.Request.Method, override val uri: URI, override val entity: Any?) : Rest.Request { lateinit var request: HttpRequestBase init { reset() } override fun reset() { when (method) { GET -> request = HttpGet(uri) PUT -> request = HttpPut(uri) POST -> request = HttpPost(uri) DELETE -> request = HttpDelete(uri) PATCH -> request = HttpPatch(uri) } addHeader("Accept-Encoding", "gzip, deflate") addHeader("Content-Type", "application/json") addHeader("Accept", "application/json") } override fun execute(): Rest.Response { if (engine.rest.proxy != null) { val hp = engine.rest.proxy as Proxy val sa = hp.address() as? InetSocketAddress if (sa != null) { val scheme = if (engine.rest.baseURI?.startsWith("https") ?: false) "https" else "http" val proxy = HttpHost(sa.address, sa.port, scheme) request.config = RequestConfig.custom().setProxy(proxy).build() } } engine.requestInterceptor?.invoke(this) if (entity != null && request is HttpEntityEnclosingRequestBase) { val r = request as HttpEntityEnclosingRequestBase when (entity) { is JsonModel -> r.entity = StringEntity(entity.toJSON().toString(), UTF_8) is JsonValue -> r.entity = StringEntity(entity.toString(), UTF_8) is InputStream -> r.entity = InputStreamEntity(entity) is HttpEntity -> r.entity = entity else -> throw IllegalArgumentException("Don't know how to handle entity of type ${entity.javaClass}") } } val httpResponse = client.execute(request, engine.context) val response = HttpClientResponse(this, httpResponse) engine.responseInterceptor?.invoke(response) return response } override fun addHeader(name: String, value: String) = request.addHeader(name, value) override fun getHeader(name: String) = request.getFirstHeader("name")?.value override var properties: MutableMap<Any, Any> = HashMap() } class HttpClientResponse(override val request: HttpClientRequest, val response: CloseableHttpResponse) : Rest.Response { override val statusCode: Int get() = response.statusLine.statusCode override val reason: String get() = response.statusLine.reasonPhrase override fun close() { consume() } override fun text(): String { try { return EntityUtils.toString(response.entity, UTF_8) } finally { consume() } } override fun consume() = apply { EntityUtils.consumeQuietly(response.entity) try { (response as? CloseableHttpResponse)?.close() } finally { Platform.runLater { Rest.ongoingRequests.remove(request) } } } override fun content() = response.entity.content override fun bytes(): ByteArray { try { return EntityUtils.toByteArray(response.entity) } finally { consume() } } override val headers get() = response.allHeaders.associate { it.name to listOf(it.value) } } inline fun <reified T : JsonModel> JsonObject.toModel(): T { val model = T::class.java.newInstance() model.updateModel(this) return model } inline fun <reified T : JsonModel> JsonArray.toModel(): ObservableList<T> { return FXCollections.observableArrayList(map { (it as JsonObject).toModel<T>() }) } class RestProgressBar : Fragment() { override val root = progressbar { prefWidth = 75.0 isVisible = false } init { Rest.ongoingRequests.addListener(ListChangeListener<Rest.Request> { c -> val size = c.list.size Platform.runLater { val tooltip = c.list.joinToString("\n") { r -> "%s %s".format(r.method, r.uri) } root.tooltip = Tooltip(tooltip) root.isVisible = size > 0 if (size == 0) { root.progress = 100.0 } else if (size == 1) { root.progress = INDETERMINATE_PROGRESS } else { val pct = 1.0 / size.toDouble() root.progress = pct } } }) } } val String.urlEncoded: String get() = URLEncoder.encode(this, StandardCharsets.UTF_8.name()) val Map<*, *>.queryString: String get() { val q = StringBuilder() forEach { k, v -> if (k != null) { q.append(if (q.isEmpty()) "?" else "&") q.append(k.toString().urlEncoded) if (v != null) q.append("=${v.toString().urlEncoded}") } } return q.toString() } interface AuthContext { fun interceptRequest(request: Rest.Request) fun interceptResponse(response: Rest.Response): Rest.Response } class DigestAuthContext(val username: String, val password: String) : AuthContext { val nonceCounter = AtomicLong(0) var nonce: String = "" var realm: String = "" var qop: String = "" var opaque: String = "" var algorithm: String = "" var digest = MessageDigest.getInstance("MD5") companion object { val QuotedStringParameters = listOf("username", "realm", "nonce", "uri", "response", "cnonce", "opaque") } override fun interceptRequest(request: Rest.Request) { if (nonce.isNotBlank() && request.getHeader("Authorization") == null) { request.addHeader("Authorization", generateAuthHeader(request, null)) } } private fun generateCnonce(digest: MessageDigest) = digest.concat(System.nanoTime().toString()) override fun interceptResponse(response: Rest.Response): Rest.Response { extractNextNonce(response) if (response.statusCode != 401 || response.request.properties["Authorization-Retried"] != null) return response val params = response.digestParams if (params != null && params["stale"]?.toBoolean() != false) { FX.log.fine { "Digest Challenge: $params" } algorithm = params["algorithm"] ?: "MD5" digest = MessageDigest.getInstance(algorithm.removeSuffix("-sess")) realm = params["realm"] ?: kotlin.error("Realm is not present in response digest parameters") nonce = params["nonce"] ?: kotlin.error("Nonce is not present in response digest parameters") opaque = params["opaque"] ?: "" nonceCounter.set(0) qop = (params["qop"] ?: "").split(",").map(String::trim).sortedBy { it.length }.last() val request = response.request request.reset() request.addHeader("Authorization", generateAuthHeader(request, response)) request.properties["Authorization-Retried"] = true return request.execute() } return response } private fun extractNextNonce(response: Rest.Response) { val authInfo = response.header("Authentication-Info") if (authInfo != null) { val params = authInfo.split(",").associate { val (name, value) = it.split("=", limit = 2) name to value } val nextNonce = params["nextnonce"] if (nextNonce != null) { nonceCounter.set(0) nonce = nextNonce } } } private fun generateAuthHeader(request: Rest.Request, response: Rest.Response?): String { val cnonce = generateCnonce(digest) val path = request.uri.path val nc = Integer.toHexString(nonceCounter.incrementAndGet().toInt()).padStart(8, '0') val ha1 = when (algorithm) { "MD5-sess" -> digest.concat(digest.concat(username, realm, password), nonce, cnonce) else -> digest.concat(username, realm, password) } val ha2 = when (qop) { "auth-int" -> digest.concat(request.method.name, path, digest.concat(response?.text() ?: "")) else -> digest.concat(request.method.name, path) } val encoded = when (qop) { "auth", "auth-int" -> digest.concat(ha1, nonce, nonceCounter.incrementAndGet().toString(), cnonce, qop, ha2) else -> digest.concat(ha1, nonce, ha2) } val authParams = mapOf( "username" to username, "realm" to realm, "nonce" to nonce, "uri" to path, "response" to encoded, "opaque" to opaque, "algorithm" to algorithm, "nc" to nc ) val header = "Digest " + authParams.map { val q = if (it.key in QuotedStringParameters) "\"" else "" "${it.key}=$q${it.value}$q" }.joinToString() FX.log.fine { "Digest Response: $header" } return header } } class HttpURLBasicAuthContext(val username: String, val password: String) : AuthContext { override fun interceptRequest(request: Rest.Request) { val b64 = Base64.getEncoder().encodeToString("$username:$password".toByteArray(UTF_8)) request.addHeader("Authorization", "Basic $b64") } override fun interceptResponse(response: Rest.Response): Rest.Response { return response } } class RestException(message: String, val request: Rest.Request?, val response: Rest.Response?, cause: Throwable) : RuntimeException(message, cause)
apache-2.0
1566324063b54f78069ae63196052fd5
37.705185
628
0.617876
4.488832
false
false
false
false
chromeos/vulkanphotobooth
app/src/main/java/dev/hadrosaur/vulkanphotobooth/cameracontroller/Camera2DeviceStateCallback.kt
1
3148
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.hadrosaur.vulkanphotobooth.cameracontroller import android.hardware.camera2.CameraDevice import androidx.annotation.NonNull import dev.hadrosaur.vulkanphotobooth.CameraParams import dev.hadrosaur.vulkanphotobooth.MainActivity import dev.hadrosaur.vulkanphotobooth.MainActivity.Companion.logd /** * Callbacks that track the state of the camera device using the Camera 2 API. */ class Camera2DeviceStateCallback( internal var params: CameraParams, internal var activity: MainActivity ) : CameraDevice.StateCallback() { /** * Camera device has opened successfully */ override fun onOpened(cameraDevice: CameraDevice) { params.isOpen = true params.device = cameraDevice params.cameraOpenRequested = false camera2StartPreview(activity, params) } /** * Camera device has been closed. */ override fun onClosed(camera: CameraDevice) { // logd("Camera has been closed correctly.") params.isOpen = false params.isClosing = false; params.isPreviewing = false; params.cameraOpenRequested = false if (camera != null) super.onClosed(camera) } /** * Camera has been disconnected. Whatever was happening, it won't work now. */ override fun onDisconnected(@NonNull cameraDevice: CameraDevice) { if (!params.isOpen) { return } camera2CloseCamera(params) } /** * Camera device has thrown an error. Try to recover or fail gracefully. */ override fun onError(@NonNull cameraDevice: CameraDevice, error: Int) { logd("In CameraStateCallback onError: " + cameraDevice.id + " error: " + error) if (!params.isOpen) { return } when (error) { ERROR_MAX_CAMERAS_IN_USE -> { // Try to close an open camera and re-open this one logd("In CameraStateCallback too many cameras open, closing one...") camera2CloseCamera(params) camera2OpenCamera(activity, params) } ERROR_CAMERA_DEVICE -> { logd("Fatal camera error, close and try to re-initialize...") camera2CloseCamera(params) camera2OpenCamera(activity, params) } ERROR_CAMERA_IN_USE -> { logd("This camera is already open... doing nothing") } else -> { camera2CloseCamera(params) } } } }
apache-2.0
83945cebc903f7b3d4d5ec5d7bd6e04c
29.572816
87
0.636912
4.649926
false
false
false
false
rweekers/voornameninliedjes-backend-spring
src/main/kotlin/nl/orangeflamingo/voornameninliedjesbackendadmin/controller/SongController.kt
1
9237
package nl.orangeflamingo.voornameninliedjesbackendadmin.controller import nl.orangeflamingo.voornameninliedjesbackendadmin.domain.* import nl.orangeflamingo.voornameninliedjesbackendadmin.dto.* import nl.orangeflamingo.voornameninliedjesbackendadmin.repository.SongRepository import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.cache.annotation.CachePut import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.* import org.springframework.web.client.RestTemplate import java.lang.IllegalArgumentException import java.time.Instant @RestController @RequestMapping("/api") class SongController { private val log = LoggerFactory.getLogger(SongController::class.java) @Autowired private lateinit var songRepository: SongRepository val restTemplate: RestTemplate = RestTemplate() @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/songs") @CachePut(value = ["songs"]) @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun getSongs(): List<SongDto> { return songRepository.findAll(/*Sort(Sort.Direction.ASC, "name")*/).map { convertToDto(it) }.map { enrichSong(it) } } @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/songs", params = ["name"]) @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun getSongsByName(@RequestParam(name = "name") name: String): List<SongDto> { return songRepository.findAllByNameContainingIgnoreCaseOrderByName(name).map { convertToDto(it) }.map { enrichSong(it) } } @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/songs", params = ["first-character"]) @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun getSongsWithNameStartingWith(@RequestParam(name = "first-character") firstCharacter: String): List<SongDto> { return songRepository.findAllByNameStartsWithIgnoreCaseOrderByName(firstCharacter).map { convertToDto(it) }.map { enrichSong(it) } } @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/songs/{id}") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun getSongById(@PathVariable("id") id: String): SongDto { return songRepository.findById(id).map { convertToDto(it) }.map { enrichSong(it) }.orElseThrow { RuntimeException("Song with $id not found") } } @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/songs/{user}") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun newSong(@RequestBody newSong: SongDto, @PathVariable user: String): SongDto { val logEntry = LogEntry(Instant.now(), user) return convertToDto(songRepository.save(convert(newSong, mutableListOf(logEntry)))) } @PreAuthorize("hasRole('ROLE_ADMIN')") @PutMapping("/songs/{user}/{id}") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun replaceSong(@RequestBody song: SongDto, @PathVariable user: String, @PathVariable id: String): SongDto { assert(song.id == id) val logEntry = LogEntry(Instant.now(), user) val songFromDb = songRepository.findById(id) if (songFromDb.isPresent) { val songDB = songFromDb.get() songDB.artist = song.artist songDB.title = song.title songDB.name = song.name songDB.status = SongStatus.valueOf(song.status) songDB.background = song.background songDB.youtube = song.youtube songDB.spotify = song.spotify songDB.wikimediaPhotos = song.wikimediaPhotos.map { w -> convertToDomain(w) }.toMutableSet() songDB.flickrPhotos = song.flickrPhotos.toMutableSet() songDB.sources = song.sources.map { s -> convertToDomain(s) }.toMutableSet() songDB.logs.add(logEntry) songRepository.save(songDB) return convertToDto(songDB) } return convertToDto(songRepository.save(convert(song, mutableListOf(logEntry)))) } @PreAuthorize("hasRole('ROLE_ADMIN')") @PostMapping("/songs/{user}/{id}/{flickrId}") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun addFlickrPhoto(@PathVariable user: String, @PathVariable id: String, @PathVariable flickrId: String) { val songOptional = songRepository.findById(id) if (songOptional.isPresent) { val song = songOptional.get() val logEntry = LogEntry(Instant.now(), user) song.logs.add(logEntry) song.flickrPhotos.add(flickrId) songRepository.save(song) } else { log.warn("Song with id $id not found") } } @PreAuthorize("hasRole('ROLE_ADMIN')") @DeleteMapping("/songs/{id}") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun deleteSong(@PathVariable id: String) { songRepository.deleteById(id) } @PreAuthorize("hasRole('ROLE_OWNER')") @PutMapping("/songs/{id}/prepend-logs") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun prependLogs(@RequestBody logs: List<LogEntryDto>, @PathVariable id: String): SongDto { val songFromDb = songRepository.findById(id).orElseThrow { IllegalArgumentException("Song with id $id not found") } // Reverse list to start with most recent and add all at beginning val logsToPrepend = logs.map { convertToDomain(it) }.reversed() logsToPrepend.forEach { songFromDb.logs.add(0, it) } songRepository.save(songFromDb) return convertToDto(songFromDb) } @PreAuthorize("hasRole('ROLE_OWNER')") @PutMapping("/songs/{id}/replace-logs") @CrossOrigin(origins = ["http://localhost:3000", "https://voornameninliedjes.nl", "*"]) fun replaceLogs(@RequestBody logs: List<LogEntryDto>, @PathVariable id: String): SongDto { val songFromDb = songRepository.findById(id).orElseThrow { IllegalArgumentException("Song with id $id not found") } val newLogs = logs.map { convertToDomain(it) } songFromDb.logs.clear() songFromDb.logs.addAll(newLogs) songRepository.save(songFromDb) return convertToDto(songFromDb) } private fun convert(songDto: SongDto, logs: MutableList<LogEntry>): Song { val status = SongStatus.valueOf(songDto.status) return Song(id = null, artist = songDto.artist, title = songDto.title, name = songDto.name, background = songDto.background, youtube = songDto.youtube, spotify = songDto.spotify, sources = songDto.sources.map { s -> convertToDomain(s) }.toMutableSet(), status = status, logs = logs) } private fun convertToDto(song: Song): SongDto { return SongDto( id = song.id, artist = song.artist, title = song.title, name = song.name, artistImage = "https://ak9.picdn.net/shutterstock/videos/24149239/thumb/1.jpg", background = song.background, youtube = song.youtube, spotify = song.spotify, status = song.status.name, wikimediaPhotos = song.wikimediaPhotos.map { w -> convertToDto(w) }.toSet(), flickrPhotos = song.flickrPhotos, sources = song.sources.map { s -> convertToDto(s) }.toSet(), logs = song.logs ) } private fun convertToDto(wikimediaPhoto: WikimediaPhoto): WikimediaPhotoDto { return WikimediaPhotoDto(wikimediaPhoto.url, wikimediaPhoto.attribution) } private fun convertToDomain(wikimediaPhotoDto: WikimediaPhotoDto): WikimediaPhoto { return WikimediaPhoto(wikimediaPhotoDto.url, wikimediaPhotoDto.attribution) } private fun convertToDomain(sourceDto: SourceDto): Source { return Source(url = sourceDto.url, name = sourceDto.name) } private fun convertToDto(source: Source): SourceDto { return SourceDto(url = source.url, name = source.name) } private fun convertToDomain(logEntryDto: LogEntryDto): LogEntry { return LogEntry(date = logEntryDto.date, user = logEntryDto.user) } private fun enrichSong(song: SongDto): SongDto { val wikimediaPhoto = song.wikimediaPhotos.firstOrNull() if (wikimediaPhoto != null) { return song.copy(artistImage = wikimediaPhoto.url) } val flickrPhotoId = song.flickrPhotos.firstOrNull() if (flickrPhotoId != null) { val photo = restTemplate.getForObject("https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=9676a28e9cb321d2721e813055abb6dc&format=json&nojsoncallback=true&photo_id=" + flickrPhotoId, FlickrPhotoDto::class.java)?.photo if (photo != null) { return song.copy(artistImage = "https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}_c.jpg") } } return song } }
mit
996b17549d8a87a5b28e3846949a4f16
45.417085
290
0.66959
4.065581
false
false
false
false
AlexLandau/semlang
kotlin/semlang-parser/src/main/kotlin/validator/validator.kt
1
56252
package net.semlang.validator import net.semlang.api.* import net.semlang.api.Function import net.semlang.api.parser.Issue import net.semlang.api.parser.IssueLevel import net.semlang.api.parser.Location import net.semlang.modules.computeFake0Version import net.semlang.parser.ParsingResult import net.semlang.parser.parseFile import net.semlang.parser.parseString import net.semlang.transforms.invalidate import java.io.File import java.util.* /* * Warning: Doesn't validate that composed literals satisfy their requires blocks, which requires running semlang code to * check (albeit code that can always be run in a vacuum) */ fun validateModule(context: RawContext, moduleName: ModuleName, nativeModuleVersion: String, upstreamModules: List<ValidatedModule>): ValidationResult { val fake0Version = computeFake0Version(context, upstreamModules) val moduleId = ModuleUniqueId(moduleName, fake0Version) // TODO: Actually implement this val moduleVersionMappings = mapOf<ModuleNonUniqueId, ModuleUniqueId>() val issuesList = ArrayList<Issue>() val typesInfo = getTypesInfo(context, moduleId, upstreamModules, moduleVersionMappings, { issue -> issuesList.add(issue) }) val typesMetadata = getTypesMetadata(typesInfo) val validator = Validator(moduleId, nativeModuleVersion, upstreamModules, moduleVersionMappings, typesInfo, typesMetadata, issuesList) return validator.validate(context) } fun validateModule(context: RawContext, typesInfo: TypesInfo, typesMetadata: TypesMetadata, moduleName: ModuleName, nativeModuleVersion: String, upstreamModules: List<ValidatedModule>): ValidationResult { val fake0Version = computeFake0Version(context, upstreamModules) val moduleId = ModuleUniqueId(moduleName, fake0Version) // TODO: Actually implement this val moduleVersionMappings = mapOf<ModuleNonUniqueId, ModuleUniqueId>() val issuesList = ArrayList<Issue>() val validator = Validator(moduleId, nativeModuleVersion, upstreamModules, moduleVersionMappings, typesInfo, typesMetadata, issuesList) return validator.validate(context) } fun validate(parsingResult: ParsingResult, moduleName: ModuleName, nativeModuleVersion: String, upstreamModules: List<ValidatedModule>): ValidationResult { return when (parsingResult) { is ParsingResult.Success -> { validateModule(parsingResult.context, moduleName, nativeModuleVersion, upstreamModules) } is ParsingResult.Failure -> { val validationResult = validateModule(parsingResult.partialContext, moduleName, nativeModuleVersion, upstreamModules) when (validationResult) { is ValidationResult.Success -> { ValidationResult.Failure(parsingResult.errors, validationResult.warnings) } is ValidationResult.Failure -> { ValidationResult.Failure(parsingResult.errors + validationResult.errors, validationResult.warnings) } } } } } fun parseAndValidateFile(file: File, moduleName: ModuleName, nativeModuleVersion: String, upstreamModules: List<ValidatedModule> = listOf()): ValidationResult { val parsingResult = parseFile(file) return validate(parsingResult, moduleName, nativeModuleVersion, upstreamModules) } fun parseAndValidateString(text: String, documentUri: String, moduleName: ModuleName, nativeModuleVersion: String): ValidationResult { val parsingResult = parseString(text, documentUri) return validate(parsingResult, moduleName, nativeModuleVersion, listOf()) } sealed class ValidationResult { abstract fun assumeSuccess(): ValidatedModule abstract fun getAllIssues(): List<Issue> data class Success(val module: ValidatedModule, val warnings: List<Issue>): ValidationResult() { override fun getAllIssues(): List<Issue> { return warnings } override fun assumeSuccess(): ValidatedModule { return module } } data class Failure(val errors: List<Issue>, val warnings: List<Issue>): ValidationResult() { override fun getAllIssues(): List<Issue> { return errors + warnings } override fun assumeSuccess(): ValidatedModule { error("Encountered errors in validation:\n${formatForCliOutput(errors)}") } fun getErrorInfoInCliFormat(): String { return formatForCliOutput(errors) } } } private fun formatForCliOutput(allErrors: List<Issue>): String { val sb = StringBuilder() val errorsByDocument: Map<String?, List<Issue>> = allErrors.groupBy { error -> if (error.location == null) null else error.location!!.documentUri } for ((document, errors) in errorsByDocument) { if (document == null) { sb.append("In an unknown location:\n") } else { sb.append("In ${document}:\n") } for (error in errors) { sb.append(" ") if (error.location != null) { sb.append(error.location!!.range).append(": ") } sb.append(error.message).append("\n") } } return sb.toString() } private class Validator( val moduleId: ModuleUniqueId, val nativeModuleVersion: String, val upstreamModules: List<ValidatedModule>, val moduleVersionMappings: Map<ModuleNonUniqueId, ModuleUniqueId>, val typesInfo: TypesInfo, val typesMetadata: TypesMetadata, initialIssues: List<Issue>) { val warnings = ArrayList<Issue>(initialIssues.filter { it.level == IssueLevel.WARNING }) val errors = ArrayList<Issue>(initialIssues.filter { it.level == IssueLevel.ERROR }) fun validate(context: RawContext): ValidationResult { val ownFunctions = validateFunctions(context.functions) val ownStructs = validateStructs(context.structs) val ownUnions = validateUnions(context.unions) if (errors.isEmpty()) { val createdModule = ValidatedModule.create(moduleId, nativeModuleVersion, ownFunctions, ownStructs, ownUnions, upstreamModules, moduleVersionMappings) return ValidationResult.Success(createdModule, warnings) } else { return ValidationResult.Failure(errors, warnings) } } private fun validateFunctions(functions: List<Function>): Map<EntityId, ValidatedFunction> { val validatedFunctions = LinkedHashMap<EntityId, ValidatedFunction>() for (function in functions) { val validatedFunction = validateFunction(function) if (validatedFunction != null && !typesInfo.duplicateLocalFunctionIds.contains(validatedFunction.id)) { validatedFunctions.put(function.id, validatedFunction) } else if (errors.isEmpty()) { error("Something bad happened") } } return validatedFunctions } private fun validateFunction(function: Function): ValidatedFunction? { val arguments = validateArguments(function.arguments, function.typeParameters.associateBy(TypeParameter::name)) ?: return null val returnType = validateType(function.returnType, function.typeParameters.associateBy(TypeParameter::name)) ?: return null //TODO: Validate that type parameters don't share a name with something important val variableTypes = getArgumentVariableTypes(arguments, function.arguments) val block = validateBlock(function.block, variableTypes, function.typeParameters.associateBy(TypeParameter::name)) ?: return null if (returnType != block.type) { errors.add(Issue("Stated return type ${function.returnType} does not match the block's actual return type ${prettyType(block.type)}", function.returnTypeLocation, IssueLevel.ERROR)) } return ValidatedFunction(function.id, function.typeParameters, arguments, returnType, block, function.annotations) } private fun validateType(type: UnvalidatedType, typeParametersInScope: Map<String, TypeParameter>): Type? { return validateType(type, typeParametersInScope, listOf()) } private fun validateType(type: UnvalidatedType, typeParametersInScope: Map<String, TypeParameter>, internalParameters: List<String>): Type? { return when (type) { is UnvalidatedType.FunctionType -> { val newInternalParameters = ArrayList<String>() // Add the new parameters to the front of the list for (typeParameter in type.typeParameters) { newInternalParameters.add(typeParameter.name) } newInternalParameters.addAll(internalParameters) val argTypes = type.argTypes.map { argType -> validateType(argType, typeParametersInScope, newInternalParameters) ?: return null } val outputType = validateType(type.outputType, typeParametersInScope, newInternalParameters) ?: return null Type.FunctionType.create(type.isReference(), type.typeParameters, argTypes, outputType) } is UnvalidatedType.NamedType -> { if (type.parameters.isEmpty() && type.ref.moduleRef == null && type.ref.id.namespacedName.size == 1) { val typeName = type.ref.id.namespacedName[0] val internalParameterIndex = internalParameters.indexOf(typeName) if (internalParameterIndex >= 0) { return Type.InternalParameterType(internalParameterIndex) } val externalParameterType = typeParametersInScope[typeName] if (externalParameterType != null) { return Type.ParameterType(externalParameterType) } } val typeInfo = typesInfo.getResolvedTypeInfo(type.ref) when (typeInfo) { is TypeInfoResult.Error -> { errors.add(Issue(typeInfo.errorMessage, type.location, IssueLevel.ERROR)) return null } is ResolvedTypeInfo -> { /* Automatic type guard */ } } val shouldBeReference = typeInfo.info.isReference if (shouldBeReference && !type.isReference()) { errors.add(Issue("Type $type is a reference type and should be marked as such with '&'", type.location, IssueLevel.ERROR)) return null } if (type.isReference() && !shouldBeReference) { errors.add(Issue("Type $type is not a reference type and should not be marked with '&'", type.location, IssueLevel.ERROR)) return null } val parameters = type.parameters.map { parameter -> validateType(parameter, typeParametersInScope, internalParameters) ?: return null } Type.NamedType(typeInfo.resolvedRef, type.ref, type.isReference(), parameters) } } } private fun validateArguments(arguments: List<UnvalidatedArgument>, typeParametersInScope: Map<String, TypeParameter>): List<Argument>? { val validatedArguments = ArrayList<Argument>() for (argument in arguments) { val type = validateType(argument.type, typeParametersInScope) ?: return null validatedArguments.add(Argument(argument.name, type)) } return validatedArguments } private fun getArgumentVariableTypes(arguments: List<Argument>, unvalidatedArguments: List<UnvalidatedArgument>): Map<String, Type> { val variableTypes = HashMap<String, Type>() for ((index, argument) in arguments.withIndex()) { if (variableTypes.containsKey(argument.name)) { errors.add(Issue("Duplicate argument name ${argument.name}", unvalidatedArguments[index].location, IssueLevel.ERROR)) } else { variableTypes[argument.name] = argument.type } } return variableTypes } private fun validateBlock(block: Block, externalVariableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedBlock? { val variableTypes = HashMap(externalVariableTypes) val validatedStatements = ArrayList<ValidatedStatement>() if (block.statements.isEmpty()) { errors.add(Issue("Blocks cannot be empty", block.location, IssueLevel.ERROR)) return null } for (statement in block.statements) { // TODO: Refactor to combine the referential action checks, if possible val validatedStatement = validateStatement(statement, variableTypes, typeParametersInScope) ?: return null if (validatedStatement is ValidatedStatement.Assignment) { // Check the expression type here, not the assignment type, for more appropriate error messages if (validatedStatement.expression.type.isReference() && validatedStatement.expression.aliasType == AliasType.PossiblyAliased) { errors.add( Issue( "We are assigning a reference to the variable ${validatedStatement.name}, but the reference may already have an alias; references are not allowed to have more than one alias", (statement as Statement.Assignment).nameLocation, IssueLevel.ERROR ) ) } variableTypes.put(validatedStatement.name, validatedStatement.type) } validatedStatements.add(validatedStatement) } // TODO: It's not clear that this is the right way to propagate this information val (lastStatementType, lastStatementAliasType) = when (val lastStatement = validatedStatements.last()) { is ValidatedStatement.Assignment -> { errors.add(Issue("The last statement in a block should not be an assignment", block.statements.last().location, IssueLevel.ERROR)) return null } is ValidatedStatement.Bare -> { Pair(lastStatement.type, lastStatement.expression.aliasType) } } return TypedBlock(lastStatementType, validatedStatements, lastStatementAliasType) } private fun validateStatement(statement: Statement, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): ValidatedStatement? { return when (statement) { is Statement.Assignment -> { val varName = statement.name if (variableTypes.containsKey(varName)) { errors.add( Issue( "The already-assigned variable $varName cannot be reassigned", statement.nameLocation, IssueLevel.ERROR ) ) } if (isInvalidVariableName(varName)) { errors.add(Issue("Invalid variable name $varName", statement.nameLocation, IssueLevel.ERROR)) } val validatedExpression = validateExpression(statement.expression, variableTypes, typeParametersInScope) ?: return null val unvalidatedAssignmentType = statement.type val validatedAssignmentType = if (unvalidatedAssignmentType != null) { val assignmentType = validateType(unvalidatedAssignmentType, typeParametersInScope) ?: return null if (validatedExpression.type != assignmentType) { errors.add( Issue( "Declared variable type ${prettyType(assignmentType)} " + "doesn't match expression type ${prettyType(validatedExpression.type)}", statement.nameLocation, IssueLevel.ERROR ) ) return null } assignmentType } else { validatedExpression.type } val referentialActionsCount = countReferentialActions(validatedExpression) if (referentialActionsCount > 1) { // TODO: This should allow nested calls where the order is unambiguous, but I need to consider the general case more carefully // TODO: Another convenience we can add is allowing multiple referential "actions" if they are all read-only, e.g. reading a bunch of variables errors.add( Issue( "The statement contains more than one referential action; move these to separate statements to disambiguate the order in which they should happen", statement.expression.location, IssueLevel.ERROR ) ) } ValidatedStatement.Assignment( varName, validatedAssignmentType, validatedExpression ) } is Statement.Bare -> { val validatedExpression = validateExpression(statement.expression, variableTypes, typeParametersInScope) ?: return null val referentialActionsCount = countReferentialActions(validatedExpression) if (referentialActionsCount > 1) { // TODO: This should allow nested calls where the order is unambiguous, but I need to consider the general case more carefully // TODO: Another convenience we can add is allowing multiple referential "actions" if they are all read-only, e.g. reading a bunch of variables errors.add( Issue( "The statement contains more than one referential action; move these to separate statements to disambiguate the order in which they should happen", statement.expression.location, IssueLevel.ERROR ) ) } ValidatedStatement.Bare(validatedExpression.type, validatedExpression) } } } private fun countReferentialActions(statement: ValidatedStatement): Int { return when (statement) { is ValidatedStatement.Assignment -> countReferentialActions(statement.expression) is ValidatedStatement.Bare -> countReferentialActions(statement.expression) } } private fun countReferentialActions(expression: TypedExpression): Int { return when (expression) { is TypedExpression.Variable -> 0 is TypedExpression.IfThen -> countReferentialActions(expression.condition) is TypedExpression.NamedFunctionCall -> { var count = 0 if (expression.type.isReference() || expression.arguments.any { it.type.isReference() }) { count++ } for (argument in expression.arguments) { count += countReferentialActions(argument) } count } is TypedExpression.ExpressionFunctionCall -> { var count = 0 count += countReferentialActions(expression.functionExpression) if (expression.type.isReference() || expression.arguments.any { it.type.isReference() }) { count++ } for (argument in expression.arguments) { count += countReferentialActions(argument) } count } is TypedExpression.Literal -> 0 is TypedExpression.ListLiteral -> { expression.contents.map(this::countReferentialActions).sum() } is TypedExpression.NamedFunctionBinding -> 0 is TypedExpression.ExpressionFunctionBinding -> countReferentialActions(expression.functionExpression) is TypedExpression.Follow -> 0 is TypedExpression.InlineFunction -> 0 } } //TODO: Construct this more sensibly from more centralized lists private val INVALID_VARIABLE_NAMES: Set<String> = setOf("function", "let", "if", "else", "struct", "requires", "interface", "union") private fun isInvalidVariableName(name: String): Boolean { val nameAsEntityRef = EntityId.of(name).asRef() return typesInfo.getFunctionInfo(nameAsEntityRef) != null || INVALID_VARIABLE_NAMES.contains(name) } private fun validateExpression(expression: Expression, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { try { return when (expression) { is Expression.Variable -> validateVariableExpression(expression, variableTypes) is Expression.IfThen -> validateIfThenExpression( expression, variableTypes, typeParametersInScope ) is Expression.Follow -> validateFollowExpression( expression, variableTypes, typeParametersInScope ) is Expression.NamedFunctionCall -> validateNamedFunctionCallExpression( expression, variableTypes, typeParametersInScope ) is Expression.ExpressionFunctionCall -> validateExpressionFunctionCallExpression( expression, variableTypes, typeParametersInScope ) is Expression.Literal -> validateLiteralExpression(expression, typeParametersInScope) is Expression.ListLiteral -> validateListLiteralExpression( expression, variableTypes, typeParametersInScope ) is Expression.NamedFunctionBinding -> validateNamedFunctionBinding( expression, variableTypes, typeParametersInScope ) is Expression.ExpressionFunctionBinding -> validateExpressionFunctionBinding( expression, variableTypes, typeParametersInScope ) is Expression.InlineFunction -> validateInlineFunction( expression, variableTypes, typeParametersInScope ) } } catch (e: RuntimeException) { throw RuntimeException("Error when validating expression $expression", e) } } private fun validateInlineFunction(expression: Expression.InlineFunction, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { for (arg in expression.arguments) { if (variableTypes.containsKey(arg.name)) { errors.add(Issue("Argument name ${arg.name} shadows an existing variable name", arg.location, IssueLevel.ERROR)) } } val validatedArguments = validateArguments(expression.arguments, typeParametersInScope) ?: return null val incomingVariableTypes: Map<String, Type> = variableTypes + validatedArguments.asVariableTypesMap() val validatedBlock = validateBlock(expression.block, incomingVariableTypes, typeParametersInScope) ?: return null // Note: This is the source of the canonical in-memory ordering val varsToBind = ArrayList<String>(variableTypes.keys) varsToBind.retainAll(getVarsReferencedIn(validatedBlock)) val varsToBindWithTypes = varsToBind.map { name -> Argument(name, variableTypes[name]!!)} var isReference = false for (varToBindWithType in varsToBindWithTypes) { if (varToBindWithType.type.isReference()) { isReference = true } } val returnType = validateType(expression.returnType, typeParametersInScope) ?: return null if (validatedBlock.type != returnType) { errors.add(Issue("The inline function has a return type ${prettyType(returnType)}, but the actual type returned is ${prettyType(validatedBlock.type)}", expression.location, IssueLevel.ERROR)) } val functionType = Type.FunctionType.create(isReference, listOf(), validatedArguments.map(Argument::type), returnType) return TypedExpression.InlineFunction(functionType, AliasType.NotAliased, validatedArguments, varsToBindWithTypes, returnType, validatedBlock) } private fun validateExpressionFunctionBinding(expression: Expression.ExpressionFunctionBinding, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { val functionExpression = validateExpression(expression.functionExpression, variableTypes, typeParametersInScope) ?: return null val functionType = functionExpression.type as? Type.FunctionType if (functionType == null) { errors.add(Issue("Attempting to bind expression like a function, but it has a non-function type ${prettyType(functionExpression.type)}", expression.functionExpression.location, IssueLevel.ERROR)) return null } if (expression.bindings.size != functionType.getNumArguments()) { errors.add(Issue("The function binding here expects ${functionType.getNumArguments()} arguments, but ${expression.bindings.size} were given", expression.location, IssueLevel.ERROR)) return null } val bindings = expression.bindings.map { binding -> if (binding == null) { null } else { validateExpression(binding, variableTypes, typeParametersInScope) } } val bindingTypes = bindings.map { if (it == null) null else it.type } val providedChoices = expression.chosenParameters.map { if (it == null) null else validateType(it, typeParametersInScope) } val inferredTypeParameters = inferChosenTypeParameters(functionType, providedChoices, bindingTypes, functionType.toString(), expression.location) ?: return null val typeWithNewParameters = functionType.rebindTypeParameters(inferredTypeParameters) val bindableArgumentTypes = typeWithNewParameters.getBindableArgumentTypes() var isBindingAReference = false for (entry in bindableArgumentTypes.zip(bindings)) { val expectedType = entry.first val binding = entry.second if (binding != null) { // TODO: Make a test where this is necessary if (expectedType == null) { error("Invalid binding") } if (binding.type != expectedType) { errors.add(Issue("A binding is of type ${prettyType(binding.type)} but the expected argument type is ${prettyType(expectedType)}", expression.location, IssueLevel.ERROR)) } if (binding.type.isReference()) { isBindingAReference = true } } } val postBindingType = typeWithNewParameters.rebindArguments(bindingTypes) // This is a defensive check of an expected property while I'm getting this implemented... if (isBindingAReference && !postBindingType.isReference()) { error("Something went wrong") } return TypedExpression.ExpressionFunctionBinding(postBindingType, functionExpression.aliasType, functionExpression, bindings, inferredTypeParameters, providedChoices) } private fun prettyType(type: Type): String { return when (type) { is Type.FunctionType.Ground -> { val referenceString = if (type.isReference()) "&" else "" referenceString + "(" + type.argTypes.map(this::prettyType).joinToString(", ") + ") -> " + prettyType(type.outputType) } is Type.FunctionType.Parameterized -> { val groundType = type.getDefaultGrounding() val referenceString = if (type.isReference()) "&" else "" val typeParametersString = if (type.typeParameters.isEmpty()) { "" } else { "<" + type.typeParameters.joinToString(", ") + ">" } referenceString + typeParametersString + "(" + groundType.argTypes.map(this::prettyType).joinToString(", ") + ") -> " + prettyType(groundType.outputType) } is Type.InternalParameterType -> TODO() is Type.ParameterType -> { type.parameter.name } is Type.NamedType -> { val isRefString = if (type.isReference()) "&" else "" val refString = typesInfo.getSimplestRefForType(type.ref).toString() val parametersString = if (type.parameters.isEmpty()) { "" } else { "<" + type.parameters.joinToString(", ") + ">" } isRefString + refString + parametersString } } } private fun validateNamedFunctionBinding(expression: Expression.NamedFunctionBinding, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { val functionRef = expression.functionRef val resolvedFunctionInfo = typesInfo.getResolvedFunctionInfo(functionRef) when (resolvedFunctionInfo) { is FunctionInfoResult.Error -> { errors.add(Issue(resolvedFunctionInfo.errorMessage, expression.functionRefLocation, IssueLevel.ERROR)) return null } is ResolvedFunctionInfo -> { /* Automatic type guard */ } } val functionInfo = resolvedFunctionInfo.info val bindings = expression.bindings.map { binding -> if (binding == null) { null } else { validateExpression(binding, variableTypes, typeParametersInScope) } } val bindingTypes = bindings.map { binding -> if (binding == null) { null } else { binding.type } } if (expression.bindings.size != functionInfo.type.getNumArguments()) { errors.add(Issue("The function $functionRef expects ${functionInfo.type.getNumArguments()} arguments (with types ${functionInfo.type.argTypes}), but ${expression.bindings.size} were given", expression.functionRefLocation, IssueLevel.ERROR)) return null } val providedChoices = expression.chosenParameters.map { if (it == null) null else validateType(it, typeParametersInScope) } val validatedFunctionType = validateType(functionInfo.type, typeParametersInScope) as? Type.FunctionType ?: return null val inferredTypeParameters = inferChosenTypeParameters(validatedFunctionType, providedChoices, bindingTypes, functionRef.toString(), expression.location) ?: return null val typeWithNewParameters = validatedFunctionType.rebindTypeParameters(inferredTypeParameters) val bindableArgumentTypes = typeWithNewParameters.getBindableArgumentTypes() var isBindingAReference = false for (entry in bindableArgumentTypes.zip(bindings)) { val expectedType = entry.first val binding = entry.second if (binding != null) { // TODO: Make a test where this is necessary if (expectedType == null) { error("Invalid binding") } if (binding.type != expectedType) { errors.add(Issue("A binding is of type ${prettyType(binding.type)} but the expected argument type is ${prettyType(expectedType)}", expression.location, IssueLevel.ERROR)) } if (binding.type.isReference()) { isBindingAReference = true } } } val postBindingType = typeWithNewParameters.rebindArguments(bindingTypes) // This is a defensive check of an expected property while I'm getting this implemented... if (isBindingAReference && !postBindingType.isReference()) { error("Something went wrong") } return TypedExpression.NamedFunctionBinding(postBindingType, AliasType.NotAliased, functionRef, resolvedFunctionInfo.resolvedRef, bindings, inferredTypeParameters, providedChoices) } private fun inferChosenTypeParameters(functionType: Type.FunctionType, providedChoices: List<Type?>, bindingTypes: List<Type?>, functionDescription: String, expressionLocation: Location?): List<Type?>? { // Deal with inference first? // What's left after that? if (functionType !is Type.FunctionType.Parameterized) { return listOf() } val chosenParameters = if (functionType.typeParameters.size == providedChoices.size) { providedChoices } else if (functionType.typeParameters.size < providedChoices.size) { errors.add(Issue("Too many type parameters were supplied for function call/binding for $functionDescription; provided ${providedChoices.size}, but ${functionType.typeParameters.size} were expected, function type was ${prettyType(functionType)}", expressionLocation, IssueLevel.ERROR)) return null } else { // Apply type parameter inference val inferenceSourcesByArgument = functionType.getTypeParameterInferenceSources() val explicitParametersIterator = providedChoices.iterator() val types = inferenceSourcesByArgument.map { inferenceSources -> val inferredType = inferenceSources.stream().map { it.findType(bindingTypes) }.filter { it != null }.findFirst() if (inferredType.isPresent()) { inferredType.get() } else { if (!explicitParametersIterator.hasNext()) { errors.add(Issue("Not enough type parameters were supplied for function call/binding for $functionDescription", expressionLocation, IssueLevel.ERROR)) return null } val chosenParameter = explicitParametersIterator.next() chosenParameter ?: return null } } if (explicitParametersIterator.hasNext()) { errors.add(Issue("The function binding for $functionDescription did not supply all type parameters, but supplied more than the appropriate number for type parameter inference", expressionLocation, IssueLevel.ERROR)) return null } types } if (chosenParameters.size != functionType.typeParameters.size) { // TODO: Hopefully this is impossible to hit now error("Referenced a function $functionDescription with type parameters ${functionType.typeParameters}, but used an incorrect number of type parameters, passing in $chosenParameters") } for ((typeParameter, chosenType) in functionType.typeParameters.zip(chosenParameters)) { if (chosenType != null) { validateTypeParameterChoice(typeParameter, chosenType, expressionLocation) } } return chosenParameters } private fun validateFollowExpression(expression: Expression.Follow, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { val structureExpression = validateExpression(expression.structureExpression, variableTypes, typeParametersInScope) ?: return null val structureNamedType = structureExpression.type as? Type.NamedType if (structureNamedType == null) { errors.add(Issue("Cannot dereference an expression $structureExpression of non-struct, non-interface type ${prettyType(structureExpression.type)}", expression.location, IssueLevel.ERROR)) return null } val structureTypeInfo = typesInfo.getTypeInfo(structureNamedType.originalRef) ?: error("No type info for ${structureNamedType.originalRef}") return when (structureTypeInfo) { is TypeInfo.Struct -> { val memberType = structureTypeInfo.memberTypes[expression.name] if (memberType == null) { errors.add(Issue("Struct type ${prettyType(structureNamedType)} does not have a member named '${expression.name}'", expression.location, IssueLevel.ERROR)) return null } // Type parameters come from the struct definition itself // Chosen types come from the struct type known for the variable val typeParameters = structureTypeInfo.typeParameters val chosenTypes = structureNamedType.parameters for (chosenParameter in chosenTypes) { if (chosenParameter.isReference()) { errors.add(Issue("Reference types cannot be used as parameters", expression.location, IssueLevel.ERROR)) } } val parameterizedType = replaceAndValidateExternalTypeParameters(memberType, typeParameters, chosenTypes) val type = validateType(parameterizedType, typeParametersInScope) ?: return null //TODO: Ground this if needed return TypedExpression.Follow(type, structureExpression.aliasType, structureExpression, expression.name) } is TypeInfo.Union -> { error("Currently we don't allow follows for unions") } is TypeInfo.OpaqueType -> { errors.add(Issue("Cannot dereference an expression of opaque type ${prettyType(structureExpression.type)}", expression.location, IssueLevel.ERROR)) return null } } } private fun replaceAndValidateExternalTypeParameters(originalType: UnvalidatedType, typeParameters: List<TypeParameter>, chosenTypes: List<Type>): UnvalidatedType { // TODO: Check that the parameters are of appropriate types val parameterReplacementMap = typeParameters.map { it.name }.zip(chosenTypes.map(::invalidate)).toMap() val replacedType = originalType.replacingNamedParameterTypes(parameterReplacementMap) return replacedType } private fun validateExpressionFunctionCallExpression(expression: Expression.ExpressionFunctionCall, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { val functionExpression = validateExpression(expression.functionExpression, variableTypes, typeParametersInScope) ?: return null val functionType = functionExpression.type as? Type.FunctionType if (functionType == null) { errors.add(Issue("This expression is called like a function, but has a non-function type ${prettyType(functionExpression.type)}", expression.functionExpression.location, IssueLevel.ERROR)) return null } if (expression.arguments.size != functionType.getNumArguments()) { errors.add(Issue("The function binding here expects ${functionType.getNumArguments()} arguments (with types ${functionType.getDefaultGrounding().argTypes.map(this::prettyType)}), but ${expression.arguments.size} were given", expression.location, IssueLevel.ERROR)) return null } val providedChoices = expression.chosenParameters.map { validateType(it, typeParametersInScope) } if (providedChoices.contains(null)) { return null } val arguments = ArrayList<TypedExpression>() for (untypedArgument in expression.arguments) { val argument = validateExpression(untypedArgument, variableTypes, typeParametersInScope) ?: return null arguments.add(argument) } val argumentTypes = arguments.map(TypedExpression::type) val inferredNullableTypeParameters = inferChosenTypeParameters(functionType, providedChoices, argumentTypes, functionType.toString(), expression.location) ?: return null val inferredTypeParameters = inferredNullableTypeParameters.filterNotNull() val groundFunctionType = functionType.groundWithTypeParameters(inferredTypeParameters) if (argumentTypes != groundFunctionType.argTypes) { errors.add(Issue("The function expression expects arguments with types ${groundFunctionType.argTypes.map(this::prettyType)}, but was given arguments with types ${argumentTypes.map(this::prettyType)}", expression.location, IssueLevel.ERROR)) return null } return TypedExpression.ExpressionFunctionCall(groundFunctionType.outputType, AliasType.NotAliased, functionExpression, arguments, inferredTypeParameters, providedChoices.map { it ?: error("This case should be handled earlier") }) } private fun validateNamedFunctionCallExpression(expression: Expression.NamedFunctionCall, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { val functionRef = expression.functionRef val resolvedFunctionInfo = typesInfo.getResolvedFunctionInfo(functionRef) when (resolvedFunctionInfo) { is FunctionInfoResult.Error -> { errors.add(Issue(resolvedFunctionInfo.errorMessage, expression.functionRefLocation, IssueLevel.ERROR)) return null } is ResolvedFunctionInfo -> { /* Automatic type guard */ } } val functionInfo = resolvedFunctionInfo.info val providedChoices = expression.chosenParameters.map { validateType(it, typeParametersInScope) } if (providedChoices.contains(null)) { return null } val arguments = ArrayList<TypedExpression>() for (untypedArgument in expression.arguments) { val argument = validateExpression(untypedArgument, variableTypes, typeParametersInScope) ?: return null arguments.add(argument) } val argumentTypes = arguments.map(TypedExpression::type) if (expression.arguments.size != functionInfo.type.getNumArguments()) { errors.add(Issue("The function $functionRef expects ${functionInfo.type.getNumArguments()} arguments (with types ${functionInfo.type.argTypes}), but ${expression.arguments.size} were given", expression.functionRefLocation, IssueLevel.ERROR)) return null } val validatedFunctionType = validateType(functionInfo.type, typeParametersInScope) as Type.FunctionType val inferredNullableTypeParameters = inferChosenTypeParameters(validatedFunctionType, providedChoices, argumentTypes, functionRef.toString(), expression.location) ?: return null val inferredTypeParameters = inferredNullableTypeParameters.filterNotNull() val groundFunctionType = validatedFunctionType.groundWithTypeParameters(inferredTypeParameters) if (argumentTypes != groundFunctionType.argTypes) { val paramString = if (inferredTypeParameters.isEmpty()) "" else "<${inferredTypeParameters.map(this::prettyType).joinToString(", ")}>" errors.add(Issue("The function $functionRef$paramString expects arguments with types ${groundFunctionType.argTypes.map(this::prettyType)}, but was given arguments with types ${argumentTypes.map(this::prettyType)}", expression.location, IssueLevel.ERROR)) return null } return TypedExpression.NamedFunctionCall(groundFunctionType.outputType, AliasType.NotAliased, functionRef, resolvedFunctionInfo.resolvedRef, arguments, inferredTypeParameters, providedChoices.map { it ?: error("This case should be handled earlier") }) } private fun validateTypeParameterChoice(typeParameter: TypeParameter, chosenType: Type, location: Location?) { val typeClass = typeParameter.typeClass if (chosenType.isReference()) { errors.add(Issue("Reference types cannot be used as parameters", location, IssueLevel.ERROR)) } if (typeClass != null) { val unused: Any = when (typeClass) { TypeClass.Data -> { if (!typesInfo.isDataType(chosenType)) { errors.add(Issue("Type parameter ${typeParameter.name} requires a data type, but ${prettyType(chosenType)} is not a data type", location, IssueLevel.ERROR)) } else {} } } } } private fun validateLiteralExpression(expression: Expression.Literal, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { val type = validateType(expression.type, typeParametersInScope) ?: return null val typesList = if (type is Type.NamedType) { typesMetadata.typeChains[type.ref]?.getTypesList() ?: listOf(expression.type) } else listOf(expression.type) val validator = getLiteralValidatorForTypeChain(typesList) if (validator == null) { // TODO: Differentiate the error based on types metadata errors.add(Issue("Cannot create a literal for type ${expression.type}", expression.location, IssueLevel.ERROR)) return null } val isValid = validator.validate(expression.literal) if (!isValid) { errors.add(Issue("Invalid literal value '${expression.literal}' for type '${expression.type}'", expression.location, IssueLevel.ERROR)) } // TODO: Someday we need to check for literal values that violate "requires" blocks at validation time return TypedExpression.Literal(type, AliasType.NotAliased, expression.literal) } private fun getLiteralValidatorForTypeChain(types: List<UnvalidatedType>): LiteralValidator? { val lastType = types.last() if (lastType is UnvalidatedType.NamedType && isNativeType(lastType) && lastType.ref.id == NativeOpaqueType.INTEGER.id) { return LiteralValidator.INTEGER } if (lastType is UnvalidatedType.NamedType && isNativeType(lastType) && lastType.ref.id == NativeOpaqueType.BOOLEAN.id) { return LiteralValidator.BOOLEAN } if (types.size >= 2) { val secondToLastType = types[types.size - 2] if (secondToLastType is UnvalidatedType.NamedType) { val typeRef = secondToLastType.ref if (isNativeType(secondToLastType) && typeRef.id == NativeStruct.STRING.id) { return LiteralValidator.STRING } } } return null } private fun isNativeType(type: UnvalidatedType.NamedType): Boolean { val resolved = typesInfo.getResolvedTypeInfo(type.ref) return when (resolved) { is ResolvedTypeInfo -> isNativeModule(resolved.resolvedRef.module) is TypeInfoResult.Error -> false } } private fun validateListLiteralExpression(expression: Expression.ListLiteral, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { val chosenParameter = validateType(expression.chosenParameter, typeParametersInScope) ?: return null if (chosenParameter.isReference()) { errors.add(Issue("Reference types cannot be used as parameters", expression.location, IssueLevel.ERROR)) } val listType = NativeOpaqueType.LIST.getType(chosenParameter) var itemErrorFound = false val contents = ArrayList<TypedExpression>() for (itemExpression in expression.contents) { val validated = validateExpression(itemExpression, variableTypes, typeParametersInScope) if (validated == null) { itemErrorFound = true } else { if (validated.type != chosenParameter) { errors.add(Issue("Expression type ${prettyType(validated.type)} does not match the list item type ${prettyType(chosenParameter)}", itemExpression.location, IssueLevel.ERROR)) itemErrorFound = true } else { contents.add(validated) } } } if (itemErrorFound) { return null } return TypedExpression.ListLiteral(listType, AliasType.NotAliased, contents, chosenParameter) } private fun validateIfThenExpression(expression: Expression.IfThen, variableTypes: Map<String, Type>, typeParametersInScope: Map<String, TypeParameter>): TypedExpression? { val condition = validateExpression(expression.condition, variableTypes, typeParametersInScope) ?: return null if (condition.type != NativeOpaqueType.BOOLEAN.getType()) { errors.add(Issue("The condition of an if expression should be a Boolean, but is of type ${prettyType(condition.type)}", expression.condition.location, IssueLevel.ERROR)) } // TODO: Reconsider how references interact with if/then expressions val thenBlock = validateBlock(expression.thenBlock, variableTypes, typeParametersInScope) ?: return null val elseBlock = validateBlock(expression.elseBlock, variableTypes, typeParametersInScope) ?: return null val type = typeUnion(thenBlock.type, elseBlock.type) if (type == null) { errors.add(Issue("Cannot reconcile types of 'then' block (${prettyType(thenBlock.type)}) and 'else' block (${prettyType(elseBlock.type)})", expression.location, IssueLevel.ERROR)) return null } val aliasType = if (thenBlock.lastStatementAliasType == AliasType.NotAliased && elseBlock.lastStatementAliasType == AliasType.NotAliased) { AliasType.NotAliased } else { AliasType.PossiblyAliased } return TypedExpression.IfThen(type, aliasType, condition, thenBlock, elseBlock) } private fun typeUnion(type1: Type, type2: Type): Type? { // TODO: Handle actual type unions, inheritance as these things get added // TODO: Then move this stuff to the API level if (type1 == type2) { return type1 } return null } private fun validateVariableExpression(expression: Expression.Variable, variableTypes: Map<String, Type>): TypedExpression? { val type = variableTypes[expression.name] if (type != null) { return TypedExpression.Variable(type, AliasType.PossiblyAliased, expression.name) } else { errors.add(Issue("Unknown variable ${expression.name}", expression.location, IssueLevel.ERROR)) return null } } private fun validateStructs(structs: List<UnvalidatedStruct>): Map<EntityId, Struct> { val validatedStructs = LinkedHashMap<EntityId, Struct>() for (struct in structs) { val validatedStruct = validateStruct(struct) if (validatedStruct != null) { validatedStructs.put(struct.id, validatedStruct) } } return validatedStructs } private fun validateStruct(struct: UnvalidatedStruct): Struct? { val members = validateMembers(struct, struct.typeParameters.associateBy(TypeParameter::name)) ?: return null val memberTypes = members.associate { member -> member.name to member.type } val uncheckedRequires = struct.requires val requires = if (uncheckedRequires != null) { validateBlock(uncheckedRequires, memberTypes, struct.typeParameters.associateBy(TypeParameter::name)) ?: return null } else { null } if (requires != null && requires.type != NativeOpaqueType.BOOLEAN.getType()) { val message = "Struct ${struct.id} has a requires block with inferred type ${prettyType(requires.type)}, but the type should be Boolean" val location = struct.requires!!.location errors.add(Issue(message, location, IssueLevel.ERROR)) } if (memberTypes.values.any(Type::isReference)) { errors.add(Issue("Struct ${struct.id} has members with reference types, which are not allowed", struct.idLocation, IssueLevel.ERROR)) } return Struct(struct.id, moduleId, struct.typeParameters, members, requires, struct.annotations) } private fun validateMembers(struct: UnvalidatedStruct, typeParametersInScope: Map<String, TypeParameter>): List<Member>? { // Check for name duplication val allNames = HashSet<String>() for (member in struct.members) { if (allNames.contains(member.name)) { // TODO: Improve position of message errors.add(Issue("Struct ${struct.id} has multiple members named ${member.name}", struct.idLocation, IssueLevel.ERROR)) } allNames.add(member.name) } return struct.members.map { member -> val type = validateType(member.type, typeParametersInScope) ?: return null Member(member.name, type) } } private fun validateUnions(unions: List<UnvalidatedUnion>): Map<EntityId, Union> { val validatedUnions = LinkedHashMap<EntityId, Union>() for (union in unions) { val validatedUnion = validateUnion(union) if (validatedUnion != null) { validatedUnions.put(union.id, validatedUnion) } } return validatedUnions } private fun validateUnion(union: UnvalidatedUnion): Union? { if (union.options.isEmpty()) { errors.add(Issue("A union must include at least one option", union.idLocation, IssueLevel.ERROR)) return null } val options = validateOptions(union.options, union.typeParameters.associateBy(TypeParameter::name)) ?: return null return Union(union.id, moduleId, union.typeParameters, options, union.annotations) } private fun validateOptions(options: List<UnvalidatedOption>, unionTypeParameters: Map<String, TypeParameter>): List<Option>? { val namesAlreadySeen = HashSet<String>() return options.map { option -> if (namesAlreadySeen.contains(option.name)) { errors.add(Issue("Duplicate option name ${option.name}", option.idLocation, IssueLevel.ERROR)) return null } namesAlreadySeen.add(option.name) val unvalidatedType = option.type val type = if (unvalidatedType == null) null else validateType(unvalidatedType, unionTypeParameters) if (type != null && type.isReference()) { errors.add(Issue("Reference types are not allowed in unions", option.idLocation, IssueLevel.ERROR)) } if (option.name == "when") { errors.add(Issue("Union options cannot be named 'when'", option.idLocation, IssueLevel.ERROR)) return null } Option(option.name, type) } } } private fun List<Argument>.asVariableTypesMap(): Map<String, Type> { return this.map{arg -> Pair(arg.name, arg.type)}.toMap() }
apache-2.0
dcc03c6087b176758cf412c64f9c33a6
50.278031
296
0.640813
5.423971
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sqlite/SQLiteHelpers.kt
2
2689
package abi43_0_0.expo.modules.sqlite import java.io.File import java.io.IOException import java.util.ArrayList @Throws(IOException::class) internal fun ensureDirExists(dir: File): File { if (!dir.isDirectory) { if (dir.isFile) { throw IOException("Path '$dir' points to a file, but must point to a directory.") } if (!dir.mkdirs()) { var additionalErrorMessage = "" if (dir.exists()) { additionalErrorMessage = "Path already points to a non-normal file." } if (dir.parentFile == null) { additionalErrorMessage = "Parent directory is null." } throw IOException("Couldn't create directory '$dir'. $additionalErrorMessage") } } return dir } internal fun pluginResultsToPrimitiveData(results: List<SQLiteModule.SQLitePluginResult>): List<Any> { return results.map { convertPluginResultToArray(it) } } private fun convertPluginResultToArray(result: SQLiteModule.SQLitePluginResult): List<Any?> { val rowsContent = result.rows.map { row -> row.map { value -> when (value) { null -> null is String -> value is Boolean -> value else -> (value as Number).toDouble() } } } return arrayListOf( result.error?.message, result.insertId.toInt(), result.rowsAffected, result.columns, rowsContent ) } private fun isPragma(str: String): Boolean { return startsWithCaseInsensitive(str, "pragma") } private fun isPragmaReadOnly(str: String): Boolean { return isPragma(str) && !str.contains('=') } internal fun isSelect(str: String): Boolean { return startsWithCaseInsensitive(str, "select") || isPragmaReadOnly(str) } internal fun isInsert(str: String): Boolean { return startsWithCaseInsensitive(str, "insert") } internal fun isUpdate(str: String): Boolean { return startsWithCaseInsensitive(str, "update") } internal fun isDelete(str: String): Boolean { return startsWithCaseInsensitive(str, "delete") } private fun startsWithCaseInsensitive(str: String, substr: String): Boolean { return str.trimStart().startsWith(substr, true) } internal fun convertParamsToStringArray(paramArrayArg: ArrayList<Any?>): Array<String?> { return paramArrayArg.map { param -> when (param) { is String -> unescapeBlob(param) is Boolean -> if (param) "1" else "0" is Double -> param.toString() null -> null else -> throw ClassCastException("Could not find proper SQLite data type for argument: $") } }.toTypedArray() } private fun unescapeBlob(str: String): String { return str.replace("\u0001\u0001", "\u0000") .replace("\u0001\u0002", "\u0001") .replace("\u0002\u0002", "\u0002") }
bsd-3-clause
529db7cb54b08342b7fe6c5dec9fb4c2
27.010417
102
0.682038
3.919825
false
false
false
false
satamas/fortran-plugin
src/main/kotlin/org/jetbrains/fortran/lang/resolve/FortranLabelReferenceImpl.kt
1
1115
package org.jetbrains.fortran.lang.resolve import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.fortran.lang.psi.FortranProgramUnit import org.jetbrains.fortran.lang.psi.ext.FortranNamedElement import org.jetbrains.fortran.lang.psi.impl.FortranLabelDeclImpl import org.jetbrains.fortran.lang.psi.mixin.FortranLabelImplMixin class FortranLabelReferenceImpl(element: FortranLabelImplMixin) : FortranReferenceBase<FortranLabelImplMixin>(element), FortranReference { override val FortranLabelImplMixin.referenceAnchor: PsiElement get() = integerliteral override fun resolveInner(incompleteCode: Boolean): List<FortranNamedElement> { val programUnit = PsiTreeUtil.getParentOfType(element, FortranProgramUnit::class.java) ?: return emptyList() val labelDeclarations = PsiTreeUtil.findChildrenOfType(programUnit, FortranLabelDeclImpl::class.java) return if(incompleteCode){ labelDeclarations.toList() } else{ labelDeclarations.filter { element.getLabelValue() == it.getLabelValue() } } } }
apache-2.0
eed84156e753ce458569b542a6abec01
43.64
116
0.778475
4.785408
false
false
false
false
Soya93/Extract-Refactoring
platform/configuration-store-impl/src/FileBasedStorage.kt
4
10178
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.components.impl.stores.StorageUtil import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.LineSeparator import com.intellij.util.loadElement import org.jdom.Element import org.jdom.JDOMException import org.jdom.Parent import java.io.File import java.io.IOException import java.nio.ByteBuffer open class FileBasedStorage(file: File, fileSpec: String, rootElementName: String, pathMacroManager: TrackingPathMacroSubstitutor? = null, roamingType: RoamingType? = null, provider: StreamProvider? = null) : XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) { private @Volatile var cachedVirtualFile: VirtualFile? = null private var lineSeparator: LineSeparator? = null private var blockSavingTheContent = false @Volatile var file = file private set init { if (ApplicationManager.getApplication().isUnitTestMode && file.path.startsWith('$')) { throw AssertionError("It seems like some macros were not expanded for path: $file") } } protected open val isUseXmlProlog: Boolean = false // we never set io file to null fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: File?) { cachedVirtualFile = virtualFile if (ioFileIfChanged != null) { file = ioFileIfChanged } } override fun createSaveSession(states: StateMap) = FileSaveSession(states, this) protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) : XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) { override fun save() { if (!storage.blockSavingTheContent) { super.save() } } override fun saveLocally(element: Element?) { if (storage.lineSeparator == null) { storage.lineSeparator = if (storage.isUseXmlProlog) LineSeparator.LF else LineSeparator.getSystemLineSeparator() } val virtualFile = storage.getVirtualFile() if (element == null) { deleteFile(storage.file, this, virtualFile) storage.cachedVirtualFile = null } else { storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, element, if (storage.isUseXmlProlog) storage.lineSeparator!! else LineSeparator.LF, storage.isUseXmlProlog) } } } fun getVirtualFile(): VirtualFile? { var result = cachedVirtualFile if (result == null) { result = LocalFileSystem.getInstance().findFileByIoFile(file) cachedVirtualFile = result } return cachedVirtualFile } override fun loadLocalData(): Element? { blockSavingTheContent = false try { val file = getVirtualFile() if (file == null || file.isDirectory || !file.isValid) { LOG.debug { "Document was not loaded for $fileSpec file is ${if (file == null) "null" else "directory"}" } } else if (file.length == 0L) { processReadException(null) } else { val charBuffer = CharsetToolkit.UTF8_CHARSET.decode(ByteBuffer.wrap(file.contentsToByteArray())) lineSeparator = detectLineSeparators(charBuffer, if (isUseXmlProlog) null else LineSeparator.LF) return loadElement(charBuffer) } } catch (e: JDOMException) { processReadException(e) } catch (e: IOException) { processReadException(e) } return null } private fun processReadException(e: Exception?) { val contentTruncated = e == null blockSavingTheContent = !contentTruncated && (PROJECT_FILE == fileSpec || fileSpec.startsWith(PROJECT_CONFIG_DIR) || fileSpec == StoragePathMacros.MODULE_FILE || fileSpec == StoragePathMacros.WORKSPACE_FILE) if (!ApplicationManager.getApplication().isUnitTestMode && !ApplicationManager.getApplication().isHeadlessEnvironment) { if (e != null) { LOG.info(e) } Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, "Load Settings", "Cannot load settings from file '$file': ${if (contentTruncated) "content truncated" else e!!.message}\n${if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"}", NotificationType.WARNING) .notify(null) } } override fun toString() = file.systemIndependentPath } fun writeFile(file: File?, requestor: Any, virtualFile: VirtualFile?, element: Element, lineSeparator: LineSeparator, prependXmlProlog: Boolean): VirtualFile { val result = if (file != null && (virtualFile == null || !virtualFile.isValid)) { StorageUtil.getOrCreateVirtualFile(requestor, file) } else { virtualFile!! } if (LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) { val content = element.toBufferExposingByteArray(lineSeparator.separatorString) if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) { throw IllegalStateException("Content equals, but it must be handled not on this level: ${result.name}") } else if (StorageUtil.DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) { StorageUtil.DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}\n---------" } } doWrite(requestor, result, element, lineSeparator, prependXmlProlog) return result } private val XML_PROLOG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".toByteArray() private fun isEqualContent(result: VirtualFile, lineSeparator: LineSeparator, content: BufferExposingByteArrayOutputStream, prependXmlProlog: Boolean): Boolean { val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size + lineSeparator.separatorBytes.size if (result.length.toInt() != (headerLength + content.size())) { return false } val oldContent = result.contentsToByteArray() if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) || !ArrayUtil.startsWith(oldContent, XML_PROLOG.size, lineSeparator.separatorBytes))) { return false } for (i in headerLength..oldContent.size - 1) { if (oldContent[i] != content.internalBuffer[i - headerLength]) { return false } } return true } private fun doWrite(requestor: Any, file: VirtualFile, content: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) { LOG.debug { "Save ${file.presentableUrl}" } if (!file.isWritable) { // may be element is not long-lived, so, we must write it to byte array val byteArray = if (content is Element) content.toBufferExposingByteArray(lineSeparator.separatorString) else (content as BufferExposingByteArrayOutputStream) throw ReadOnlyModificationException(file, StateStorage.SaveSession { doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog) }) } runWriteAction { file.getOutputStream(requestor).use { out -> if (prependXmlProlog) { out.write(XML_PROLOG) out.write(lineSeparator.separatorBytes) } if (content is Element) { JDOMUtil.writeParent(content, out, lineSeparator.separatorString) } else { (content as BufferExposingByteArrayOutputStream).writeTo(out) } } } } internal fun Parent.toBufferExposingByteArray(lineSeparator: String = "\n"): BufferExposingByteArrayOutputStream { val out = BufferExposingByteArrayOutputStream(512) JDOMUtil.writeParent(this, out, lineSeparator) return out } internal fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator?): LineSeparator { for (c in chars) { if (c == '\r') { return LineSeparator.CRLF } else if (c == '\n') { // if we are here, there was no \r before return LineSeparator.LF } } return defaultSeparator ?: LineSeparator.getSystemLineSeparator() } private fun deleteFile(file: File, requestor: Any, virtualFile: VirtualFile?) { if (virtualFile == null) { LOG.warn("Cannot find virtual file ${file.absolutePath}") } if (virtualFile == null) { if (file.exists()) { FileUtil.delete(file) } } else if (virtualFile.exists()) { if (virtualFile.isWritable) { deleteFile(requestor, virtualFile) } else { throw ReadOnlyModificationException(virtualFile, StateStorage.SaveSession { deleteFile(requestor, virtualFile) }) } } } fun deleteFile(requestor: Any, virtualFile: VirtualFile) { runWriteAction { virtualFile.delete(requestor) } } internal class ReadOnlyModificationException(val file: VirtualFile, val session: StateStorage.SaveSession?) : RuntimeException()
apache-2.0
12692459cd2a8b060ed442ab5146fc19
37.411321
215
0.721556
4.807747
false
false
false
false
EventFahrplan/EventFahrplan
engelsystem/src/test/kotlin/info/metadude/android/eventfahrplan/engelsystem/utils/UriParserTest.kt
1
2639
package info.metadude.android.eventfahrplan.engelsystem.utils import com.google.common.truth.Truth.assertThat import info.metadude.android.eventfahrplan.engelsystem.models.EngelsystemUri import org.junit.Assert.fail import org.junit.Test import java.net.URISyntaxException class UriParserTest { private val uriParser = UriParser() @Test fun parseUriWithEmptyString() { try { uriParser.parseUri("") failExpectingUriSyntaxException() } catch (e: URISyntaxException) { assertThat(e.message).contains("Empty URL") } } @Test fun parseUriWithoutScheme() { try { uriParser.parseUri("example.com") failExpectingUriSyntaxException() } catch (e: URISyntaxException) { assertThat(e.message).contains("Scheme is missing") } } @Test fun parseUriWithoutHost() { try { uriParser.parseUri("https://?key=a1b2c3") failExpectingUriSyntaxException() } catch (e: URISyntaxException) { assertThat(e.message).contains("Host is missing") } } @Test fun parseUriWithoutPath() { try { uriParser.parseUri("https://example.com?key=a1b2c3") failExpectingUriSyntaxException() } catch (e: URISyntaxException) { assertThat(e.message).contains("Path is missing") } } @Test fun parseUriWithoutQuery() { try { uriParser.parseUri("https://example.com/foo/file.json") failExpectingUriSyntaxException() } catch (e: URISyntaxException) { assertThat(e.message).contains("Query is missing") } } @Test fun parseUriWithoutApiKey() { try { uriParser.parseUri("https://example.com/foo/file.json?key") failExpectingUriSyntaxException() } catch (e: URISyntaxException) { assertThat(e.message).contains("API key is missing") } } private fun failExpectingUriSyntaxException() { fail("Expect a URISyntaxException to be thrown.") } @Test fun parseUriWithCompleteUrl() { val uri = EngelsystemUri("https://example.com", "foo/file.json", "a1b2c3") assertThat(uriParser.parseUri("https://example.com/foo/file.json?key=a1b2c3")).isEqualTo(uri) } @Test fun parseUriWithCompleteUrlWithPort() { val uri = EngelsystemUri("https://example.com:3000", "foo/file.json", "a1b2c3") assertThat(uriParser.parseUri("https://example.com:3000/foo/file.json?key=a1b2c3")).isEqualTo(uri) } }
apache-2.0
371c5865989221f7db8ee99fbd64aa11
28.651685
106
0.622963
4.169036
false
true
false
false
saschpe/PlanningPoker
mobile/src/main/java/saschpe/poker/customtabs/CustomTabs.kt
1
2546
/* * Copyright 2018 Sascha Peilicke * * 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 saschpe.poker.customtabs import android.content.Context import android.net.Uri import androidx.browser.customtabs.CustomTabsIntent import androidx.core.content.res.ResourcesCompat import saschpe.android.customtabs.CustomTabsHelper import saschpe.android.customtabs.WebViewFallback import saschpe.poker.R import saschpe.poker.util.BitmapHelper object CustomTabs { private const val PRIVACY_POLICY_URL = "https://sites.google.com/view/planningpoker/privacy-policy" /** * Start Privacy Policy custom tab. * * See https://developer.chrome.com/multidevice/android/customtabs * * @param context Activity context */ fun startPrivacyPolicy(context: Context) = startUrl(context, PRIVACY_POLICY_URL) private fun startUrl(context: Context, url: String, animate: Boolean = false) { val customTabsIntentBuilder = getDefaultCustomTabsIntentBuilder(context) if (animate) { customTabsIntentBuilder .setStartAnimations(context, R.anim.slide_in_right, R.anim.slide_out_left) .setExitAnimations(context, R.anim.slide_in_left, R.anim.slide_out_right) } val customTabsIntent = customTabsIntentBuilder.build() CustomTabsHelper.addKeepAliveExtra(context, customTabsIntent.intent) CustomTabsHelper.openCustomTab(context, customTabsIntent, Uri.parse(url), WebViewFallback()) } private fun getDefaultCustomTabsIntentBuilder(context: Context): CustomTabsIntent.Builder { val builder = CustomTabsIntent.Builder() .addDefaultShareMenuItem() .setToolbarColor(ResourcesCompat.getColor(context.resources, R.color.primary, null)) .setShowTitle(true) val backArrow = BitmapHelper.getBitmapFromVectorDrawable(context, R.drawable.ic_arrow_back) if (backArrow != null) { builder.setCloseButtonIcon(backArrow) } return builder } }
apache-2.0
e69cbeea3b3e807c58f8bd4c73c848cf
38.169231
103
0.725452
4.367067
false
false
false
false
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/module/mail/DefaultMailer.kt
3
4790
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.mail import com.mycollab.common.domain.MailRecipientField import com.mycollab.configuration.EmailConfiguration import com.mycollab.core.MyCollabException import com.mycollab.core.utils.StringUtils import org.apache.commons.mail.EmailConstants import org.apache.commons.mail.EmailException import org.apache.commons.mail.HtmlEmail import org.slf4j.LoggerFactory /** * @author MyCollab Ltd. * @since 1.0 */ class DefaultMailer(private val emailConf: EmailConfiguration) : IMailer { private fun getBasicEmail(fromEmail: String, fromName: String, toEmail: List<MailRecipientField>, ccEmail: List<MailRecipientField>?, bccEmail: List<MailRecipientField>?, subject: String, html: String): HtmlEmail { try { val email = HtmlEmail() email.hostName = emailConf.smtphost email.setSmtpPort(emailConf.port) email.isStartTLSEnabled = emailConf.startTls email.isSSLOnConnect = emailConf.ssl email.setFrom(fromEmail, fromName) email.setCharset(EmailConstants.UTF_8) toEmail.forEach { when { isValidate(it.email) && isValidate(it.name) -> email.addTo(it.email, it.name) else -> LOG.error("Invalid cc email input: ${it.email}---${it.email}") } } ccEmail?.forEach { when { isValidate(it.email) && isValidate(it.name) -> email.addCc(it.email, it.name) else -> LOG.error("Invalid cc email input: ${it.email}---${it.email}") } } bccEmail?.forEach { when { isValidate(it.email) && isValidate(it.name) -> email.addBcc(it.email, it.name) else -> LOG.error("Invalid cc email input: ${it.email}---${it.email}") } } if (emailConf.username != null) { email.setAuthentication(emailConf.username, emailConf.password) } email.subject = subject if (StringUtils.isNotBlank(html)) { email.setHtmlMsg(html) email.setTextMsg(StringUtils.convertHtmlToPlainText(html)) } return email } catch (e: EmailException) { LOG.info("Email content: $subject \n $html") throw MyCollabException(e) } } override fun sendHTMLMail(fromEmail: String, fromName: String, toEmails: List<MailRecipientField>, ccEmails: List<MailRecipientField>?, bccEmails: List<MailRecipientField>?, subject: String, html: String) { try { val email = getBasicEmail(fromEmail, fromName, toEmails, ccEmails, bccEmails, subject, html) email.send() } catch (e: EmailException) { LOG.info("Email content: $subject \n $html") throw MyCollabException(e) } } override fun sendHTMLMail(fromEmail: String, fromName: String, toEmails: List<MailRecipientField>, ccEmails: List<MailRecipientField>?, bccEmails: List<MailRecipientField>?, subject: String, html: String, attachments: List<AttachmentSource>?) { try { when (attachments) { null -> sendHTMLMail(fromEmail, fromName, toEmails, ccEmails, bccEmails, subject, html) else -> { val email = getBasicEmail(fromEmail, fromName, toEmails, ccEmails, bccEmails, subject, html) attachments.forEach { email.attach(it.attachmentObj) } email.send() } } } catch (e: EmailException) { throw MyCollabException(e) } } private fun isValidate(value: String?) = StringUtils.isNotBlank(value) companion object { private val LOG = LoggerFactory.getLogger(DefaultMailer::class.java) } }
agpl-3.0
0c77547a7f76a5073df9b0bd753aaa79
38.578512
112
0.602005
4.442486
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/widgets/ratingbar/ScaleRatingBar.kt
2
2049
package ru.fantlab.android.ui.widgets.ratingbar import android.content.Context import android.util.AttributeSet import android.view.animation.AnimationUtils import ru.fantlab.android.R class ScaleRatingBar : AnimationRatingBar { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override fun emptyRatingBar() { if (mRunnable != null) { mHandler?.removeCallbacksAndMessages(mRunnableToken) } val delay: Long = 0 for (view in mPartialViews) { mHandler?.postDelayed({ view.setEmpty() }, delay + 5.toShort()) } } override fun fillRatingBar(rating: Float) { if (mRunnable != null) { mHandler?.removeCallbacksAndMessages(mRunnableToken) } for (partialView in mPartialViews) { val ratingViewId = partialView.tag as Int val maxIntOfRating = Math.ceil(rating.toDouble()) if (ratingViewId > maxIntOfRating) { partialView.setEmpty() continue } if (isInEditMode) { if (ratingViewId.toDouble() == maxIntOfRating) { partialView.setPartialFilled(rating) } else { partialView.setFilled() } } else { mRunnable = getAnimationRunnable(rating, partialView, ratingViewId, maxIntOfRating) postRunnable(mRunnable!!, ANIMATION_DELAY) } } } private fun getAnimationRunnable(rating: Float, partialView: PartialView, ratingViewId: Int, maxIntOfRating: Double): Runnable { return Runnable { if (ratingViewId.toDouble() == maxIntOfRating) { partialView.setPartialFilled(rating) } else { partialView.setFilled() } if (ratingViewId.toFloat() == rating) { val scaleUp = AnimationUtils.loadAnimation(context, R.anim.scale_up) val scaleDown = AnimationUtils.loadAnimation(context, R.anim.scale_down) partialView.startAnimation(scaleUp) partialView.startAnimation(scaleDown) } } } companion object { private val ANIMATION_DELAY: Long = 15 } }
gpl-3.0
67628300f28a07129b34506a1feacf36
25.61039
129
0.725232
3.626549
false
false
false
false
0x1bad1d3a/Kaku
app/src/main/java/ca/fuwafuwa/kaku/Windows/Views/KanjiCharacterView.kt
2
7928
package ca.fuwafuwa.kaku.Windows.Views import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.util.Log import android.util.TypedValue import android.view.GestureDetector import android.view.Gravity import android.view.MotionEvent import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import ca.fuwafuwa.kaku.* import ca.fuwafuwa.kaku.Ocr.BoxParams import ca.fuwafuwa.kaku.Windows.* import ca.fuwafuwa.kaku.Windows.Data.DisplayDataOcr import ca.fuwafuwa.kaku.Windows.Data.ISquareChar import ca.fuwafuwa.kaku.Windows.Interfaces.ICopyText import ca.fuwafuwa.kaku.Windows.Interfaces.IRecalculateKanjiViews import ca.fuwafuwa.kaku.Windows.Interfaces.ISearchPerformer /** * Created by 0xbad1d3a5 on 5/5/2016. */ class KanjiCharacterView : FrameLayout, GestureDetector.OnGestureListener, IRecalculateKanjiViews { private lateinit var mContext: Context private lateinit var mGestureDetector: GestureDetector private lateinit var mWindowCoordinator: WindowCoordinator private lateinit var mSearchPerformer: ISearchPerformer private lateinit var mKanjiChoiceWindow: KanjiChoiceWindow private lateinit var mEditWindow: EditWindow private lateinit var mSquareChar: ISquareChar private lateinit var mKanjiTextView: TextView private lateinit var mIconImageView: ImageView private var mCellSizePx: Int = 0 private var mScrollStartEvent: MotionEvent? = null constructor(context: Context) : super(context) { Init(context) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { Init(context) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { Init(context) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { Init(context) } private fun Init(context: Context) { mContext = context mGestureDetector = GestureDetector(mContext, this) mKanjiTextView = TextView(mContext) mKanjiTextView.gravity = Gravity.CENTER mKanjiTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20.toFloat()) mKanjiTextView.setTextColor(Color.BLACK) addView(mKanjiTextView) mIconImageView = ImageView(mContext) mIconImageView.visibility = INVISIBLE addView(mIconImageView) } fun getSquareChar(): ISquareChar { return mSquareChar } fun setDependencies(windowCoordinator: WindowCoordinator, searchPerformer: ISearchPerformer) { mWindowCoordinator = windowCoordinator mSearchPerformer = searchPerformer mKanjiChoiceWindow = mWindowCoordinator.getWindowOfType(WINDOW_KANJI_CHOICE) mEditWindow = mWindowCoordinator.getWindowOfType(WINDOW_EDIT) } fun setText(squareChar: ISquareChar) { mSquareChar = squareChar mKanjiTextView.text = squareChar.char } fun setCellSize(px: Int) { mCellSizePx = dpToPx(context, pxToDp(context, px) - 2) } fun highlight() { background = mContext.getDrawable(R.drawable.bg_translucent_border_0_blue_blue) } fun highlightLight() { background = mContext.getDrawable(R.drawable.bg_transparent_border_0_nil_default) } fun unhighlight() { background = null } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val cellWidthSpec = View.MeasureSpec.makeMeasureSpec(mCellSizePx, View.MeasureSpec.EXACTLY) val cellHeightSpec = View.MeasureSpec.makeMeasureSpec(mCellSizePx, View.MeasureSpec.EXACTLY) for (i in 0 until childCount) { getChildAt(i).measure(cellWidthSpec, cellHeightSpec) } setMeasuredDimension(mCellSizePx, mCellSizePx) } override fun onTouchEvent(e: MotionEvent): Boolean { mGestureDetector.onTouchEvent(e) if (e.action == MotionEvent.ACTION_UP) { visibility = View.VISIBLE if (mScrollStartEvent != null) { mScrollStartEvent = null mKanjiTextView.visibility = View.VISIBLE mIconImageView.visibility = View.INVISIBLE val choiceResult = mKanjiChoiceWindow.onSquareScrollEnd(e) when (choiceResult.first) { ChoiceResultType.SWAP -> { mKanjiTextView.text = choiceResult.second mSquareChar.text = choiceResult.second recalculateKanjiViews() } ChoiceResultType.EDIT -> { val window = getProperWindow<Window>() if (mSquareChar.displayData is DisplayDataOcr) { window.hide() } mEditWindow.setInfo(mSquareChar) mEditWindow.setInputDoneCallback(this) mEditWindow.show() } ChoiceResultType.DELETE -> { mSquareChar.text = "" recalculateKanjiViews() } ChoiceResultType.NONE -> { // Do nothing } } } } return true } override fun recalculateKanjiViews() { val cwindow = getProperWindow<IRecalculateKanjiViews>() cwindow.recalculateKanjiViews() val window = getProperWindow<Window>() window.show() } override fun onSingleTapUp(e: MotionEvent): Boolean { highlightLight() mSquareChar.userTouched = true mSearchPerformer.performSearch(mSquareChar) return true } override fun onScroll(motionEvent: MotionEvent, motionEvent1: MotionEvent, v: Float, v1: Float): Boolean { // scroll event start if (mScrollStartEvent == null) { Log.d(TAG, "ScrollStart") mScrollStartEvent = motionEvent unhighlight() mKanjiTextView.visibility = View.INVISIBLE mIconImageView.visibility = View.VISIBLE mIconImageView.setImageResource(R.drawable.icon_swap) mKanjiChoiceWindow.onSquareScrollStart(mSquareChar, getKanjiBoxParams()) } // scroll event continuing else { Log.d(TAG, "ScrollContinue") mIconImageView.setImageResource(mKanjiChoiceWindow.onSquareScroll(motionEvent1)) } return true } override fun onDown(motionEvent: MotionEvent): Boolean { return false } override fun onFling(motionEvent: MotionEvent, motionEvent1: MotionEvent, v: Float, v1: Float): Boolean { return false } override fun onLongPress(motionEvent: MotionEvent) { val window = getProperWindow<ICopyText>() window.copyText() } override fun onShowPress(e: MotionEvent?) { } private fun <WindowType> getProperWindow() : WindowType { return if (mSquareChar.displayData.instantMode) { mWindowCoordinator.getWindowOfType(WINDOW_INSTANT_KANJI) } else { mWindowCoordinator.getWindowOfType(WINDOW_INFO) } } private fun getKanjiBoxParams() : BoxParams { var pos = IntArray(2) getLocationOnScreen(pos) return BoxParams(pos[0], pos[1], width, height) } companion object { private val TAG = KanjiCharacterView::class.java.name } }
bsd-3-clause
ae0f23719c856194c4b883185b262f88
28.692884
142
0.632316
4.834146
false
false
false
false
EmpowerOperations/getoptk
src/main/kotlin/com/empowerops/getoptk/CakeParser.kt
1
964
package com.empowerops.getoptk //import me.sargunvohra.lib.cakeparse.api.* //import me.sargunvohra.lib.cakeparse.lexer.Token //import me.sargunvohra.lib.cakeparse.converter.BaseParser //import me.sargunvohra.lib.cakeparse.converter.Parser //import me.sargunvohra.lib.cakeparse.converter.Result object CakeParser { // // object P { // // val lParen = token("lParen", "\\(") // val rParen = token("rParen", "\\)") // val epsilon = token("epsilon", "") // // // // then put all refs // val parenRef: Parser<Token> = ref({ paren }) // // // then put all rules // val paren = (lParen then parenRef before rParen) //or BaseParser { input -> Result(epsilon, input) } // // } // // fun buildAST(args: Array<String>, opts: List<CommandLineOption<*>>){ // // val tokens = setOf(P.lParen, P.rParen) // // val result = tokens.lexer().lex("").parseToEnd(P.paren).value // // val x = 4; // } }
apache-2.0
980197cfbde010fa977670ff2a451030
26.571429
110
0.610996
3.30137
false
false
false
false
felipebz/sonar-plsql
sonar-zpa-plugin/src/main/kotlin/org/sonar/plsqlopen/rules/SonarQubeRuleMetadataLoader.kt
1
2831
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.rules import org.sonar.plsqlopen.utils.getAnnotation import org.sonar.plugins.plsqlopen.api.annotations.Priority import java.lang.reflect.Field import org.sonar.check.Priority as SonarPriority import org.sonar.check.Rule as SonarRule import org.sonar.check.RuleProperty as SonarRuleProperty class SonarQubeRuleMetadataLoader : RuleMetadataLoader() { override fun getRuleAnnotation(annotatedClassOrObject: Any): RuleData? { val ruleAnnotation = super.getRuleAnnotation(annotatedClassOrObject) if (ruleAnnotation != null) { return ruleAnnotation } val sonarRule = getAnnotation(annotatedClassOrObject, SonarRule::class.java) if (sonarRule != null) { val priority = when(sonarRule.priority) { SonarPriority.BLOCKER -> Priority.BLOCKER SonarPriority.CRITICAL -> Priority.CRITICAL SonarPriority.MAJOR -> Priority.MAJOR SonarPriority.MINOR -> Priority.MINOR SonarPriority.INFO -> Priority.INFO } return RuleData( sonarRule.key, sonarRule.name, sonarRule.description, priority, sonarRule.tags, sonarRule.status) } return null } override fun getRulePropertyAnnotation(field: Field): RulePropertyData? { val rulePropertyAnnotation = super.getRulePropertyAnnotation(field) if (rulePropertyAnnotation != null) { return rulePropertyAnnotation } val sonarRuleProperty = field.getAnnotation(SonarRuleProperty::class.java) if (sonarRuleProperty != null) { return RulePropertyData( sonarRuleProperty.key, sonarRuleProperty.description, sonarRuleProperty.defaultValue, sonarRuleProperty.type) } return null } }
lgpl-3.0
c7ad54329c4888c7dbdaf237efaae403
35.766234
84
0.671494
4.806452
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/widget/AvatarStatsWidgetProvider.kt
1
8601
package com.habitrpg.android.habitica.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.content.Intent import android.view.View import android.view.ViewGroup import android.widget.RemoteViews import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.withImmutableFlag import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.common.habitica.extensions.dpToPx import com.habitrpg.common.habitica.helpers.HealthFormatter import com.habitrpg.common.habitica.helpers.NumberAbbreviator import com.habitrpg.common.habitica.views.AvatarView class AvatarStatsWidgetProvider : BaseWidgetProvider() { private lateinit var avatarView: AvatarView private var user: User? = null private var appWidgetManager: AppWidgetManager? = null private var showManaBar = mutableMapOf<Int, Boolean>() private var showAvatar = mutableMapOf<Int, Boolean>() override fun layoutResourceId(): Int { return R.layout.widget_avatar_stats } private fun setUp() { if (!hasInjected) { hasInjected = true HabiticaBaseApplication.userComponent?.inject(this) } } override fun onEnabled(context: Context) { super.onEnabled(context) avatarView = AvatarView( context.applicationContext, showBackground = true, showMount = true, showPet = true ) val layoutParams = ViewGroup.LayoutParams(140.dpToPx(context), 147.dpToPx(context)) avatarView.layoutParams = layoutParams this.setUp() userRepository.getUserFlowable().subscribe({ user = it updateData() }, ExceptionHandler.rx()) } override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { super.onUpdate(context, appWidgetManager, appWidgetIds) if (!this::avatarView.isInitialized) { avatarView = AvatarView( context.applicationContext, showBackground = true, showMount = true, showPet = true ) val layoutParams = ViewGroup.LayoutParams(140.dpToPx(context), 147.dpToPx(context)) avatarView.layoutParams = layoutParams } this.setUp() this.appWidgetManager = appWidgetManager this.context = context if (user == null) { userRepository.getUserFlowable().firstElement().subscribe({ user = it updateData(appWidgetIds) }, ExceptionHandler.rx()) } else { updateData() } } override fun configureRemoteViews( remoteViews: RemoteViews, widgetId: Int, columns: Int, rows: Int ): RemoteViews { showAvatar[widgetId] = columns > 3 if (showAvatar[widgetId] == true) { remoteViews.setViewVisibility(R.id.avatar_view, View.VISIBLE) } else { remoteViews.setViewVisibility(R.id.avatar_view, View.GONE) } showManaBar[widgetId] = rows > 1 if (rows > 1) { remoteViews.setViewVisibility(R.id.detail_info_view, View.VISIBLE) } else { remoteViews.setViewVisibility(R.id.detail_info_view, View.GONE) } return remoteViews } private fun updateData(widgetIds: IntArray? = null) { val context = context val appWidgetManager = appWidgetManager val user = user val stats = user?.stats if (user == null || stats == null || context == null || appWidgetManager == null) { return } val thisWidget = ComponentName(context, AvatarStatsWidgetProvider::class.java) val allWidgetIds = widgetIds ?: appWidgetManager.getAppWidgetIds(thisWidget) val currentHealth = HealthFormatter.format(stats.hp ?: 0.0) val currentHealthString = HealthFormatter.formatToString(stats.hp ?: 0.0) val healthValueString = currentHealthString + "/" + stats.maxHealth val expValueString = "" + stats.exp?.toInt() + "/" + stats.toNextLevel val mpValueString = "" + stats.mp?.toInt() + "/" + stats.maxMP for (widgetId in allWidgetIds) { val options = appWidgetManager.getAppWidgetOptions(widgetId) val remoteViews = sizeRemoteViews(context, options, widgetId) remoteViews.setTextViewText(R.id.TV_hp_value, healthValueString) remoteViews.setTextViewText(R.id.exp_TV_value, expValueString) remoteViews.setTextViewText(R.id.mp_TV_value, mpValueString) remoteViews.setImageViewBitmap( R.id.ic_hp_header, HabiticaIconsHelper.imageOfHeartLightBg() ) remoteViews.setImageViewBitmap( R.id.ic_exp_header, HabiticaIconsHelper.imageOfExperience() ) remoteViews.setImageViewBitmap(R.id.ic_mp_header, HabiticaIconsHelper.imageOfMagic()) remoteViews.setProgressBar( R.id.hp_bar, stats.maxHealth ?: 0, currentHealth.toInt(), false ) remoteViews.setProgressBar( R.id.exp_bar, stats.toNextLevel ?: 0, stats.exp?.toInt() ?: 0, false ) remoteViews.setProgressBar(R.id.mp_bar, stats.maxMP ?: 0, stats.mp?.toInt() ?: 0, false) remoteViews.setViewVisibility( R.id.mp_wrapper, if (showManaBar[widgetId] != true || stats.habitClass == null || (stats.lvl ?: 0) < 10 || user.preferences?.disableClasses == true ) View.GONE else View.VISIBLE ) remoteViews.setTextViewText( R.id.gold_tv, NumberAbbreviator.abbreviate(context, stats.gp ?: 0.0) ) remoteViews.setTextViewText(R.id.gems_tv, (user.balance * 4).toInt().toString()) val hourGlassCount = user.hourglassCount if (hourGlassCount == 0) { remoteViews.setViewVisibility(R.id.hourglass_icon, View.GONE) remoteViews.setViewVisibility(R.id.hourglasses_tv, View.GONE) } else { remoteViews.setImageViewBitmap( R.id.hourglass_icon, HabiticaIconsHelper.imageOfHourglass() ) remoteViews.setViewVisibility(R.id.hourglass_icon, View.VISIBLE) remoteViews.setTextViewText(R.id.hourglasses_tv, hourGlassCount.toString()) remoteViews.setViewVisibility(R.id.hourglasses_tv, View.VISIBLE) } remoteViews.setImageViewBitmap(R.id.gem_icon, HabiticaIconsHelper.imageOfGem()) remoteViews.setImageViewBitmap(R.id.gold_icon, HabiticaIconsHelper.imageOfGold()) remoteViews.setTextViewText( R.id.lvl_tv, context.getString(R.string.user_level, user.stats?.lvl ?: 0) ) if (showAvatar[widgetId] == true) { val finalRemoteViews = remoteViews avatarView.setAvatar(user) avatarView.onAvatarImageReady { bitmap -> finalRemoteViews.setImageViewBitmap(R.id.avatar_view, bitmap) appWidgetManager.partiallyUpdateAppWidget(widgetId, finalRemoteViews) } } val openAppIntent = Intent(context.applicationContext, MainActivity::class.java) val openApp = PendingIntent.getActivity( context, 0, openAppIntent, withImmutableFlag(PendingIntent.FLAG_UPDATE_CURRENT) ) remoteViews.setOnClickPendingIntent(android.R.id.background, openApp) appWidgetManager.updateAppWidget(widgetId, remoteViews) } } }
gpl-3.0
2091ec8dab07ff39bd9687117d904896
38.191589
100
0.603534
5.029825
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/options/AnimationsOptions.kt
1
2199
package com.reactnativenavigation.options import org.json.JSONObject class AnimationsOptions { @JvmField var push = StackAnimationOptions() @JvmField var pop = StackAnimationOptions() @JvmField var setStackRoot = StackAnimationOptions() @JvmField var setRoot = TransitionAnimationOptions() @JvmField var showModal = TransitionAnimationOptions() @JvmField var dismissModal = TransitionAnimationOptions() fun mergeWith(other: AnimationsOptions) { push.mergeWith(other.push) pop.mergeWith(other.pop) setRoot.mergeWith(other.setRoot) setStackRoot.mergeWith(other.setStackRoot) showModal.mergeWith(other.showModal) dismissModal.mergeWith(other.dismissModal) } fun mergeWithDefault(defaultOptions: AnimationsOptions) { push.mergeWithDefault(defaultOptions.push) pop.mergeWithDefault(defaultOptions.pop) setStackRoot.mergeWithDefault(defaultOptions.setStackRoot) setRoot.mergeWithDefault(defaultOptions.setRoot) showModal.mergeWithDefault(defaultOptions.showModal) dismissModal.mergeWithDefault(defaultOptions.dismissModal) } companion object { @JvmStatic fun parse(json: JSONObject?): AnimationsOptions { val options = AnimationsOptions() if (json == null) return options options.push = StackAnimationOptions(json.optJSONObject("push")) options.pop = StackAnimationOptions(json.optJSONObject("pop")) options.setStackRoot = StackAnimationOptions(json.optJSONObject("setStackRoot")) val rootAnimJson = json.optJSONObject("setRoot") rootAnimJson?.let { options.setRoot = parseTransitionAnimationOptions(it) } val showModalJson = json.optJSONObject("showModal") showModalJson?.let { options.showModal = parseTransitionAnimationOptions(it) } val dismissModalJson = json.optJSONObject("dismissModal") dismissModalJson?.let { options.dismissModal = parseTransitionAnimationOptions(it) } return options } } }
mit
b9ad3715742f8fa973559800f622c2f7
37.578947
92
0.681673
5.324455
false
false
false
false
TinoGuo/AnimatedWebp2
src/main/java/cn/tino/animatedwebp/MainScreen.kt
1
12918
package cn.tino.animatedwebp import javafx.beans.binding.BooleanBinding import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.scene.control.* import javafx.scene.layout.GridPane import javafx.stage.FileChooser import main.java.cn.tino.animatedwebp.Styles.Companion.mainScreen import main.java.cn.tino.animatedwebp.WebpParameter import sun.misc.Launcher import tornadofx.* import java.io.ByteArrayOutputStream import java.io.File import java.io.InputStream import java.nio.charset.Charset /** * mailTo:[email protected] * Created by tino on 2017 June 17, 18:08. */ class MainScreen : View() { companion object { val singleFileCmd = " -frame %s +%d+0+0+0-b" val encodeWebpCmd = "%s/cwebp -q %d %s -o %s" val webpMuxCmd = "%s/webpmux %s -loop %d -bgcolor 0,0,0,0 -o %s.webp" val singleWebpCmd = "%s/cwebp -q %d %s -o %s" val ERROR = "Error" } override val root = GridPane() val parameter = WebpParameter() var projectDir: File by singleAssign() var quality: TextField by singleAssign() var speed: TextField by singleAssign() var loop: CheckBox by singleAssign() var loopTimes: TextField by singleAssign() var chooseFile: Button by singleAssign() var chooseDir: Button by singleAssign() var execute: Button by singleAssign() var fileFilter: Spinner<String> by singleAssign() init { title = "Animated Webp Tools" with(root) { maxWidth = 1200.px.value addClass(mainScreen) row("webp quality(0~100)") { quality = textfield { text = "75" bind(parameter.qualityProperty()) } } row("webp speed(frames/s)") { speed = textfield { text = "30" bind(parameter.speedProperty()) } } row("infinity loop") { loop = checkbox { bind(parameter.loopInfinityProperty()) } label("loop times") loopTimes = textfield { disableProperty().bind(parameter.loopInfinityProperty().isEqualTo(true)) bind(parameter.loopTimesProperty()) } } row { chooseFile = button("choose single file") { setOnAction { parameter.fileSelected = tornadofx.chooseFile(null, arrayOf(FileChooser.ExtensionFilter("image", "*.jpg", "*.png", "*.gif")), FileChooserMode.Single, primaryStage, null).let { if (it.isEmpty()) { return@let null } return@let it.first() } } } chooseDir = button("choose dir") { setOnAction { parameter.fileSelected = chooseDirectory(null, null, primaryStage, null) } } label("File filter") fileFilter = spinner(FXCollections.observableArrayList(".png", ".jpg", ".gif"), false, parameter.fileFilterProperty()) { disableProperty().bind(parameter.fileSelectedProperty().let { return@let object : BooleanBinding() { init { super.bind(it) } override fun getDependencies(): ObservableList<*> { return FXCollections.singletonObservableList(it) } override fun dispose() { super.unbind(it) } override fun computeValue(): Boolean { if (it.get() == null) { return true } return it.get().isFile } } }) } } row("") { execute = button("execute") { setOnAction { when (parameter.fileSelected.isDirectory) { true -> processMultiFiles() false -> processSingle() } } disableProperty().bind(parameter.qualityProperty().isNull.or(parameter.speedProperty().isNull) .or(parameter.fileSelectedProperty().isNull)) } } } quality.text = "75" speed.text = "30" loop.isSelected = true loopTimes.text = "1" val file = File(javaClass.protectionDomain.codeSource.location.path) if (file.isFile) { var preProcess = false file.parentFile.listFiles().forEach { it -> if (it.name.contains("webpLib")) { preProcess = it.list().findAllLib() return@forEach } } if (!preProcess) { alert(Alert.AlertType.ERROR, ERROR, "webpLib directory lose!", ButtonType.OK, actionFn = { buttonType -> if (buttonType.buttonData == ButtonBar.ButtonData.OK_DONE) { System.exit(0) } }) } else { projectDir = file.parentFile.listFiles{pathname -> pathname.endsWith("webpLib")}.first() } } else { val url = Launcher::class.java.getResource("/") if (url != null) { projectDir = File(File(url.toURI()).parentFile.parentFile.absolutePath + "/webpLib") } else { alert(Alert.AlertType.ERROR, ERROR, "webpLib directory lose!", ButtonType.OK, actionFn = { buttonType -> if (buttonType.buttonData == ButtonBar.ButtonData.OK_DONE) { System.exit(0) } }) } } } fun Array<String>.findAllLib(): Boolean { val count = mutableMapOf<String, Int>() forEach { it -> count.put(it, 1) } return count.size == 3 } fun String?.isDigitsOnly(): Boolean { val len = this?.length ?: 0 var cp: Int var i = 0 while (i < len) { cp = Character.codePointAt(this, i) if (!Character.isDigit(cp)) { return false } i += Character.charCount(cp) } return true } fun InputStream.convertString(): String { val outStream = ByteArrayOutputStream(1024) val data: ByteArray = ByteArray(1024) var count = this.read(data, 0, 1024) while (count != -1) { outStream.write(data, 0, 1024) count = this.read(data, 0, 1024) } return String(outStream.toByteArray(), Charset.defaultCharset()) } fun Runtime.openFileBrowser(path: String) { val os = System.getProperty("os.name").toLowerCase() if (os.startsWith("win")) { this.exec("explorer.exe /select,$path") } else { this.exec("open $path") } } fun preProcessParameter(): Boolean { if (parameter.quality.isEmpty() || parameter.speed.isEmpty() || (!parameter.loopInfinity && parameter.loopTimes.isEmpty())) { alert(Alert.AlertType.ERROR, ERROR, "content must not empty!", ButtonType.OK) return false } if (!parameter.quality.isDigitsOnly()) { alert(Alert.AlertType.ERROR, ERROR, "quality must be digits!", ButtonType.OK) return false } if (parameter.quality.toInt() !in 1..100) { alert(Alert.AlertType.ERROR, ERROR, "quality must in the range(0,100]!", ButtonType.OK) return false } if (!parameter.speed.isDigitsOnly()) { alert(Alert.AlertType.ERROR, "", "speed must be digits!", ButtonType.OK) return false } if (!parameter.loopInfinity && !parameter.loopTimes.isDigitsOnly()) { alert(Alert.AlertType.ERROR, "", "loop times must be digits!", ButtonType.OK) return false } if (parameter.loopTimes.toInt() <= 0) { alert(Alert.AlertType.ERROR, ERROR, "loop time must greater than 0!", ButtonType.OK) return false } return true } fun processSingle() { if (preProcessParameter()) { val runTime = Runtime.getRuntime() val tmpName = parameter.fileSelected.absolutePath.replaceAfter('.', "webp") runAsync { runTime.exec(String.format(singleWebpCmd, projectDir, parameter.quality.toInt(), parameter.fileSelected.absolutePath, tmpName)).apply { waitFor() } } ui { process -> when (process.exitValue()) { 0 -> alert(Alert.AlertType.INFORMATION, "", tmpName, ButtonType.OK) else -> runAsync { process.errorStream.convertString() } ui { str -> alert(Alert.AlertType.ERROR, ERROR, str, ButtonType.OK) } } } } } fun processMultiFiles() { if (!preProcessParameter()) { return } runAsync { val runTime = Runtime.getRuntime() var files = parameter.fileSelected.listFiles { pathname -> pathname!!.name.endsWith(parameter.fileFilter) } if (files.isEmpty()) { return@runAsync null } files.forEach { it -> val name = it.name.replace(parameter.fileFilter, "") runTime.exec(String.format(encodeWebpCmd, projectDir.absolutePath, parameter.quality.toInt(), it.absolutePath, it.parent + "/" + name + ".webp")) .waitFor() } val sb = StringBuilder() files = parameter.fileSelected.listFiles { pathname -> pathname!!.name.endsWith(".webp") } if (files.isEmpty()) { return@runAsync null } files.sort() for (file in files) { sb.append(String.format(singleFileCmd, file.absolutePath, 1000 / parameter.speed.toInt())) } val loopCount = if (parameter.loopInfinity) 0 else parameter.loopTimes.toInt() runTime.exec(String.format(webpMuxCmd, projectDir.absolutePath, sb.toString(), loopCount, parameter.fileSelected.parent + "/" + parameter.fileSelected.name)) .apply { this.waitFor() files.forEach { it.delete() } } } ui { process -> if (process == null) { alert(Alert.AlertType.ERROR, ERROR, "selected files is empty", ButtonType.OK) } when (process?.exitValue()) { 0 -> alert(Alert.AlertType.INFORMATION, "", "output file is: ${parameter.fileSelected.absolutePath}.webp\nOpen the directory now?", ButtonType.OK, ButtonType.CANCEL, actionFn = { btnType -> if (btnType.buttonData == ButtonBar.ButtonData.OK_DONE) { Runtime.getRuntime().openFileBrowser(parameter.fileSelected.parentFile.absolutePath) } }) else -> runAsync { process?.errorStream?.convertString() ?: "EXECUTE FAIL!" } ui { str -> alert(Alert.AlertType.ERROR, ERROR, str, ButtonType.OK) } } } } }
apache-2.0
dc31c062a55a175b3b5d304cba9143e0
35.803419
133
0.470816
5.320428
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowlib/texturedic/TextureDicIV.kt
1
4336
package nl.shadowlink.tools.shadowlib.texturedic import nl.shadowlink.tools.io.ByteReader import nl.shadowlink.tools.io.ReadFunctions import nl.shadowlink.tools.shadowlib.model.wdr.ResourceFile /** * @author Shadow-Link */ class TextureDicIV { private val textures = ArrayList<Texture>() private var sysSize = 0 fun loadTextureDic(wtd: TextureDic, compressed: Boolean, sysSize: Int) { this.sysSize = sysSize if (compressed) { val br: ByteReader? = if (wtd.br == null) { val rf = ReadFunctions(wtd.fileName) println("WTD Opened") rf.byteReader } else { wtd.br } val stream: ByteArray val res = ResourceFile() stream = res.read(br, wtd.fileSize) this.sysSize = res.systemSize val br2 = ByteReader(stream, 0) read(br2) } else { read(wtd.br) } wtd.textures = textures } fun read(br: ByteReader) { // TODO: Move GL stuff to Shadow-Mapper val VTable = br.readUInt32() val blockMapOffset = br.readOffset() val parentDictionary = br.readUInt32() val usageCount = br.readUInt32() // SimpleCollection val hashTableOffset = br.readOffset() val texCount = br.readUInt16() val texSize = br.readUInt16() if (texCount > 0) { var save = br.getCurrentOffset() br.setCurrentOffset(hashTableOffset) for (i in 0 until texCount) { // Message.displayMsgHigh("Hash: " + br.readUInt32()); } br.setCurrentOffset(save) // PointerCollection val textureListOffset = br.readOffset() val textureCount = br.readUInt16() val pTexSize = br.readUInt16() save = br.getCurrentOffset() br.setCurrentOffset(textureListOffset) for (i in 0 until textureCount) { val texOffset = br.readOffset() save = br.getCurrentOffset() br.setCurrentOffset(texOffset) val TexVTable = br.readUInt32() val unknown1 = br.readUInt32() val unknown2 = br.readUInt32() val unknown3 = br.readUInt32() val unknown4 = br.readUInt32() val texNameOffset = br.readOffset() val save2 = br.getCurrentOffset() br.setCurrentOffset(texNameOffset) val packName = br.readNullTerminatedString() // Message.displayMsgHigh("PackName: " + packName); val name = packName.replace("pack:/", "").replace(".dds", "") br.setCurrentOffset(save2) val unknown5 = br.readUInt32() val width = br.readUInt16() val height = br.readUInt16() val compression = br.readString(4) val strideSize = br.readUInt16() val type = br.readByte() val levels = br.readByte() var unk1 = br.readFloat() var unk2 = br.readFloat() var unk3 = br.readFloat() unk1 = br.readFloat() unk2 = br.readFloat() unk3 = br.readFloat() val nextTexOffset = br.readOffset() val unknown6 = br.readUInt32() val dataOffset = br.readDataOffset() val unknown7 = br.readUInt32() // load the texture br.setCurrentOffset(dataOffset + sysSize) val dataSize = when (compression) { "DXT1" -> (width * height / 2) "DXT3" -> width * height "DXT5" -> width * height else -> throw IllegalStateException("Unknown compression type") } val texture = Texture( diffuseTexName = name, dxtCompressionType = compression, width = width, height = height, data = br.readBytes(dataSize), ) textures.add(texture) br.setCurrentOffset(save) } } } }
gpl-2.0
47306404d2f68cd027dd04959d84ccf0
34.842975
83
0.515683
4.637433
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt
1
2907
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement import java.nio.ByteBuffer import java.util.* // Always followed by one of: 0x13, 0x16, 0x17 class ProgramInsulinCommand internal constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, nonce: Int, insulinProgramElements: List<ShortInsulinProgramElement>, private val checksum: Short, private val byte9: Byte, private val byte10And11: Short, private val byte12And13: Short, private val deliveryType: DeliveryType ) : NonceEnabledCommand(CommandType.PROGRAM_INSULIN, uniqueId, sequenceNumber, multiCommandFlag, nonce) { private val insulinProgramElements: List<ShortInsulinProgramElement> = ArrayList(insulinProgramElements) fun getLength(): Short = (insulinProgramElements.size * 2 + 14).toShort() fun getBodyLength(): Byte = (insulinProgramElements.size * 2 + 12).toByte() enum class DeliveryType(private val value: Byte) { BASAL(0x00.toByte()), TEMP_BASAL(0x01.toByte()), BOLUS(0x02.toByte()); fun getValue(): Byte { return value } } override val encoded: ByteArray get() { val buffer = ByteBuffer.allocate(getLength().toInt()) .put(commandType.value) .put(getBodyLength()) .putInt(nonce) .put(deliveryType.getValue()) .putShort(checksum) .put(byte9) // BASAL: currentSlot // BOLUS: number of ShortInsulinProgramElements .putShort(byte10And11) // BASAL: remainingEighthSecondsInCurrentSlot // BOLUS: immediate pulses multiplied by delay between pulses in eighth seconds .putShort(byte12And13) // BASAL: remainingPulsesInCurrentSlot // BOLUS: immediate pulses for (element in insulinProgramElements) { buffer.put(element.encoded) } return buffer.array() } override fun toString(): String { return "ProgramInsulinCommand{" + "insulinProgramElements=" + insulinProgramElements + ", checksum=" + checksum + ", byte9=" + byte9 + ", byte10And11=" + byte10And11 + ", byte12And13=" + byte12And13 + ", deliveryType=" + deliveryType + ", nonce=" + nonce + ", commandType=" + commandType + ", uniqueId=" + uniqueId + ", sequenceNumber=" + sequenceNumber + ", multiCommandFlag=" + multiCommandFlag + '}' } }
agpl-3.0
392ace451846816fa5ed9a5f8a62ad9e
40.528571
164
0.652907
4.472308
false
false
false
false
ajalt/flexadapter
sample/src/main/kotlin/com/github/ajalt/flexadapter/sample/StableIdsActivity.kt
1
3618
package com.github.ajalt.flexadapter.sample import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.CardView import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.widget.Button import com.github.ajalt.flexadapter.CachingAdapterItem import com.github.ajalt.flexadapter.CachingViewHolder import com.github.ajalt.flexadapter.FlexAdapter import kotlinx.android.synthetic.main.activity_stable_ids.* private class ColorSquareItem(var color: Int = randomColor()) : CachingAdapterItem(R.layout.item_color_square_small) { override fun CachingViewHolder.bindItemView(position: Int) { view<CardView>(R.id.card).setCardBackgroundColor(color) } fun changeColor() { color = randomColor() } } private class CarouselItem(val carousel: FlexAdapter<ColorSquareItem> = FlexAdapter()) : CachingAdapterItem(R.layout.item_carousel) { init { carousel.setHasStableIds(true) carousel.items.add(ColorSquareItem()) } override fun CachingViewHolder.initializeItemView() { view<RecyclerView>(R.id.carousel_rv).layoutManager = GridLayoutManager(itemView.context, 2, GridLayoutManager.HORIZONTAL, false) } override fun CachingViewHolder.bindItemView(position: Int) { fun updateButtons() { view<Button>(R.id.carousel_clear).setVisible(carousel.items.size > 0) view<Button>(R.id.carousel_change).setVisible(carousel.items.size > 0) view<Button>(R.id.carousel_shuffle).setVisible(carousel.items.size > 1) } view<RecyclerView>(R.id.carousel_rv).adapter = carousel view<View>(R.id.carousel_add).setOnClickListener { carousel.items.add(0, ColorSquareItem()) updateButtons() } view<View>(R.id.carousel_clear).setOnClickListener { carousel.items.clear() updateButtons() } view<View>(R.id.carousel_change).setOnClickListener { changeColors() } view<View>(R.id.carousel_shuffle).setOnClickListener { carousel.items.shuffle() } updateButtons() } fun changeColors() { carousel.items.forEach { it.changeColor() } carousel.notifyDataSetChanged() } } private fun View.setVisible(visible: Boolean) { visibility = if (visible) View.VISIBLE else View.INVISIBLE } class StableIdsActivity : AppCompatActivity() { private val adapter = FlexAdapter<CarouselItem>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_stable_ids) adapter.setHasStableIds(true) recycler_view.adapter = adapter recycler_view.layoutManager = LinearLayoutManager(this) add.setOnClickListener { adapter.items.add(0, CarouselItem()) updateButtons() recycler_view.scrollToPosition(0) } clear.setOnClickListener { adapter.items.clear() updateButtons() } change.setOnClickListener { adapter.items.forEach { it.changeColors() } } shuffle.setOnClickListener { adapter.items.shuffle() } adapter.items.add(CarouselItem()) updateButtons() } private fun updateButtons() { clear.setVisible(adapter.items.size > 0) change.setVisible(adapter.items.size > 0) shuffle.setVisible(adapter.items.size > 1) } }
apache-2.0
bb2b1d186307459d26fd307c2ac94ca4
31.594595
118
0.683803
4.406821
false
false
false
false
just-4-fun/holomorph
src/main/kotlin/just4fun/holomorph/forms_experimental/json.kt
1
3409
package just4fun.holomorph.forms_experimental import com.fasterxml.jackson.core.JsonFactory as JFactory import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken.* import just4fun.holomorph.* import java.io.StringWriter object JsonFactory : ProduceFactory<String, String> { private val factory = JFactory() override fun invoke(input: String): EntryProvider<String> = JsonProvider(input, factory.createParser(input)) override fun invoke(): EntryConsumer<String> = JsonConsumer(factory.createGenerator(StringWriter())) } /* READER */ class JsonProvider(override val input: String, val parser: JsonParser) : EntryProvider<String> { override fun provideNextEntry(entryBuilder: EntryBuilder, provideName: Boolean): Entry { val token = parser.nextValue() ?: return entryBuilder.EndEntry() val name = parser.currentName return when { token >= VALUE_EMBEDDED_OBJECT -> when (token) { VALUE_STRING -> entryBuilder.Entry(name, parser.text) VALUE_NUMBER_INT -> entryBuilder.Entry(name, parser.valueAsLong) VALUE_NUMBER_FLOAT -> entryBuilder.Entry(name, parser.valueAsDouble) VALUE_NULL -> entryBuilder.NullEntry(name) VALUE_FALSE -> entryBuilder.Entry(name, parser.valueAsBoolean) VALUE_TRUE -> entryBuilder.Entry(name, parser.valueAsBoolean) else -> entryBuilder.Entry(name, parser.text) } token == START_ARRAY -> entryBuilder.StartEntry(name, false) token == START_OBJECT -> entryBuilder.StartEntry(name, true) else -> entryBuilder.EndEntry() } } } /* WRITER */ class JsonConsumer(private val generator: JsonGenerator) : EntryConsumer<String> { override fun output(): String { generator.close() return generator.outputTarget?.toString() ?: "{}" } override fun consumeEntries(name: String?, subEntries: EnclosedEntries, expectNames: Boolean) { if (name != null) generator.writeFieldName(name) if (expectNames) generator.writeStartObject() else generator.writeStartArray() subEntries.consume() if (expectNames) generator.writeEndObject() else generator.writeEndArray() } override fun consumeEntry(name: String?, value: String) { if (name != null) generator.writeFieldName(name) generator.writeString(value) } override fun consumeEntry(name: String?, value: Long) { if (name != null) generator.writeFieldName(name) generator.writeNumber(value) } override fun consumeEntry(name: String?, value: Int) { if (name != null) generator.writeFieldName(name) generator.writeNumber(value) } override fun consumeEntry(name: String?, value: Double) { if (name != null) generator.writeFieldName(name) generator.writeNumber(value) } override fun consumeEntry(name: String?, value: Float) { if (name != null) generator.writeFieldName(name) generator.writeNumber(value) } override fun consumeEntry(name: String?, value: Boolean) { if (name != null) generator.writeFieldName(name) generator.writeBoolean(value) } override fun consumeNullEntry(name: String?) { if (name != null) generator.writeFieldName(name) generator.writeNull() } // override fun consumeEntry(value: ByteArray, typeName: String?, ordinal: Int) { // if (typeName != null) generator.writeFieldName(typeName) // // todo ??? // generator.writeStartArray() // value.forEachIndexed { ix, b -> consumeEntry(b, null, ix)} // generator.writeEndArray() // } }
apache-2.0
97b4782b0c7144d0d56608d2f0d58889
32.752475
109
0.742446
3.746154
false
false
false
false
livefront/bridge
bridgesample/src/main/java/com/livefront/bridgesample/scenario/fragment/StatePagerFragment.kt
1
3717
package com.livefront.bridgesample.scenario.fragment import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentStatePagerAdapter import androidx.viewpager.widget.ViewPager import com.livefront.bridge.Bridge import com.livefront.bridgesample.R import com.livefront.bridgesample.base.BridgeBaseFragment import com.livefront.bridgesample.scenario.activity.FragmentData import kotlinx.android.parcel.Parcelize import kotlinx.android.synthetic.main.fragment_pager.viewPager /** * A [Fragment] with a [ViewPager] that uses a [FragmentStatePagerAdapter]. This illustrates how * we currently must omit the call to [Bridge.clear] in [Fragment.onDestroy] of the child * Fragments. Failure to do so will lose data as you page between screens. */ class StatePagerFragment : BridgeBaseFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.fragment_pager, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewPager.adapter = object : FragmentStatePagerAdapter( childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT ) { override fun getItem( position: Int ): Fragment = when (getArguments(this@StatePagerFragment).mode) { Mode.BRIDGE -> LargeDataFragment.newInstance( // Note here that we specifically specify that the data should not be // cleared in onDestroy because a FragmentStatePagerAdapter will destroy // Fragments while still manually holding their Bundles for reuse later. // A future feature may allow clearing to be "deferred" when some parent // is being cleared. LargeDataArguments(shouldClearOnDestroy = false) ) Mode.NON_BRIDGE -> NonBridgeLargeDataFragment.newInstance() } override fun getCount(): Int = NUMBER_OF_PAGES override fun getPageTitle(position: Int): CharSequence? = position.toString() } } companion object { private const val ARGUMENTS_KEY = "arguments" private const val NUMBER_OF_PAGES = 10 fun getArguments( fragment: StatePagerFragment ): StatePagerArguments = fragment .requireArguments() .getParcelable(ARGUMENTS_KEY)!! fun getFragmentData(arguments: StatePagerArguments) = FragmentData( when (arguments.mode) { Mode.BRIDGE -> R.string.state_pager_screen_title Mode.NON_BRIDGE -> R.string.non_bridge_state_pager_screen_title }, StatePagerFragment::class.java, getInitialArguments(arguments) ) fun getInitialArguments(arguments: StatePagerArguments) = Bundle().apply { putParcelable(ARGUMENTS_KEY, arguments) } fun newInstance(arguments: StatePagerArguments) = StatePagerFragment().apply { this.arguments = getInitialArguments(arguments) } } /** * Specifies whether or not Bridge will be used for the child Fragments. */ enum class Mode { BRIDGE, NON_BRIDGE } } @Parcelize data class StatePagerArguments( val mode: StatePagerFragment.Mode ) : Parcelable
apache-2.0
87d7fe1d625accad509fac57e2cdb20b
37.71875
96
0.659941
5.213184
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/ReferenceVariantsCollector.kt
5
13330
// 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.completion import com.intellij.codeInsight.completion.PrefixMatcher import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper import org.jetbrains.kotlin.idea.core.util.externalDescriptors import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver import org.jetbrains.kotlin.idea.util.ShadowedDeclarationsFilter import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCodeFragment import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.SimpleClassicTypeSystemContext.isTypeVariableType import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeSmartForCompiler data class ReferenceVariants(val imported: Collection<DeclarationDescriptor>, val notImportedExtensions: Collection<CallableDescriptor>) private operator fun ReferenceVariants.plus(other: ReferenceVariants): ReferenceVariants { return ReferenceVariants(imported.union(other.imported), notImportedExtensions.union(other.notImportedExtensions)) } class ReferenceVariantsCollector( private val referenceVariantsHelper: ReferenceVariantsHelper, private val indicesHelper: KotlinIndicesHelper, private val prefixMatcher: PrefixMatcher, private val nameExpression: KtSimpleNameExpression, private val callTypeAndReceiver: CallTypeAndReceiver<*, *>, private val resolutionFacade: ResolutionFacade, private val bindingContext: BindingContext, private val importableFqNameClassifier: ImportableFqNameClassifier, private val configuration: CompletionSessionConfiguration, private val allowExpectedDeclarations: Boolean, private val runtimeReceiver: ExpressionReceiver? = null, ) { companion object { private fun KotlinType.contains(isThatType: KotlinType.() -> Boolean): Boolean { if (isThatType()) return true if (arguments.isEmpty() || arguments.firstOrNull()?.isStarProjection == true) return false for (arg in arguments) { if (arg.type.contains { isThatType() }) return true } return false } private fun DeclarationDescriptor.hasSubstitutionFailure(): Boolean { val callable = this as? CallableDescriptor ?: return false return callable.valueParameters.any { it.type.contains { isNothing() } && !it.original.type.contains { isNothing() } || it.type.contains { isTypeVariableType() } || it.type.contains { isError } } } @Suppress("UNCHECKED_CAST") private fun <T: DeclarationDescriptor> T.fixSubstitutionFailureIfAny(): T = if (hasSubstitutionFailure()) original as T else this private fun ReferenceVariants.fixDescriptors(): ReferenceVariants { val importedFixed = imported.map { it.fixSubstitutionFailureIfAny() } val notImportedFixed = notImportedExtensions.map { it.fixSubstitutionFailureIfAny() } return ReferenceVariants(importedFixed, notImportedFixed) } } private data class FilterConfiguration internal constructor( val descriptorKindFilter: DescriptorKindFilter, val additionalPropertyNameFilter: ((String) -> Boolean)?, val shadowedDeclarationsFilter: ShadowedDeclarationsFilter?, val completeExtensionsFromIndices: Boolean ) private val prefix = prefixMatcher.prefix private val descriptorNameFilter = prefixMatcher.asStringNameFilter() private val collectedImported = LinkedHashSet<DeclarationDescriptor>() private val collectedNotImportedExtensions = LinkedHashSet<CallableDescriptor>() private var isCollectingFinished = false val allCollected: ReferenceVariants get() { assert(isCollectingFinished) return ReferenceVariants(collectedImported, collectedNotImportedExtensions) } fun collectingFinished() { assert(!isCollectingFinished) isCollectingFinished = true } fun collectReferenceVariants(descriptorKindFilter: DescriptorKindFilter): ReferenceVariants { assert(!isCollectingFinished) val config = configuration(descriptorKindFilter) val basic = collectBasicVariants(config) return basic + collectExtensionVariants(config, basic) } fun collectReferenceVariants(descriptorKindFilter: DescriptorKindFilter, consumer: (ReferenceVariants) -> Unit) { assert(!isCollectingFinished) val config = configuration(descriptorKindFilter) val basic = collectBasicVariants(config).fixDescriptors() consumer(basic) val extensions = collectExtensionVariants(config, basic).fixDescriptors() consumer(extensions) } private fun collectBasicVariants(filterConfiguration: FilterConfiguration): ReferenceVariants { val variants = doCollectBasicVariants(filterConfiguration) collectedImported += variants.imported return variants } private fun collectExtensionVariants(filterConfiguration: FilterConfiguration, basicVariants: ReferenceVariants): ReferenceVariants { val variants = doCollectExtensionVariants(filterConfiguration, basicVariants) collectedImported += variants.imported collectedNotImportedExtensions += variants.notImportedExtensions return variants } private fun configuration(descriptorKindFilter: DescriptorKindFilter): FilterConfiguration { val completeExtensionsFromIndices = descriptorKindFilter.kindMask.and(DescriptorKindFilter.CALLABLES_MASK) != 0 && DescriptorKindExclude.Extensions !in descriptorKindFilter.excludes && callTypeAndReceiver !is CallTypeAndReceiver.IMPORT_DIRECTIVE @Suppress("NAME_SHADOWING") val descriptorKindFilter = if (completeExtensionsFromIndices) descriptorKindFilter exclude TopLevelExtensionsExclude // handled via indices else descriptorKindFilter val getOrSetPrefix = GET_SET_PREFIXES.firstOrNull { prefix.startsWith(it) } val additionalPropertyNameFilter: ((String) -> Boolean)? = getOrSetPrefix?.let { prefixMatcher.cloneWithPrefix(prefix.removePrefix(getOrSetPrefix).decapitalizeSmartForCompiler()).asStringNameFilter() } val shadowedDeclarationsFilter = if (runtimeReceiver != null) ShadowedDeclarationsFilter(bindingContext, resolutionFacade, nameExpression, runtimeReceiver) else ShadowedDeclarationsFilter.create(bindingContext, resolutionFacade, nameExpression, callTypeAndReceiver) return FilterConfiguration( descriptorKindFilter, additionalPropertyNameFilter, shadowedDeclarationsFilter, completeExtensionsFromIndices ) } private fun doCollectBasicVariants(filterConfiguration: FilterConfiguration): ReferenceVariants { fun getReferenceVariants(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> { return referenceVariantsHelper.getReferenceVariants( nameExpression, kindFilter, nameFilter, filterOutJavaGettersAndSetters = false, filterOutShadowed = false, excludeNonInitializedVariable = false, useReceiverType = runtimeReceiver?.type ) } val basicNameFilter = descriptorNameFilter.toNameFilter() val (descriptorKindFilter, additionalPropertyNameFilter) = filterConfiguration var runDistinct = false var basicVariants = getReferenceVariants(descriptorKindFilter, basicNameFilter) if (additionalPropertyNameFilter != null) { basicVariants += getReferenceVariants( descriptorKindFilter.intersect(DescriptorKindFilter.VARIABLES), additionalPropertyNameFilter.toNameFilter() ) runDistinct = true } val containingCodeFragment = nameExpression.containingKtFile as? KtCodeFragment if (containingCodeFragment != null) { val externalDescriptors = containingCodeFragment.externalDescriptors if (externalDescriptors != null) { basicVariants += externalDescriptors .filter { descriptorKindFilter.accepts(it) && basicNameFilter(it.name) } } } if (runDistinct) { basicVariants = basicVariants.distinct() } return ReferenceVariants(filterConfiguration.filterVariants(basicVariants).toHashSet(), emptyList()) } private fun doCollectExtensionVariants(filterConfiguration: FilterConfiguration, basicVariants: ReferenceVariants): ReferenceVariants { val (_, additionalPropertyNameFilter, shadowedDeclarationsFilter, completeExtensionsFromIndices) = filterConfiguration if (completeExtensionsFromIndices) { val nameFilter = if (additionalPropertyNameFilter != null) descriptorNameFilter or additionalPropertyNameFilter else descriptorNameFilter val extensions = if (runtimeReceiver != null) indicesHelper.getCallableTopLevelExtensions(callTypeAndReceiver, listOf(runtimeReceiver.type), nameFilter) else indicesHelper.getCallableTopLevelExtensions( callTypeAndReceiver, nameExpression, bindingContext, receiverTypeFromDiagnostic = null, nameFilter ) val (extensionsVariants, notImportedExtensions) = extensions.partition { importableFqNameClassifier.isImportableDescriptorImported( it ) } val notImportedDeclarationsFilter = shadowedDeclarationsFilter?.createNonImportedDeclarationsFilter<CallableDescriptor>( importedDeclarations = basicVariants.imported + extensionsVariants, allowExpectedDeclarations = allowExpectedDeclarations, ) val filteredImported = filterConfiguration.filterVariants(extensionsVariants + basicVariants.imported) val importedExtensionsVariants = filteredImported.filter { it !in basicVariants.imported } return ReferenceVariants( importedExtensionsVariants, notImportedExtensions.let { variants -> notImportedDeclarationsFilter?.invoke(variants) ?: variants } ) } return ReferenceVariants(emptyList(), emptyList()) } private fun <TDescriptor : DeclarationDescriptor> FilterConfiguration.filterVariants(_variants: Collection<TDescriptor>): Collection<TDescriptor> { var variants = _variants if (shadowedDeclarationsFilter != null) variants = shadowedDeclarationsFilter.filter(variants) if (!configuration.javaGettersAndSetters) variants = referenceVariantsHelper.filterOutJavaGettersAndSetters(variants) if (!configuration.dataClassComponentFunctions) variants = variants.filter { !isDataClassComponentFunction(it) } return variants } private val GET_SET_PREFIXES = listOf("get", "set", "ge", "se", "g", "s") private object TopLevelExtensionsExclude : DescriptorKindExclude() { override fun excludes(descriptor: DeclarationDescriptor): Boolean { if (descriptor !is CallableMemberDescriptor) return false if (descriptor.extensionReceiverParameter == null) return false if (descriptor.kind != CallableMemberDescriptor.Kind.DECLARATION) return false /* do not filter out synthetic extensions */ if (descriptor.isArtificialImportAliasedDescriptor) return false // do not exclude aliased descriptors - they cannot be completed via indices val containingPackage = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false // TODO: temporary solution for Android synthetic extensions if (containingPackage.fqName.asString().startsWith("kotlinx.android.synthetic.")) return false return true } override val fullyExcludedDescriptorKinds: Int get() = 0 } private fun isDataClassComponentFunction(descriptor: DeclarationDescriptor): Boolean = descriptor is FunctionDescriptor && descriptor.isOperator && DataClassDescriptorResolver.isComponentLike(descriptor.name) && descriptor.kind == CallableMemberDescriptor.Kind .SYNTHESIZED }
apache-2.0
43440eee13f256fced30b7852bec525a
46.607143
181
0.72198
6.092322
false
true
false
false
k9mail/k-9
app/autodiscovery/srvrecords/src/main/java/com/fsck/k9/autodiscovery/srvrecords/SrvServiceDiscovery.kt
2
2073
package com.fsck.k9.autodiscovery.srvrecords import com.fsck.k9.autodiscovery.api.ConnectionSettingsDiscovery import com.fsck.k9.autodiscovery.api.DiscoveredServerSettings import com.fsck.k9.autodiscovery.api.DiscoveryResults import com.fsck.k9.autodiscovery.api.DiscoveryTarget import com.fsck.k9.helper.EmailHelper import com.fsck.k9.mail.AuthType import com.fsck.k9.mail.ConnectionSecurity class SrvServiceDiscovery( private val srvResolver: MiniDnsSrvResolver ) : ConnectionSettingsDiscovery { override fun discover(email: String, target: DiscoveryTarget): DiscoveryResults? { val domain = EmailHelper.getDomainFromEmailAddress(email) ?: return null val mailServicePriority = compareBy<MailService> { it.priority }.thenByDescending { it.security } val outgoingSettings = if (target.outgoing) listOf(SrvType.SUBMISSIONS, SrvType.SUBMISSION).flatMap { srvResolver.lookup(domain, it) } .sortedWith(mailServicePriority).map { newServerSettings(it, email) } else listOf() val incomingSettings = if (target.incoming) listOf(SrvType.IMAPS, SrvType.IMAP).flatMap { srvResolver.lookup(domain, it) } .sortedWith(mailServicePriority).map { newServerSettings(it, email) } else listOf() return DiscoveryResults(incoming = incomingSettings, outgoing = outgoingSettings) } } fun newServerSettings(service: MailService, email: String): DiscoveredServerSettings { return DiscoveredServerSettings( service.srvType.protocol, service.host, service.port, service.security, AuthType.PLAIN, email ) } enum class SrvType(val label: String, val protocol: String, val assumeTls: Boolean) { SUBMISSIONS("_submissions", "smtp", true), SUBMISSION("_submission", "smtp", false), IMAPS("_imaps", "imap", true), IMAP("_imap", "imap", false) } data class MailService( val srvType: SrvType, val host: String, val port: Int, val priority: Int, val security: ConnectionSecurity )
apache-2.0
d365b9a97264bc1c4b30dbe528a66678
35.368421
105
0.716353
4.265432
false
false
false
false
Maccimo/intellij-community
plugins/evaluation-plugin/src/com/intellij/cce/evaluation/step/ActionsGenerationStep.kt
3
6883
package com.intellij.cce.evaluation.step import com.intellij.cce.actions.* import com.intellij.cce.core.* import com.intellij.cce.evaluation.EvaluationRootInfo import com.intellij.cce.processor.DefaultEvaluationRootProcessor import com.intellij.cce.processor.EvaluationRootByRangeProcessor import com.intellij.cce.util.ExceptionsUtil.stackTraceToString import com.intellij.cce.util.FilesHelper import com.intellij.cce.util.Progress import com.intellij.cce.util.Summary import com.intellij.cce.visitor.CodeFragmentBuilder import com.intellij.cce.workspace.Config import com.intellij.cce.workspace.EvaluationWorkspace import com.intellij.cce.workspace.info.FileErrorInfo import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile class ActionsGenerationStep( private val config: Config.ActionsGeneration, private val language: String, private val evaluationRootInfo: EvaluationRootInfo, project: Project, isHeadless: Boolean) : BackgroundEvaluationStep(project, isHeadless) { override val name: String = "Generating actions" override val description: String = "Generating actions by selected files" override fun runInBackground(workspace: EvaluationWorkspace, progress: Progress): EvaluationWorkspace { val filesForEvaluation = FilesHelper.getFilesOfLanguage(project, config.evaluationRoots, language) generateActions(workspace, language, filesForEvaluation, config.strategy, evaluationRootInfo, progress) return workspace } private fun generateActions(workspace: EvaluationWorkspace, languageName: String, files: Collection<VirtualFile>, strategy: CompletionStrategy, evaluationRootInfo: EvaluationRootInfo, indicator: Progress) { val actionsGenerator = ActionsGenerator(strategy, Language.resolve(languageName)) val codeFragmentBuilder = CodeFragmentBuilder.create(project, languageName) val errors = mutableListOf<FileErrorInfo>() var totalSessions = 0 val actionsSummarizer = ActionsSummarizer() for ((i, file) in files.sortedBy { it.name }.withIndex()) { if (indicator.isCanceled()) { LOG.info("Generating actions is canceled by user. Done: $i/${files.size}. With error: ${errors.size}") break } LOG.info("Start generating actions for file ${file.path}. Done: $i/${files.size}. With error: ${errors.size}") val filename = file.name val progress = (i + 1).toDouble() / files.size try { val rootVisitor = when { evaluationRootInfo.useDefault -> DefaultEvaluationRootProcessor() evaluationRootInfo.parentPsi != null -> EvaluationRootByRangeProcessor( evaluationRootInfo.parentPsi.textRange?.startOffset ?: evaluationRootInfo.parentPsi.textOffset, evaluationRootInfo.parentPsi.textRange?.endOffset ?: evaluationRootInfo.parentPsi.textOffset + evaluationRootInfo.parentPsi.textLength) else -> throw IllegalStateException("Parent psi and offset are null.") } val codeFragment = codeFragmentBuilder.build(file, rootVisitor) val fileActions = actionsGenerator.generate(codeFragment) actionsSummarizer.update(fileActions) workspace.actionsStorage.saveActions(fileActions) totalSessions += fileActions.sessionsCount indicator.setProgress(filename, "${totalSessions.toString().padStart(4)} sessions | $filename", progress) } catch (e: Throwable) { indicator.setProgress(filename, "error: ${e.message} | $filename", progress) try { workspace.errorsStorage.saveError( FileErrorInfo(FilesHelper.getRelativeToProjectPath(project, file.path), e.message ?: "No Message", stackTraceToString(e)) ) } catch (e2: Throwable) { LOG.error("Exception on saving error info for file ${file.path}.", e2) } LOG.error("Generating actions error for file ${file.path}.", e) } LOG.info("Generating actions for file ${file.path} completed. Done: $i/${files.size}. With error: ${errors.size}") } actionsSummarizer.save(workspace) } private class ActionsSummarizer { private val rootSummary: Summary = Summary.create() fun update(fileActions: FileActions) { rootSummary.apply { inc("files") group("actions") { for (action in fileActions.actions) { inc("total") inc(action.type.toString().toLowerCase()) } } group("sessions") { for (action in fileActions.actions.asSessionStarts()) { inc("total") val properties = action.nodeProperties group("common (frequent expected text by token type)") { countingGroup(properties.tokenType.name.toLowerCase(), 100) { inc(action.expectedText) } } val javaProperties = properties.java() if (javaProperties != null) { group("java (frequent tokens by kind)") { inc("total") inc(javaProperties.tokenType.toString().toLowerCase()) group(action.kind().toString().toLowerCase()) { inc("total") if (javaProperties.isStatic) inc("static") else inc("nonstatic") countingGroup("popular symbols", 3000) { inc("${javaProperties.containingClass}#${action.expectedText}") } } } } } } } } private fun List<Action>.asSessionStarts(): Iterable<CallCompletion> { val result = mutableListOf<CallCompletion>() var insideSession = false for (action in this) { if (!insideSession && action is CallCompletion) { result.add(action) insideSession = true } else if (action is FinishSession) { insideSession = false } } return result } fun save(workspace: EvaluationWorkspace) { workspace.saveAdditionalStats("actions", rootSummary.asSerializable()) } private enum class CompletionKind { PROJECT, JRE, THIRD_PARTY, UNKNOWN_LOCATION, UNKNOWN_PACKAGE } private fun CallCompletion.kind(): CompletionKind { if (nodeProperties.location == SymbolLocation.PROJECT) return CompletionKind.PROJECT if (nodeProperties.location == SymbolLocation.UNKNOWN) return CompletionKind.UNKNOWN_LOCATION val packageName = nodeProperties.java()?.packageName ?: return CompletionKind.UNKNOWN_PACKAGE return if (packageName.startsWith("java")) CompletionKind.JRE else CompletionKind.THIRD_PARTY } private fun TokenProperties.java(): JvmProperties? = PropertyAdapters.Jvm.adapt(this) } }
apache-2.0
59f504293bf68df6b9ded7f829e6a604
41.757764
123
0.66904
4.826788
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/renderer/decoration/HalfBlockDecorationRenderer.kt
1
3533
package org.hexworks.zircon.internal.component.renderer.decoration import org.hexworks.zircon.api.color.TileColor import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderContext import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer.RenderingMode import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.graphics.Symbols import org.hexworks.zircon.api.graphics.TileGraphics import org.hexworks.zircon.api.modifier.Crop import org.hexworks.zircon.api.shape.LineFactory class HalfBlockDecorationRenderer( private val renderingMode: RenderingMode ) : ComponentDecorationRenderer { override val offset = Position.offset1x1() override val occupiedSize = Size.create(2, 2) override fun render(tileGraphics: TileGraphics, context: ComponentDecorationRenderContext) { val size = tileGraphics.size val style = context.fetchStyleFor(renderingMode) val topLeft = Position.defaultPosition() val topRight = size.fetchTopRightPosition() val bottomLeft = size.fetchBottomLeftPosition() val bottomRight = size.fetchBottomRightPosition() val topTile = Tile.defaultTile() .withCharacter(Symbols.LOWER_HALF_BLOCK) .withBackgroundColor(TileColor.transparent()) .withForegroundColor(style.foregroundColor) .asCharacterTileOrNull()!! LineFactory.buildLine(topLeft, topRight).positions .drop(1) .dropLast(1).forEach { tileGraphics.draw(topTile, it) } LineFactory.buildLine(topLeft, bottomLeft).positions .drop(1) .dropLast(1).forEach { tileGraphics.draw(topTile.withCharacter(Symbols.RIGHT_HALF_BLOCK), it) } LineFactory.buildLine(topRight, bottomRight).positions .drop(1) .dropLast(1).forEach { tileGraphics.draw(topTile.withCharacter(Symbols.LEFT_HALF_BLOCK), it) } LineFactory.buildLine(bottomLeft, bottomRight).positions .drop(1) .dropLast(1).forEach { tileGraphics.draw(topTile.withCharacter(Symbols.UPPER_HALF_BLOCK), it) } val tileset = tileGraphics.tileset val cropRight = Crop( x = tileset.width.div(2), y = 0, width = tileset.width.div(2), height = tileset.height ) val cropLeft = Crop( x = 0, y = 0, width = tileset.width.div(2), height = tileset.height ) val topLeftTile = Tile.defaultTile() .withCharacter(Symbols.LOWER_HALF_BLOCK) .withModifiers(cropRight) .withBackgroundColor(TileColor.transparent()) .withForegroundColor(style.foregroundColor) .asCharacterTileOrNull()!! val topRightTile = topLeftTile .withModifiers(cropLeft) val bottomLeftTile = topLeftTile .withCharacter(Symbols.UPPER_HALF_BLOCK) val bottomRightTile = bottomLeftTile .withModifiers(cropLeft) tileGraphics.draw(topLeftTile, topLeft) tileGraphics.draw(topRightTile, topRight) tileGraphics.draw(bottomLeftTile, bottomLeft) tileGraphics.draw(bottomRightTile, bottomRight) } }
apache-2.0
718cb83bb04b0a44491352a587066483
36.189474
96
0.66544
4.716956
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/util/extensions/SiteModelExtensions.kt
1
1106
package org.wordpress.android.util.extensions import org.wordpress.android.fluxc.model.SiteModel val SiteModel.logInformation: String get() { val typeLog = "Type: ($stateLogInformation)" val usernameLog = if (isUsingWpComRestApi) "" else username val urlLog = "${if (isUsingWpComRestApi) "REST" else "Self-hosted"} URL: $url" val planLog = if (isUsingWpComRestApi) "Plan: $planShortName ($planId)" else "" val jetpackVersionLog = if (isJetpackInstalled) "Jetpack-version: $jetpackVersion" else "" return listOf(typeLog, usernameLog, urlLog, planLog, jetpackVersionLog) .filter { it != "" } .joinToString(separator = " ", prefix = "<", postfix = ">") } val SiteModel.stateLogInformation: String get() { val apiString = if (isUsingWpComRestApi) "REST" else "XML-RPC" return when { isWPCom -> "wpcom" isJetpackConnected -> "jetpack_connected - $apiString" isJetpackInstalled -> "self-hosted - jetpack_installed" else -> "self_hosted" } }
gpl-2.0
e5f10a2317e3ee48041f3c015e6659ae
41.538462
98
0.628391
4.173585
false
false
false
false
JoeSteven/HuaBan
app/src/main/java/com/joe/zatuji/module/gallery/GalleryPresenter.kt
1
2809
package com.joe.zatuji.module.gallery import android.os.Bundle import com.joe.zatuji.R import com.joe.zatuji.base.staggered.BasePicListPresenter import com.joe.zatuji.event.GalleryUpdateEvent import com.joe.zatuji.repo.FavoriteTagRepository import com.joe.zatuji.repo.RecommendRepository import com.joe.zatuji.repo.bean.FavoriteTag import com.joe.zatuji.repo.bean.Gallery import com.joe.zatuji.repo.bean.IDetailPicture import com.joey.cheetah.core.utils.ResGetter /** * Description: * author:Joey * date:2018/11/21 */ class GalleryPresenter(view: IGalleryView): BasePicListPresenter<IGalleryView>(view) { private val repo = FavoriteTagRepository() private val recommendRepo = RecommendRepository() lateinit var tag:FavoriteTag var recommend:IDetailPicture? = null override fun onLoadData(isLoadMore: Boolean) { val offset = if (isLoadMore) { var skip = mPage * mLimit.toInt() if (skip > dataItems.size) { skip = dataItems.size } skip } else { 0 } add(repo.getGallery(tag.objectId, mLimit.toInt(), offset).subscribe({ onLoadSuccess(it, isLoadMore) }, { onLoadError(it, isLoadMore) })) } override fun onSaveData(p0: Bundle?) { } override fun onRestoredData(p0: Bundle?) { } fun setFront(gallery: Gallery) { mView?.showLoading(ResGetter.string(R.string.in_set_front)) add(repo.setFront(tag.objectId, gallery.img_url).subscribe({ mView?.doneLoading() mView?.toast(ResGetter.string(R.string.set_success)) bus().post(GalleryUpdateEvent()) }, { onApiError(it) })) } fun deleteGallery(gallery: Gallery) { mView?.showLoading(ResGetter.string(R.string.in_remove_gallery)) add(repo.removeGallery(tag, gallery.objectId).subscribe({ mView?.doneLoading() mView?.toast(ResGetter.string(R.string.delete_success)) bus().post(GalleryUpdateEvent()) val pos = items.indexOf(gallery) items.remove(gallery) tag.number-- mView?.removeItem(pos, "${tag.tag}(${tag.number})") }, { onApiError(it) })) } fun recommend(input: String) { if(input.isEmpty()) { mView?.toast(ResGetter.string(R.string.no_recommed_reason)) return } if (recommend == null) return mView?.showLoading(ResGetter.string(R.string.in_recommend)) add(recommendRepo.createRecommend(recommend!!, input).subscribe({ mView?.toast(ResGetter.string(R.string.recommend_success)) mView?.doneLoading() },{ onApiError(it) })) } }
apache-2.0
65ad006f40aefbf0aec2968496fa0698
30.573034
86
0.621218
4.124816
false
false
false
false
DanielGrech/anko
dsl/testData/functional/21/ComplexListenerClassTest.kt
6
9926
class __GestureOverlayView_OnGestureListener : android.gesture.GestureOverlayView.OnGestureListener { private var _onGestureStarted: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null private var _onGesture: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null private var _onGestureEnded: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null private var _onGestureCancelled: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) = _onGestureStarted?.invoke(overlay, event) public fun onGestureStarted(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) { _onGestureStarted = listener } override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) = _onGesture?.invoke(overlay, event) public fun onGesture(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) { _onGesture = listener } override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) = _onGestureEnded?.invoke(overlay, event) public fun onGestureEnded(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) { _onGestureEnded = listener } override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) = _onGestureCancelled?.invoke(overlay, event) public fun onGestureCancelled(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) { _onGestureCancelled = listener } } class __GestureOverlayView_OnGesturingListener : android.gesture.GestureOverlayView.OnGesturingListener { private var _onGesturingStarted: ((android.gesture.GestureOverlayView?) -> Unit)? = null private var _onGesturingEnded: ((android.gesture.GestureOverlayView?) -> Unit)? = null override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) = _onGesturingStarted?.invoke(overlay) public fun onGesturingStarted(listener: (android.gesture.GestureOverlayView?) -> Unit) { _onGesturingStarted = listener } override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) = _onGesturingEnded?.invoke(overlay) public fun onGesturingEnded(listener: (android.gesture.GestureOverlayView?) -> Unit) { _onGesturingEnded = listener } } class __View_OnAttachStateChangeListener : android.view.View.OnAttachStateChangeListener { private var _onViewAttachedToWindow: ((android.view.View) -> Unit)? = null private var _onViewDetachedFromWindow: ((android.view.View) -> Unit)? = null override fun onViewAttachedToWindow(v: android.view.View) = _onViewAttachedToWindow?.invoke(v) public fun onViewAttachedToWindow(listener: (android.view.View) -> Unit) { _onViewAttachedToWindow = listener } override fun onViewDetachedFromWindow(v: android.view.View) = _onViewDetachedFromWindow?.invoke(v) public fun onViewDetachedFromWindow(listener: (android.view.View) -> Unit) { _onViewDetachedFromWindow = listener } } class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener { private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) = _onChildViewAdded?.invoke(parent, child) public fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) { _onChildViewAdded = listener } override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) = _onChildViewRemoved?.invoke(parent, child) public fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) { _onChildViewRemoved = listener } } class __AbsListView_OnScrollListener : android.widget.AbsListView.OnScrollListener { private var _onScrollStateChanged: ((android.widget.AbsListView?, Int) -> Unit)? = null private var _onScroll: ((android.widget.AbsListView, Int, Int, Int) -> Unit)? = null override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) = _onScrollStateChanged?.invoke(view, scrollState) public fun onScrollStateChanged(listener: (android.widget.AbsListView?, Int) -> Unit) { _onScrollStateChanged = listener } override fun onScroll(view: android.widget.AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) = _onScroll?.invoke(view, firstVisibleItem, visibleItemCount, totalItemCount) public fun onScroll(listener: (android.widget.AbsListView, Int, Int, Int) -> Unit) { _onScroll = listener } } class __AdapterView_OnItemSelectedListener : android.widget.AdapterView.OnItemSelectedListener { private var _onItemSelected: ((android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null private var _onNothingSelected: ((android.widget.AdapterView<*>?) -> Unit)? = null override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) = _onItemSelected?.invoke(p0, p1, p2, p3) public fun onItemSelected(listener: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) { _onItemSelected = listener } override fun onNothingSelected(p0: android.widget.AdapterView<*>?) = _onNothingSelected?.invoke(p0) public fun onNothingSelected(listener: (android.widget.AdapterView<*>?) -> Unit) { _onNothingSelected = listener } } class __SearchView_OnQueryTextListener : android.widget.SearchView.OnQueryTextListener { private var _onQueryTextSubmit: ((String?) -> Boolean)? = null private var _onQueryTextChange: ((String?) -> Boolean)? = null override fun onQueryTextSubmit(query: String?) = _onQueryTextSubmit?.invoke(query) ?: false public fun onQueryTextSubmit(listener: (String?) -> Boolean) { _onQueryTextSubmit = listener } override fun onQueryTextChange(newText: String?) = _onQueryTextChange?.invoke(newText) ?: false public fun onQueryTextChange(listener: (String?) -> Boolean) { _onQueryTextChange = listener } } class __SearchView_OnSuggestionListener : android.widget.SearchView.OnSuggestionListener { private var _onSuggestionSelect: ((Int) -> Boolean)? = null private var _onSuggestionClick: ((Int) -> Boolean)? = null override fun onSuggestionSelect(position: Int) = _onSuggestionSelect?.invoke(position) ?: false public fun onSuggestionSelect(listener: (Int) -> Boolean) { _onSuggestionSelect = listener } override fun onSuggestionClick(position: Int) = _onSuggestionClick?.invoke(position) ?: false public fun onSuggestionClick(listener: (Int) -> Boolean) { _onSuggestionClick = listener } } class __SeekBar_OnSeekBarChangeListener : android.widget.SeekBar.OnSeekBarChangeListener { private var _onProgressChanged: ((android.widget.SeekBar, Int, Boolean) -> Unit)? = null private var _onStartTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null private var _onStopTrackingTouch: ((android.widget.SeekBar) -> Unit)? = null override fun onProgressChanged(seekBar: android.widget.SeekBar, progress: Int, fromUser: Boolean) = _onProgressChanged?.invoke(seekBar, progress, fromUser) public fun onProgressChanged(listener: (android.widget.SeekBar, Int, Boolean) -> Unit) { _onProgressChanged = listener } override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) = _onStartTrackingTouch?.invoke(seekBar) public fun onStartTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) { _onStartTrackingTouch = listener } override fun onStopTrackingTouch(seekBar: android.widget.SeekBar) = _onStopTrackingTouch?.invoke(seekBar) public fun onStopTrackingTouch(listener: (android.widget.SeekBar) -> Unit) { _onStopTrackingTouch = listener } } class __SlidingDrawer_OnDrawerScrollListener : android.widget.SlidingDrawer.OnDrawerScrollListener { private var _onScrollStarted: (() -> Unit)? = null private var _onScrollEnded: (() -> Unit)? = null override fun onScrollStarted() = _onScrollStarted?.invoke() public fun onScrollStarted(listener: () -> Unit) { _onScrollStarted = listener } override fun onScrollEnded() = _onScrollEnded?.invoke() public fun onScrollEnded(listener: () -> Unit) { _onScrollEnded = listener } } class __TextWatcher : android.text.TextWatcher { private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null private var _onTextChanged: ((CharSequence, Int, Int, Int) -> Unit)? = null private var _afterTextChanged: ((android.text.Editable?) -> Unit)? = null override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = _beforeTextChanged?.invoke(s, start, count, after) public fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) { _beforeTextChanged = listener } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) = _onTextChanged?.invoke(s, start, before, count) public fun onTextChanged(listener: (CharSequence, Int, Int, Int) -> Unit) { _onTextChanged = listener } override fun afterTextChanged(s: android.text.Editable?) = _afterTextChanged?.invoke(s) public fun afterTextChanged(listener: (android.text.Editable?) -> Unit) { _afterTextChanged = listener } }
apache-2.0
08250ecedc44a0cd1f8f5de1fe65e9fe
43.12
204
0.723151
4.81144
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/quest/subquest/usecase/UndoCompletedSubQuestUseCase.kt
1
1139
package io.ipoli.android.quest.subquest.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.quest.Quest import io.ipoli.android.quest.data.persistence.QuestRepository /** * Created by Venelin Valkov <[email protected]> * on 03/31/2018. */ class UndoCompletedSubQuestUseCase(private val questRepository: QuestRepository) : UseCase<UndoCompletedSubQuestUseCase.Params, Quest> { override fun execute(parameters: Params): Quest { val subQuestIndex = parameters.subQuestIndex val quest = questRepository.findById(parameters.questId) requireNotNull(quest) val sqs = quest!!.subQuests.toMutableList() val editSubQuest = sqs[subQuestIndex] requireNotNull(editSubQuest.completedAtDate) requireNotNull(editSubQuest.completedAtTime) sqs[subQuestIndex] = editSubQuest.copy( completedAtDate = null, completedAtTime = null ) return questRepository.save( quest.copy( subQuests = sqs ) ) } data class Params(val subQuestIndex: Int, val questId: String) }
gpl-3.0
cb37ff506f5153cf43fd69ccca0bca70
27.5
82
0.687445
4.414729
false
false
false
false
JetBrains/teamcity-nuget-support
nuget-feed/src/jetbrains/buildServer/nuget/feed/server/json/JsonSearchQueryHandler.kt
1
1947
package jetbrains.buildServer.nuget.feed.server.json import jetbrains.buildServer.nuget.feed.server.NuGetFeedConstants import jetbrains.buildServer.nuget.feed.server.controllers.NuGetFeedHandler import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedFactory import jetbrains.buildServer.serverSide.TeamCityProperties import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class JsonSearchQueryHandler( private val feedFactory: NuGetFeedFactory, private val packageSourceFactory: JsonPackageSourceFactory, private val adapterFactory: JsonPackageAdapterFactory) : NuGetFeedHandler { override fun handleRequest(feedData: NuGetFeedData, request: HttpServletRequest, response: HttpServletResponse) { val feed = feedFactory.createFeed(feedData) val context = JsonNuGetFeedContext(feed, request) if (DispatcherUtils.isAsyncEnabled()) { DispatcherUtils.dispatchSearchPackages(request, response, context) } else { searchPackages(request, response, context) } } private fun searchPackages(request: HttpServletRequest, response: HttpServletResponse, context: JsonNuGetFeedContext) { val query = request.getParameter("q") val skip = request.getParameter("skip")?.toIntOrNull() val take = request.getParameter("take")?.toIntOrNull() ?: NuGetFeedConstants.NUGET_FEED_PACKAGE_SIZE val prerelease = request.getParameter("prerelease")?.toBoolean() ?: false val includeSemVer2 = request.includeSemVer2() val packageSource = packageSourceFactory.create(context.feed) val packages = packageSource.searchPackages(query, prerelease, includeSemVer2) val adapter = adapterFactory.create(context) response.writeJson(adapter.createSearchPackagesResponse(packages, take, skip)) } }
apache-2.0
c7bbb2462e50aa81d67b67df3c7cfad8
48.923077
123
0.763225
4.725728
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/store/gem/GemPackSideEffectHandler.kt
1
1623
package io.ipoli.android.store.gem import io.ipoli.android.common.AppSideEffectHandler import io.ipoli.android.common.AppState import io.ipoli.android.common.redux.Action import io.ipoli.android.common.view.CurrencyConverterAction import io.ipoli.android.player.usecase.ConvertCoinsToGemsUseCase import io.ipoli.android.store.usecase.PurchaseGemPackUseCase import space.traversal.kapsule.required /** * Created by Venelin Valkov <[email protected]> * on 04/24/2018. */ object GemPackSideEffectHandler : AppSideEffectHandler() { private val purchaseGemPackUseCase by required { purchaseGemPackUseCase } private val convertCoinsToGemsUseCase by required { convertCoinsToGemsUseCase } override suspend fun doExecute(action: Action, state: AppState) { when (action) { is CurrencyConverterAction.Convert -> dispatch( CurrencyConverterAction.ConvertTransactionComplete( convertCoinsToGemsUseCase.execute(ConvertCoinsToGemsUseCase.Params(action.gems)) ) ) is GemStoreAction.GemPackBought -> { val gsvs = state.stateFor(GemStoreViewState::class.java) val gemPack = gsvs.gemPacks.first { it.type == action.gemPackType } val result = purchaseGemPackUseCase.execute(PurchaseGemPackUseCase.Params(gemPack)) dispatch(GemStoreAction.GemPackPurchased(result.hasUnlockedPet)) } } } override fun canHandle(action: Action) = action is GemStoreAction || action is CurrencyConverterAction }
gpl-3.0
2e9b5367226df43b945b621a27e145e6
36.767442
104
0.704251
4.422343
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/common/text/RepeatPatternFormatter.kt
1
1232
package io.ipoli.android.common.text import android.content.Context import io.ipoli.android.R import io.ipoli.android.repeatingquest.entity.RepeatPattern /** * Created by Venelin Valkov <[email protected]> * on 04/11/2018. */ object RepeatPatternFormatter { fun format(context: Context, repeatPattern: RepeatPattern): String = when (repeatPattern) { is RepeatPattern.Daily -> context.getString(R.string.every_day) is RepeatPattern.Weekly, is RepeatPattern.Flexible.Weekly -> if (repeatPattern.countInPeriod == 1) context.getString(R.string.once_a_week) else context.getString(R.string.times_a_week, repeatPattern.countInPeriod) is RepeatPattern.Monthly, is RepeatPattern.Flexible.Monthly -> if (repeatPattern.countInPeriod == 1) context.getString(R.string.once_a_month) else context.getString(R.string.times_a_month, repeatPattern.countInPeriod) is RepeatPattern.Yearly -> context.getString(R.string.once_a_year) is RepeatPattern.Manual -> context.getString(R.string.manual_schedule_repeat_pattern) } }
gpl-3.0
19bde1ab4c4722a11b1db1cf1a5a3a93
43.035714
97
0.655032
4.148148
false
false
false
false
donglua/JZAndroidChart
demo-chart2/src/main/java/cn/jingzhuan/lib/chart2/demo/BarChartModel.kt
1
1642
package cn.jingzhuan.lib.chart2.demo import androidx.databinding.ViewDataBinding import android.graphics.Color import android.view.View import android.view.ViewGroup import cn.jingzhuan.lib.chart.data.BarDataSet import cn.jingzhuan.lib.chart.data.BarValue import cn.jingzhuan.lib.chart2.demo.databinding.LayoutBarChartBinding import com.airbnb.epoxy.DataBindingEpoxyModel import com.airbnb.epoxy.EpoxyModelClass import java.util.ArrayList /** * Created by Donglua on 17/8/2. */ @EpoxyModelClass(layout = R.layout.layout_bar_chart) abstract class BarChartModel : DataBindingEpoxyModel() { private val barDataSet: BarDataSet init { val barValueList = ArrayList<BarValue>() barValueList.add(BarValue(11f)) barValueList.add(BarValue(10f)) barValueList.add(BarValue(11f)) barValueList.add(BarValue(13f)) barValueList.add(BarValue(11f)) barValueList.add(BarValue(12f)) barValueList.add(BarValue(12f)) barValueList.add(BarValue(13f).apply { setGradientColors(Color.WHITE, Color.BLACK) }) barValueList.add(BarValue(15f).apply { setGradientColors(Color.WHITE, Color.BLACK) }) barDataSet = BarDataSet(barValueList) barDataSet.isAutoBarWidth = true } override fun buildView(parent: ViewGroup): View { val rootView = super.buildView(parent) val barBinding = rootView.tag as LayoutBarChartBinding barBinding.barChart.setDataSet(barDataSet) barBinding.barChart.axisRight.labelTextColor = Color.BLACK return rootView } override fun setDataBindingVariables(binding: ViewDataBinding) { binding as LayoutBarChartBinding binding.barChart.animateY(500) } }
apache-2.0
0e824cc848841707b1f160a1c80d79e0
28.321429
89
0.772229
3.577342
false
false
false
false
ftomassetti/kolasu
core/src/main/kotlin/com/strumenta/kolasu/parsing/KolasuParser.kt
1
9468
package com.strumenta.kolasu.parsing import com.strumenta.kolasu.model.* import com.strumenta.kolasu.traversing.walk import com.strumenta.kolasu.validation.Issue import com.strumenta.kolasu.validation.IssueType import org.antlr.v4.runtime.* import org.antlr.v4.runtime.misc.Interval import java.io.File import java.io.FileInputStream import java.io.InputStream import java.nio.charset.Charset import java.util.* import kotlin.reflect.full.memberFunctions import kotlin.system.measureTimeMillis /** * A complete description of a multi-stage ANTLR-based parser, from source code to AST. * * You should extend this class to implement the parts that are specific to your language. */ abstract class KolasuParser<R : Node, P : Parser, C : ParserRuleContext> : ASTParser<R> { /** * Creates the lexer. */ @JvmOverloads protected open fun createANTLRLexer(inputStream: InputStream, charset: Charset = Charsets.UTF_8): Lexer { return createANTLRLexer(CharStreams.fromStream(inputStream, charset)) } /** * Creates the lexer. */ protected abstract fun createANTLRLexer(charStream: CharStream): Lexer /** * Creates the first-stage parser. */ protected abstract fun createANTLRParser(tokenStream: TokenStream): P /** * Invokes the parser's root rule, i.e., the method which is responsible of parsing the entire input. * Usually this is the topmost rule, the one with index 0 (as also assumed by other libraries such as antlr4-c3), * so this method invokes that rule. If your grammar/parser is structured differently, or if you're using this to * parse only a portion of the input or a subset of the language, you have to override this method to invoke the * correct entry point. */ protected open fun invokeRootRule(parser: P): C? { val entryPoint = parser::class.memberFunctions.find { it.name == parser.ruleNames[0] } return entryPoint!!.call(parser) as C } /** * Transforms a parse tree into an AST (second parsing stage). */ protected abstract fun parseTreeToAst( parseTreeRoot: C, considerPosition: Boolean = true, issues: MutableList<Issue> ): R? /** * Performs "lexing" on the given code string, i.e., it breaks it into tokens. */ @JvmOverloads fun lex(code: String, onlyFromDefaultChannel: Boolean = true): LexingResult { val charset = Charsets.UTF_8 return lex(code.byteInputStream(charset), charset, onlyFromDefaultChannel) } /** * Performs "lexing" on the given code stream, i.e., it breaks it into tokens. */ @JvmOverloads fun lex( inputStream: InputStream, charset: Charset = Charsets.UTF_8, onlyFromDefaultChannel: Boolean = true ): LexingResult { val issues = LinkedList<Issue>() val tokens = LinkedList<Token>() val time = measureTimeMillis { val lexer = createANTLRLexer(inputStream, charset) attachListeners(lexer, issues) do { val t = lexer.nextToken() if (t == null) { break } else { if (!onlyFromDefaultChannel || t.channel == Token.DEFAULT_CHANNEL) { tokens.add(t) } } } while (t.type != Token.EOF) if (tokens.last.type != Token.EOF) { val message = "The parser didn't consume the entire input" issues.add(Issue(IssueType.SYNTACTIC, message, position = tokens.last!!.endPoint.asPosition)) } } return LexingResult(issues, tokens, null, time) } protected open fun attachListeners(lexer: Lexer, issues: MutableList<Issue>) { lexer.injectErrorCollectorInLexer(issues) } protected open fun attachListeners(parser: P, issues: MutableList<Issue>) { parser.injectErrorCollectorInParser(issues) } /** * Creates the first-stage lexer and parser. */ protected fun createParser(inputStream: CharStream, issues: MutableList<Issue>): P { val lexer = createANTLRLexer(inputStream) attachListeners(lexer, issues) val tokenStream = createTokenStream(lexer) val parser: P = createANTLRParser(tokenStream) attachListeners(parser, issues) return parser } protected open fun createTokenStream(lexer: Lexer) = CommonTokenStream(lexer) /** * Checks the parse tree for correctness. If you're concerned about performance, you may want to override this to * do nothing. */ open fun verifyParseTree(parser: Parser, issues: MutableList<Issue>, root: ParserRuleContext) { val lastToken = parser.tokenStream.get(parser.tokenStream.index()) if (lastToken.type != Token.EOF) { issues.add( Issue( IssueType.SYNTACTIC, "The whole input was not consumed", position = lastToken!!.endPoint.asPosition ) ) } root.processDescendantsAndErrors( { if (it.exception != null) { val message = "Recognition exception: ${it.exception.message}" issues.add(Issue.syntactic(message, position = it.toPosition())) } }, { val message = "Error node found (token: ${it.symbol?.text})" issues.add(Issue.syntactic(message, position = it.toPosition())) } ) } @JvmOverloads fun parseFirstStage(code: String, measureLexingTime: Boolean = false): FirstStageParsingResult<C> { return parseFirstStage(CharStreams.fromString(code), measureLexingTime) } @JvmOverloads fun parseFirstStage( inputStream: InputStream, charset: Charset = Charsets.UTF_8, measureLexingTime: Boolean = false ): FirstStageParsingResult<C> { return parseFirstStage(CharStreams.fromStream(inputStream, charset), measureLexingTime) } @JvmOverloads fun parseFirstStage(inputStream: CharStream, measureLexingTime: Boolean = false): FirstStageParsingResult<C> { val issues = LinkedList<Issue>() var root: C? var lexingTime: Long? = null val time = measureTimeMillis { val parser = createParser(inputStream, issues) if (measureLexingTime) { val tokenStream = parser.inputStream if (tokenStream is CommonTokenStream) { lexingTime = measureTimeMillis { tokenStream.fill() tokenStream.seek(0) } } } root = invokeRootRule(parser) if (root != null) { verifyParseTree(parser, issues, root!!) } } return FirstStageParsingResult(issues, root, null, null, time, lexingTime) } @JvmOverloads fun parseFirstStage(file: File, charset: Charset = Charsets.UTF_8, measureLexingTime: Boolean = false): FirstStageParsingResult<C> = parseFirstStage(FileInputStream(file), charset, measureLexingTime) protected open fun postProcessAst(ast: R, issues: MutableList<Issue>): R { return ast } override fun parse(code: String, considerPosition: Boolean, measureLexingTime: Boolean): ParsingResult<R> { val inputStream = CharStreams.fromString(code) return parse(inputStream, considerPosition, measureLexingTime) } @JvmOverloads fun parse( inputStream: CharStream, considerPosition: Boolean = true, measureLexingTime: Boolean = false ): ParsingResult<R> { val start = System.currentTimeMillis() val firstStage = parseFirstStage(inputStream, measureLexingTime) val myIssues = firstStage.issues.toMutableList() var ast = parseTreeToAst(firstStage.root!!, considerPosition, myIssues) assignParents(ast) ast = if (ast == null) null else postProcessAst(ast, myIssues) if (ast != null && !considerPosition) { // Remove parseTreeNodes because they cause the position to be computed ast.walk().forEach { it.origin = null } } val now = System.currentTimeMillis() return ParsingResult( myIssues, ast, inputStream.getText(Interval(0, inputStream.index() + 1)), null, firstStage, now - start ) } override fun parse(file: File, charset: Charset, considerPosition: Boolean): ParsingResult<R> = parse(FileInputStream(file), charset, considerPosition) // For convenient use from Java fun walk(node: Node) = node.walk() @JvmOverloads fun processProperties( node: Node, propertyOperation: (PropertyDescription) -> Unit, propertiesToIgnore: Set<String> = emptySet() ) = node.processProperties(propertiesToIgnore, propertyOperation) /** * Traverses the AST to ensure that parent nodes are correctly assigned. * * If you're already assigning the parents correctly when you build the AST, or you're not interested in tracking * child-parent relationships, you can override this method to do nothing to improve performance. */ protected open fun assignParents(ast: R?) { ast?.assignParents() } }
apache-2.0
9863c86082544ebc9b5e8a502e1b0918
36.275591
117
0.635403
4.587209
false
false
false
false
pkleimann/livingdoc2
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/fixtures/FixtureMethodInvoker.kt
1
5917
package org.livingdoc.engine.fixtures import org.livingdoc.api.conversion.TypeConverter import org.livingdoc.converters.TypeConverters import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.lang.reflect.Parameter class FixtureMethodInvoker( private val document: Any? ) { /** * Invoke the given static `method` with the given [String] `arguments`. * * Before invoking the method, the [String] arguments will be converted into objects of the appropriate types. * This is done by looking up a matching [TypeConverter] as follows: * * 1. `parameter` * 2. `method` * 3. `class` * 4. `document` * 5. `default` * * This method is capable of invoking any static method. If the invoked method is not public, it will be made so. * * @param method the [Method] to invoke * @param arguments the arguments for the invoked method as strings * @return the result of the invocation or `null` in case the invoked method has not return type (`void` / `Unit`) * @throws StaticFixtureMethodInvocationException in case anything went wrong with the invocation */ fun invokeStatic(method: Method, arguments: Array<String> = emptyArray()): Any? { try { return doInvokeStatic(method, arguments) } catch (e: Exception) { throw StaticFixtureMethodInvocationException(method, method.declaringClass, e) } } private fun doInvokeStatic(method: Method, arguments: Array<String>): Any? { val methodParameters = method.parameters assertThatAllArgumentsForMethodAreProvided(arguments, methodParameters) val convertedArguments = convert(arguments, methodParameters) return forceInvocation(method, convertedArguments) } /** * Invoke the given `method` on the given `fixture` instance with the given [String] `arguments`. * * Before invoking the method, the [String] arguments will be converted into objects of the appropriate types. * This is done by looking up a matching [TypeConverter] as follows: * * 1. `parameter` * 2. `method` * 3. `class` * 4. `document` * 5. `default` * * This method is capable of invoking any method on the given fixture instance. If the invoked method is not * public, it will be made so. * * @param method the [Method] to invoke * @param fixture the fixture instance to invoke the method on * @param arguments the arguments for the invoked method as strings * @return the result of the invocation or `null` in case the invoked method has not return type (`void` / `Unit`) * @throws FixtureMethodInvocationException in case anything went wrong with the invocation */ fun invoke(method: Method, fixture: Any, arguments: Array<String> = emptyArray()): Any? { try { return doInvoke(method, fixture, arguments) } catch (e: Exception) { throw FixtureMethodInvocationException(method, fixture, e) } } private fun doInvoke(method: Method, fixture: Any, arguments: Array<String>): Any? { val methodParameters = method.parameters assertThatAllArgumentsForMethodAreProvided(arguments, methodParameters) val convertedArguments = convert(arguments, methodParameters) return forceInvocation(method, convertedArguments, fixture) } private fun assertThatAllArgumentsForMethodAreProvided( arguments: Array<String>, methodParameters: Array<Parameter> ) { val numberOfArguments = arguments.size val numberOfMethodParameters = methodParameters.size if (numberOfArguments != numberOfMethodParameters) { throw MismatchedNumberOfArgumentsException(numberOfArguments, numberOfMethodParameters) } } private fun convert( arguments: Array<String>, methodParameters: Array<Parameter> ): Array<Any> { // TODO: Zip function? val convertedArguments = mutableListOf<Any>() for (i in arguments.indices) { val argument = arguments[i] val methodParameter = methodParameters[i] val convertedArgument = convert(argument, methodParameter) convertedArguments.add(convertedArgument) } return convertedArguments.toTypedArray() } private fun convert(argument: String, methodParameter: Parameter): Any { val documentClass = document?.javaClass val typeConverter = TypeConverters.findTypeConverter(methodParameter, documentClass) ?: throw NoTypeConverterFoundException(methodParameter) return typeConverter.convert(argument, methodParameter, documentClass) } private fun forceInvocation(method: Method, arguments: Array<Any>, instance: Any? = null): Any? { method.isAccessible = true try { return method.invoke(instance, *arguments) } catch (e: InvocationTargetException) { throw e.cause ?: e } } class FixtureMethodInvocationException(method: Method, fixture: Any, e: Exception) : RuntimeException("Could not invoke method '$method' on fixture '$fixture' because of an exception:", e) class StaticFixtureMethodInvocationException(method: Method, fixtureClass: Class<*>, e: Exception) : RuntimeException( "Could not invoke method '$method' on fixture class '$fixtureClass' because of an exception:", e ) internal class MismatchedNumberOfArgumentsException(args: Int, params: Int) : RuntimeException("Method argument number mismatch: arguments = $args, method parameters = $params") internal class NoTypeConverterFoundException(parameter: Parameter) : RuntimeException("No type converter could be found to convert method parameter: $parameter") }
apache-2.0
a5c93ef1f25e1db007509a26034e6662
41.568345
118
0.684975
4.898179
false
false
false
false
mdanielwork/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequestExecutorManager.kt
3
2961
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import org.jetbrains.annotations.CalledInAwt import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.AccountTokenChangedListener import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager import org.jetbrains.plugins.github.exceptions.GithubMissingTokenException import java.awt.Component /** * Allows to acquire API executor without exposing the auth token to external code */ class GithubApiRequestExecutorManager internal constructor(private val accountManager: GithubAccountManager, private val authenticationManager: GithubAuthenticationManager, private val requestExecutorFactory: GithubApiRequestExecutor.Factory) : AccountTokenChangedListener { private val executors = mutableMapOf<GithubAccount, GithubApiRequestExecutor.WithTokenAuth>() init { ApplicationManager.getApplication().messageBus .connect() .subscribe(GithubAccountManager.ACCOUNT_TOKEN_CHANGED_TOPIC, this) } override fun tokenChanged(account: GithubAccount) { val token = accountManager.getTokenForAccount(account) if (token == null) executors.remove(account) else executors[account]?.token = token } @CalledInAwt fun getExecutor(account: GithubAccount, project: Project): GithubApiRequestExecutor.WithTokenAuth? { return getOrTryToCreateExecutor(account) { authenticationManager.requestNewToken(account, project) } } @CalledInAwt fun getExecutor(account: GithubAccount, parentComponent: Component): GithubApiRequestExecutor.WithTokenAuth? { return getOrTryToCreateExecutor(account) { authenticationManager.requestNewToken(account, null, parentComponent) } } @CalledInAwt @Throws(GithubMissingTokenException::class) fun getExecutor(account: GithubAccount): GithubApiRequestExecutor.WithTokenAuth { return getOrTryToCreateExecutor(account) { throw GithubMissingTokenException(account) }!! } private fun getOrTryToCreateExecutor(account: GithubAccount, missingTokenHandler: () -> String?): GithubApiRequestExecutor.WithTokenAuth? { return executors.getOrPut(account) { (authenticationManager.getTokenForAccount(account) ?: missingTokenHandler()) ?.let(requestExecutorFactory::create) ?: return null } } companion object { @JvmStatic fun getInstance(): GithubApiRequestExecutorManager = service() } }
apache-2.0
6e6688f278759d5ad3ea4a686e34b6b2
43.878788
140
0.765282
5.607955
false
false
false
false
dahlstrom-g/intellij-community
platform/script-debugger/protocol/protocol-model-generator/src/ListType.kt
19
1168
package org.jetbrains.protocolModelGenerator open class ListType(private val itemType: BoxableType) : BoxableType { override val defaultValue: Nothing? = null override val writeMethodName: String get() = when { itemType == BoxableType.STRING -> "writeStringList" itemType == BoxableType.LONG -> "writeLongArray" itemType == BoxableType.INT -> "writeIntArray" itemType == BoxableType.NUMBER -> "writeDoubleArray" itemType == BoxableType.NUMBER -> "writeDoubleArray" itemType is StandaloneType && itemType.writeMethodName == "writeEnum" -> "writeEnumList" else -> "writeList" } override val fullText: CharSequence get() { if (itemType == BoxableType.LONG || itemType == BoxableType.INT || itemType == BoxableType.NUMBER) { return "Array<${itemType.fullText}>" } return "List<${itemType.fullText}>" } override fun getShortText(contextNamespace: NamePath): String { if (itemType == BoxableType.LONG || itemType == BoxableType.INT || itemType == BoxableType.NUMBER) { return "${itemType.fullText}Array" } return "List<${itemType.getShortText(contextNamespace)}>" } }
apache-2.0
f6eddf1067a85a07be71237de06ec8d7
36.709677
104
0.688356
4.728745
false
false
false
false
MasoodFallahpoor/InfoCenter
InfoCenter/src/main/java/com/fallahpoor/infocenter/fragments/RamFragment.kt
1
3847
/* Copyright (C) 2014-2016 Masood Fallahpoor This file is part of Info Center. Info Center 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. Info Center 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 Info Center. If not, see <http://www.gnu.org/licenses/>. */ package com.fallahpoor.infocenter.fragments import android.app.ActivityManager import android.app.ActivityManager.MemoryInfo import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.fallahpoor.infocenter.R import com.fallahpoor.infocenter.Utils import com.fallahpoor.infocenter.adapters.CustomArrayAdapter import com.fallahpoor.infocenter.adapters.ListItem import com.fallahpoor.infocenter.adapters.OrdinaryListItem import kotlinx.android.synthetic.main.fragment_others.* import java.io.BufferedReader import java.io.FileReader import java.util.* /** * RamFragment displays the total and free RAM of the device. */ class RamFragment : Fragment() { private var utils: Utils? = null private val listItems: ArrayList<ListItem> get() { return ArrayList<ListItem>().apply { add(OrdinaryListItem(getString(R.string.ram_item_total_ram), totalRam)) add(OrdinaryListItem(getString(R.string.ram_item_free_ram), freeRam)) } } // Returns the total RAM of the device private val totalRam: String get() { val buffReader: BufferedReader val aLine: String val lngTotalRam: Long var totalRam: String try { buffReader = BufferedReader(FileReader("/proc/meminfo")) aLine = buffReader.readLine() buffReader.close() val tokens = aLine.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() lngTotalRam = java.lang.Long.parseLong(tokens[1]) * 1024 totalRam = utils!!.getFormattedSize(lngTotalRam) } catch (ex: Exception) { totalRam = getString(R.string.unknown) } return totalRam } // end method getTotalRam // Returns the free RAM of the device private val freeRam: String get() { val memoryInfo = MemoryInfo() val activityManager: ActivityManager? val lngFreeRam: Long val freeRam: String activityManager = activity!!.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager activityManager.getMemoryInfo(memoryInfo) lngFreeRam = memoryInfo.availMem freeRam = utils!!.getFormattedSize(lngFreeRam) return freeRam } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.fragment_others, container, false) utils = Utils(activity!!) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) listView.adapter = CustomArrayAdapter(activity, listItems) } }
gpl-3.0
1260940fcfa4650f68405d99d50ca750
31.066667
95
0.668313
4.697192
false
false
false
false
Leanplum/Leanplum-Android-SDK
AndroidSDKCore/src/main/java/com/leanplum/migration/wrapper/IdentityManager.kt
1
4400
/* * Copyright 2022, Leanplum, Inc. All rights reserved. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.leanplum.migration.wrapper import com.leanplum.internal.Log import com.leanplum.migration.MigrationConstants import com.leanplum.utils.StringPreference import com.leanplum.utils.StringPreferenceNullable import kotlin.properties.ReadWriteProperty private const val UNDEFINED = "undefined" private const val ANONYMOUS = "anonymous" private const val IDENTIFIED = "identified" /** * Scheme for migrating user profile is as follows: * - anonymous is translated to <CTID=deviceId, Identity=null> * - non-anonymous to <CTID=deviceId_hash(userId), Identity=userId> * Where deviceId is also hashed if it is longer than 50 characters or contains invalid symbols. * * When you login, but previous profile is anonymous, a merge should happen. CT SDK allows merges * only when the CTID remains the same, meaning that the merged profile would get the anonymous * profile's CTID. This is the reason to save anonymousMergeUserId into SharedPreferences and to * allow it to restore when user is back. * * When you call Leanplum.start and pass userId, that is not currently logged in, there are several * cases that could happen: * * 1. "undefined" state * * Wrapper hasn't been started even once, meaning that anonymous profile doesn't exist, so use the * "deviceId_hash(userId)" scheme. * * 2. "anonymous" state * * Wrapper has been started and previous user is anonymous - use deviceId as CTID to allow merge of * anonymous data. * * 3. "identified" state * * Wrapper has been started and previous user is not anonymous - use the "deviceId_hash(userId)" * scheme. */ class IdentityManager( deviceId: String, userId: String, stateDelegate: ReadWriteProperty<Any, String> = StringPreference("ct_login_state", UNDEFINED), mergeUserDelegate: ReadWriteProperty<Any, String?> = StringPreferenceNullable("ct_anon_merge_userid"), ) { private val identity: LPIdentity = LPIdentity(deviceId = deviceId, userId = userId) private var state: String by stateDelegate private val startState: String private var anonymousMergeUserId: String? by mergeUserDelegate init { startState = state if (isAnonymous()) { loginAnonymously() } else { loginIdentified() } } fun isAnonymous() = identity.isAnonymous() fun isFirstTimeStart() = startState == UNDEFINED private fun loginAnonymously() { state = ANONYMOUS } private fun loginIdentified() { if (state == UNDEFINED) { state = IDENTIFIED } else if (state == ANONYMOUS) { anonymousMergeUserId = identity.userId() Log.d("Wrapper: anonymous data will be merged to $anonymousMergeUserId") state = IDENTIFIED } } fun cleverTapId(): String { if (identity.isAnonymous()) { return identity.deviceId() } else if (identity.userId() == anonymousMergeUserId) { return identity.deviceId() } else { return "${identity.deviceId()}_${identity.userId()}" } } fun profile() = mapOf(MigrationConstants.IDENTITY to identity.originalUserId()) fun setUserId(userId: String): Boolean { if (!identity.setUserId(userId)) { // trying to set same userId return false } if (state == ANONYMOUS) { anonymousMergeUserId = identity.userId() Log.d("Wrapper: anonymous data will be merged to $anonymousMergeUserId") state = IDENTIFIED } return true; } fun isDeviceIdHashed() = identity.originalDeviceId() != identity.deviceId() fun getOriginalDeviceId() = identity.originalDeviceId() }
apache-2.0
269fcf80f5700011b447feb2c2773291
32.082707
104
0.721591
4.259439
false
false
false
false
phylame/jem
imabw/src/main/kotlin/jem/imabw/ui/Dialogs.kt
1
11322
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jem.imabw.ui import javafx.application.Platform import javafx.beans.binding.Bindings import javafx.scene.control.* import javafx.scene.layout.BorderPane import javafx.scene.layout.VBox import javafx.stage.DirectoryChooser import javafx.stage.FileChooser import javafx.stage.Modality import javafx.stage.Window import jclp.ValueMap import jclp.text.ifNotEmpty import jclp.traceText import jem.Chapter import jem.epm.EpmManager import jem.epm.FileParser import jem.epm.PMAB_NAME import jem.imabw.* import jem.title import mala.App import mala.ixin.graphicFor import java.io.File import java.util.concurrent.Callable fun Dialog<*>.init(title: String, owner: Window, tag: String = "") { headerText = null this.title = title initModality(Modality.WINDOW_MODAL) initOwner(owner) if (tag.isNotEmpty()) { setOnShowing { UISettings.restoreState(this, tag) } setOnHidden { UISettings.storeState(this, tag) } } } fun alert(type: Alert.AlertType, title: String, content: String, owner: Window = Imabw.topWindow): Alert { return Alert(type, content).apply { init(title, owner) } } fun info(title: String, content: String, owner: Window = Imabw.topWindow) { alert(Alert.AlertType.INFORMATION, title, content, owner).showAndWait() } fun error(title: String, content: String, owner: Window = Imabw.topWindow) { alert(Alert.AlertType.ERROR, title, content, owner).showAndWait() } fun confirm(title: String, content: String, owner: Window = Imabw.topWindow): Boolean { return with(alert(Alert.AlertType.CONFIRMATION, title, content, owner)) { showAndWait().get() == ButtonType.OK } } fun debug(title: String, content: String, throwable: Throwable, owner: Window) { with(alert(Alert.AlertType.NONE, title, content, owner)) { val textArea = TextArea().apply { isEditable = false isFocusTraversable = false styleClass += "error-text" } dialogPane.expandableContent = textArea dialogPane.buttonTypes += ButtonType.CLOSE graphic = App.assets.graphicFor("dialog/bug") dialogPane.expandedProperty().addListener { _ -> if (textArea.text.isEmpty()) textArea.text = throwable.traceText } showAndWait() } } fun input( title: String, label: String, initial: String, canEmpty: Boolean = true, mustDiff: Boolean = false, owner: Window = Imabw.topWindow ): String? { return with(TextInputDialog(initial)) { graphic = null init(title, owner) val textField = editor textField.prefColumnCount = 20 val okButton = dialogPane.lookupButton(ButtonType.OK) if (!canEmpty) { if (mustDiff) { okButton.disableProperty().bind(Bindings.createBooleanBinding(Callable { textField.text.let { it.isEmpty() || it == initial } }, textField.textProperty())) } else { okButton.disableProperty().bind(Bindings.isEmpty(textField.textProperty())) } } else if (mustDiff) { okButton.disableProperty().bind(Bindings.equal(textField.textProperty(), initial)) } contentText = label showAndWait().let { if (it.isPresent) it.get() else null } } } fun text( title: String, initial: String, canEmpty: Boolean = true, mustDiff: Boolean = false, owner: Window = Imabw.topWindow ): String? { with(Dialog<ButtonType>()) { init(title, owner, "text") val root = VBox().apply { dialogPane.content = this } val textArea = TextArea().apply { text = initial isWrapText = true root.children += this selectAll() } val openButton = ButtonType(App.tr("ui.button.open"), ButtonBar.ButtonData.LEFT) dialogPane.buttonTypes.addAll(ButtonType.OK, ButtonType.CANCEL, openButton) dialogPane.lookupButton(openButton).isDisable = true val okButton = dialogPane.lookupButton(ButtonType.OK) if (!canEmpty) { if (mustDiff) { okButton.disableProperty().bind(Bindings.createBooleanBinding(Callable { textArea.text.let { it.isEmpty() || it == initial } }, textArea.textProperty())) } else { okButton.disableProperty().bind(Bindings.isEmpty(textArea.textProperty())) } } else if (mustDiff) { okButton.disableProperty().bind(Bindings.equal(textArea.textProperty(), initial)) } Platform.runLater { textArea.requestFocus() } return if (showAndWait().get() == ButtonType.OK) textArea.text else null } } private val fileChooser = FileChooser().apply { (Workbench.work?.path ?: History.latest)?.let { File(it) }?.let { if (it.isDirectory) { initialDirectory = it } else if (it.exists()) { initialDirectory = it.parentFile } } } private val directoryChooser = DirectoryChooser() private val allExtensionFilter = FileChooser.ExtensionFilter(getExtensionName("any"), "*.*") private fun getExtensionName(ext: String): String { return App.optTr("misc.ext.$ext") ?: App.tr("misc.ext.common", ext.toUpperCase()) } private fun setExtensionFilters(chooser: FileChooser, extensions: Collection<Collection<String>>, selected: String) { val filters = chooser.extensionFilters for (extension in extensions) { FileChooser.ExtensionFilter(getExtensionName(extension.first()), extension.map { "*.$it" }).apply { filters += this if (selected in extension) { chooser.selectedExtensionFilter = this } } } } fun selectOpenFile(title: String, owner: Window): File? { fileChooser.title = title fileChooser.extensionFilters.clear() return fileChooser.showOpenDialog(owner) } fun selectSaveFile(title: String, initName: String = "", owner: Window): File? { fileChooser.title = title fileChooser.extensionFilters.setAll(allExtensionFilter) fileChooser.initialFileName = initName return fileChooser.showSaveDialog(owner) } fun selectDirectory(title: String, owner: Window): File? { directoryChooser.title = title return directoryChooser.showDialog(owner) } fun selectOpenImage(title: String, owner: Window): File? { fileChooser.title = title GeneralSettings.lastImageDir.ifNotEmpty { fileChooser.initialDirectory = File(it) } fileChooser.extensionFilters.setAll(allExtensionFilter) setExtensionFilters(fileChooser, setOf( setOf("jpg", "jpeg"), setOf("png"), setOf("bmp"), setOf("gif") ), "") return fileChooser.showOpenDialog(owner)?.apply { GeneralSettings.lastImageDir = parent } } private fun parserExtensions(): List<Set<String>> { return EpmManager.services.filter { it.hasParser && it is FileParser }.map { it.keys } } private fun makerExtensions(): List<Set<String>> { return EpmManager.services.filter { it.hasMaker }.map { it.keys } } private fun makeSaveResult(file: File, chooser: FileChooser): Pair<File, String> { var extension = file.extension val extensions = chooser.selectedExtensionFilter.extensions if (extensions.find { extension in it } == null) { extension = extensions.first().substring(2) // trim '*.' } return file to extension } fun openBookFile(owner: Window): File? { fileChooser.title = App.tr("d.openBook.title") fileChooser.extensionFilters.clear() setExtensionFilters(fileChooser, parserExtensions(), PMAB_NAME) GeneralSettings.lastBookDir.ifNotEmpty { fileChooser.initialDirectory = File(it) } return fileChooser.showOpenDialog(owner)?.also { GeneralSettings.lastBookDir = it.parent } } fun saveBookFile(name: String, format: String, owner: Window): Pair<File, String>? { fileChooser.initialFileName = name fileChooser.title = App.tr("d.saveBook.title") fileChooser.extensionFilters.setAll(FileChooser.ExtensionFilter(getExtensionName(format), "*.$format")) GeneralSettings.lastBookDir.ifNotEmpty { fileChooser.initialDirectory = File(it) } return fileChooser.showSaveDialog(owner)?.let { GeneralSettings.lastBookDir = it.parent makeSaveResult(it, fileChooser) } } fun saveBookFile(name: String, owner: Window): Pair<File, String>? { fileChooser.initialFileName = name fileChooser.title = App.tr("d.saveBook.title") fileChooser.extensionFilters.clear() setExtensionFilters(fileChooser, makerExtensions(), PMAB_NAME) GeneralSettings.lastBookDir.ifNotEmpty { fileChooser.initialDirectory = File(it) } return fileChooser.showSaveDialog(owner)?.let { GeneralSettings.lastBookDir = it.parent makeSaveResult(it, fileChooser) } } fun openBookFiles(owner: Window): List<File>? { fileChooser.title = App.tr("d.openBook.title") fileChooser.extensionFilters.clear() setExtensionFilters(fileChooser, parserExtensions(), PMAB_NAME) GeneralSettings.lastBookDir.ifNotEmpty { fileChooser.initialDirectory = File(it) } return fileChooser.showOpenMultipleDialog(owner)?.also { GeneralSettings.lastBookDir = it.first().parent } } fun editAttributes(chapter: Chapter, owner: Window): Boolean { with(Dialog<ButtonType>()) { isResizable = true init(App.tr("d.editAttribute.title", chapter.title), owner, "attributes") val pane = AttributePane(chapter).apply { dialogPane.content = BorderPane(this) } dialogPane.buttonTypes.setAll(ButtonType.OK, ButtonType.CANCEL) dialogPane.content.style += "-fx-padding: 0" val result = showAndWait().get() pane.storeState() return if (result == ButtonType.OK && pane.isModified) { pane.syncVariants() true } else false } } fun editVariants(map: ValueMap, title: String, ignoredKeys: Set<String> = emptySet(), owner: Window): Boolean { with(Dialog<ButtonType>()) { isResizable = true init(title, owner, "variants") val pane = object : VariantPane(map, "variants", false) { override fun ignoredKeys() = ignoredKeys } dialogPane.content = pane dialogPane.content.style += "-fx-padding: 0" dialogPane.buttonTypes.setAll(ButtonType.OK, ButtonType.CANCEL) val result = showAndWait().get() pane.storeState() return if (result == ButtonType.OK && pane.isModified) { pane.syncVariants() true } else false } }
apache-2.0
0f41a88420595129e0527ddd0cbf3526
35.75974
117
0.668786
4.264407
false
false
false
false
JoelMarcey/buck
tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/actions/select/KotlinRunLineMarkerContributor.kt
1
2805
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.intellij.ideabuck.actions.select import com.facebook.buck.intellij.ideabuck.actions.select.detectors.KotlinPotentialTestClass import com.facebook.buck.intellij.ideabuck.actions.select.detectors.KotlinPotentialTestFunction import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.openapi.util.IconLoader import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.containingClass /** * Creates runnable line markers (gutter icon) for classes/methods that can be run by a buck test * configurations. */ class KotlinRunLineMarkerContributor : RunLineMarkerContributor() { override fun getInfo(psiElement: PsiElement): Info? { if (psiElement is LeafPsiElement && psiElement.elementType === KtTokens.IDENTIFIER) { when (val parent = psiElement.parent) { is KtClass -> { val isTestClass = BuckKotlinTestDetector.isTestClass(KotlinPotentialTestClass(parent)) if (isTestClass) { val runAction = ClassKotlinBuckTestAction(parent, false) val debugAction = ClassKotlinBuckTestAction(parent, true) return buildInfo(runAction, debugAction) } } is KtNamedFunction -> { val containingClass = parent.containingClass() ?: return null val isTestFunction = BuckKotlinTestDetector.isTestFunction(KotlinPotentialTestFunction(parent)) if (isTestFunction) { val runAction = FunctionKotlinBuckTestAction(parent, containingClass, false) val debugAction = FunctionKotlinBuckTestAction(parent, containingClass, true) return buildInfo(runAction, debugAction) } } } } return null } private fun buildInfo(runAction: KotlinBuckTestAction, debugAction: KotlinBuckTestAction): Info { return Info( IconLoader.getIcon("/icons/buck_icon.png"), arrayOf(runAction, debugAction), RUN_TEST_TOOLTIP_PROVIDER) } }
apache-2.0
faab5466e3989d8ff1299095eeb55335
38.507042
99
0.730838
4.605911
false
true
false
false
gmariotti/kotlin-koans
lesson5/task4/src/Task.kt
1
1043
fun renderProductTable(): String { return html { table { tr (color = getTitleColor()){ td { text("Product") } td { text("Price") } td { text("Popularity") } } val products = getProducts() for ((index, product) in products.withIndex()) { tr { td (color = getCellColor(index, 0)) { text(product.description) } td (color = getCellColor(index, 1)) { text(product.price) } td (color = getCellColor(index, 2)) { text(product.popularity) } } } } }.toString() } fun getTitleColor() = "#b9c9fe" fun getCellColor(index: Int, row: Int) = if ((index + row) %2 == 0) "#dce4ff" else "#eff2ff"
mit
cabf735012d9560c4e74c1d09bb07b18
29.705882
92
0.365292
5.112745
false
false
false
false
outbrain/ob1k
ob1k-crud/src/main/java/com/outbrain/ob1k/crud/CrudApplication.kt
1
4601
package com.outbrain.ob1k.crud import com.google.gson.JsonObject import com.outbrain.ob1k.concurrent.ComposableFuture import com.outbrain.ob1k.concurrent.ComposableFutures import com.outbrain.ob1k.crud.dao.* import com.outbrain.ob1k.crud.model.EntityDescription import com.outbrain.ob1k.crud.model.EntityField import com.outbrain.ob1k.crud.model.Model import com.outbrain.ob1k.crud.service.CrudDispatcher import com.outbrain.ob1k.crud.service.ModelService import com.outbrain.ob1k.db.IBasicDao import java.util.concurrent.ExecutorService class CrudApplication(private val dao: IBasicDao? = null, commaDelimitedTables: String = "") { private val tables = commaDelimitedTables.split(",").filter { it.isNotEmpty() } var model = Model() var dispatcher = CrudDispatcher() init { if (commaDelimitedTables.isNotBlank()) { dao?.let { withTableInfo(dao, tables).get() } dao?.let { updateTableReferences(dao).get() } dao?.let { tables.map { newMySQLDao(it) }.forEach { dispatcher = dispatcher.register(it, model) } } } } private fun withTableInfo(dao: IBasicDao, tables: List<String>) = ComposableFutures.foreach(tables, this, { table, _ -> withTableInfo(dao, table) }) private fun withTableInfo(dao: IBasicDao, table: String): ComposableFuture<CrudApplication> { return dao.list("SHOW COLUMNS FROM $table", EntityFieldMapper()) .map { EntityDescription(table = table, id = model.total, fields = it) } .map { withEntity(it) } } private fun updateTableReferences(dao: IBasicDao) = dao.list("SELECT TABLE_NAME,COLUMN_NAME,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME " + "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " + "WHERE REFERENCED_TABLE_NAME IS NOT NULL AND " + "TABLE_NAME IN (${tables.map { "'$it'" }.joinToString(",")})", RefFieldMapper(model)) fun withEntity(resourceName: String, fields: List<EntityField>) = withEntity(EntityDescription(table = "_$resourceName", id = model.total, fields = fields)) fun withEntity(it: EntityDescription): CrudApplication { model = model.withEntity(it) return this } fun <T> withEntity(it: Class<T>): CrudApplication { model = model.withEntity(it) return this } fun addReference(from: String, to: String) = addReference(from, to, to) fun referenceManyAsList(from: String, to: String): CrudApplication { get(from).fromReferenceManyToList(to) model = Model(model.total - 1, model.data.filter { it.resourceName != to }) return this } fun addOneToOneReference(from: String, to: String) = addOneToOneReference(from, to, to) fun addOneToManyReference(from: String, to: String) = addOneToManyReference(from, to, "${to}s") fun addReference(from: String, to: String, by: String): CrudApplication { get(from).add2DirectionReferenceTo(get(to), by) return this } fun addOneToOneReference(from: String, to: String, by: String): CrudApplication { get(from).addOneToOneference(get(to), by) return this } fun addOneToManyReference(from: String, to: String, by: String): CrudApplication { get(from).addOneToManyReference(get(to), by) return this } fun newMySQLDao(table: String) = MySQLCrudDao(model.getByTable(table)!!, dao!!) fun <T> newCustomDao(dao: ICrudAsyncDao<T>, dateformat: String) = CrudAsyncDaoDelegate(get(dao.resourceName()), dao, dateformat) fun <T> newCustomDao(dao: ICrudDao<T>, dateformat: String, executorService: ExecutorService) = newCustomDao(AsyncDaoBridge(dao, executorService), dateformat) fun <T> withCustomDao(dao: ICrudDao<T>, dateformat: String, executorService: ExecutorService) = withCustomDao(AsyncDaoBridge(dao, executorService), dateformat) fun <T> withCustomDao(dao: ICrudAsyncDao<T>, dateformat: String) = withDao(CrudAsyncDaoDelegate(get(dao.resourceName()), dao, dateformat)) fun withDao(dao: ICrudAsyncDao<JsonObject>): CrudApplication { dispatcher = dispatcher.register(dao, model) return this } fun dispatcher() = dispatcher fun modelService() = ModelService(model) operator fun invoke(resourceName: String, fieldName: String) = model(resourceName, fieldName) operator fun invoke(resourceName: String) = model(resourceName) fun get(resourceName: String, fieldName: String) = this(resourceName, fieldName)!! fun get(resourceName: String) = this(resourceName)!! }
apache-2.0
5da15c319d0177d76ddbe21c86bb0003
42
163
0.692241
3.942588
false
false
false
false
jeantuffier/reminder
app/src/main/java/fr/jeantuffier/reminder/free/home/presentation/HomeAdapter.kt
1
1052
package fr.jeantuffier.reminder.free.home.presentation import android.support.v7.widget.RecyclerView import android.view.ViewGroup import fr.jeantuffier.reminder.free.common.model.Task import fr.jeantuffier.reminder.free.home.presentation.delegate.RegularTaskDelegate class HomeAdapter(private val items: MutableList<Task>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val regularTaskDelegate = RegularTaskDelegate() override fun getItemCount() = items.size override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int) = regularTaskDelegate.createViewHolder(parent, viewType) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val task = items[position] regularTaskDelegate.bindViewHolder(holder, task) holder.itemView.tag = task.id } fun addItem(task: Task) = items.add(task) fun removeItem(position: Int) = items.removeAt(position) fun setItems(tasks: List<Task>) { items.clear() items.addAll(0, tasks) } }
mit
74c68771e0e423c7fde29d11e1176ca8
32.935484
107
0.744297
4.329218
false
false
false
false
allotria/intellij-community
community-guitests/testSrc/com/intellij/testGuiFramework/tests/community/CommunityProjectCreator.kt
4
5449
// 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.testGuiFramework.tests.community import com.intellij.ide.IdeBundle import com.intellij.ide.actions.newclass.CreateWithTemplatesDialogPanel import com.intellij.openapi.diagnostic.Logger import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.impl.* import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitProgressDialogUntilGone import com.intellij.testGuiFramework.util.Key.* import com.intellij.testGuiFramework.util.Modifier.CONTROL import com.intellij.testGuiFramework.util.Modifier.META import com.intellij.testGuiFramework.util.plus import com.intellij.testGuiFramework.util.step import com.intellij.testGuiFramework.utils.TestUtilsClass import com.intellij.testGuiFramework.utils.TestUtilsClassCompanion import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.WaitTimedOutError import org.junit.Assert import java.nio.file.Path import java.nio.file.Paths val GuiTestCase.CommunityProjectCreator by CommunityProjectCreator class CommunityProjectCreator(guiTestCase: GuiTestCase) : TestUtilsClass(guiTestCase) { companion object : TestUtilsClassCompanion<CommunityProjectCreator>({ it -> CommunityProjectCreator(it) }) private val LOG = Logger.getInstance(this.javaClass) private val defaultProjectName = "untitled" fun createCommandLineProject(projectName: String = defaultProjectName, needToOpenMainJava: Boolean = true) { with(guiTestCase) { welcomeFrame { actionLink("Create New Project").click() waitProgressDialogUntilGone(robot = robot(), progressTitle = "Loading Templates", timeoutToAppear = Timeouts.seconds02) dialog("New Project") { jList("Java").clickItem("Java") button("Next").click() val projectFromTemplateCheckbox = checkbox("Create project from template") projectFromTemplateCheckbox.click() //check that "Create project from template" has been clicked. GUI-80 if (!projectFromTemplateCheckbox.isSelected) projectFromTemplateCheckbox.click() Assert.assertTrue("Checkbox \"Create project from template\" should be selected!", projectFromTemplateCheckbox.isSelected) jList("Command Line App").clickItem("Command Line App") button("Next").click() typeText(projectName) checkFileAlreadyExistsDialog() //confirm overwriting already created project button("Finish").click() } } waitForFirstIndexing() if (needToOpenMainJava) openMainInCommandLineProject() } } private fun GuiTestCase.checkFileAlreadyExistsDialog() { try { val dialogFixture = dialog(IdeBundle.message("title.file.already.exists"), false, timeout = Timeouts.seconds01) dialogFixture.button("Yes").click() } catch (cle: ComponentLookupException) { /*do nothing here */ } } fun GuiTestCase.openMainInCommandLineProject() { ideFrame { projectView { path(project.name, "src", "com.company", "Main").doubleClick() waitForBackgroundTasksToFinish() } } } fun GuiTestCase.openFileInCommandLineProject(fileName: String) { ideFrame { projectView { path(project.name, "src", "com.company", fileName).doubleClick() waitForBackgroundTasksToFinish() } } } fun GuiTestCase.waitForFirstIndexing() { ideFrame { val secondToWaitIndexing = 10 try { waitForStartingIndexing(secondToWaitIndexing) //let's wait for 2 minutes until indexing bar will appeared } catch (timedOutError: WaitTimedOutError) { LOG.warn("Waiting for indexing has been exceeded $secondToWaitIndexing seconds") } waitForBackgroundTasksToFinish() } } fun createJavaClass(fileContent: String, fileName: String = "Test") { with(guiTestCase) { ideFrame { projectView { path(project.name, "src", "com.company").rightClick() } menu("New", "Java Class").click() step("Find CreateWithTemplatesDialogPanel to detect popup for a new class") { findComponentWithTimeout(null, CreateWithTemplatesDialogPanel::class.java, Timeouts.seconds02) typeText(fileName) shortcut(ENTER) } editor("$fileName.java") { shortcut(CONTROL + A, META + A) copyToClipboard(fileContent) shortcut(CONTROL + V, META + V) } } } } /** * @projectName of importing project should be locate in the current module testData/ */ fun importProject(projectName: String): Path { val projectDirUrl = this.javaClass.classLoader.getResource(projectName) return guiTestCase.guiTestRule.importProject(Paths.get(projectDirUrl.toURI())) } fun importCommandLineApp() { importProject("command-line-app") } /** * @fileName - name of file with extension stored in src/com.company/ */ fun importCommandLineAppAndOpenFile(fileName: String) { importCommandLineApp() guiTestCase.waitForFirstIndexing() guiTestCase.openFileInCommandLineProject(fileName) } fun importCommandLineAppAndOpenMain() { importCommandLineApp() guiTestCase.waitForFirstIndexing() guiTestCase.openMainInCommandLineProject() } }
apache-2.0
33ce114c8c1218aabbdc990f0709a847
35.817568
140
0.717012
4.865179
false
true
false
false
allotria/intellij-community
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/VirtualFileIndexTest.kt
3
7951
// 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.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl import com.intellij.workspaceModel.storage.entities.* import com.intellij.workspaceModel.storage.entities.ModifiableVFUEntity import com.intellij.workspaceModel.storage.entities.addNullableVFUEntity import com.intellij.workspaceModel.storage.entities.addVFU2Entity import com.intellij.workspaceModel.storage.entities.addVFUEntity import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.junit.Assert.* import org.junit.Before import org.junit.Test class VirtualFileIndexTest { private lateinit var virtualFileManager: VirtualFileUrlManager @Before fun setUp() { virtualFileManager = VirtualFileUrlManagerImpl() } @Test fun `add entity with not null vfu`() { val fileUrl = "/user/opt/app/a.txt" val builder = createEmptyBuilder() val entity = builder.addVFUEntity("hello", fileUrl, virtualFileManager) assertEquals(fileUrl, entity.fileProperty.url) assertEquals(entity.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entity.id).first()) } @Test fun `change virtual file url`() { val fileUrl = "/user/opt/app/a.txt" val fileUrl2 = "/user/opt/app/b.txt" val fileUrl3 = "/user/opt/app/c.txt" val builder = createEmptyBuilder() val entity = builder.addVFUEntity("hello", fileUrl, virtualFileManager) assertEquals(fileUrl, entity.fileProperty.url) val modifiedEntity = builder.modifyEntity(ModifiableVFUEntity::class.java, entity) { this.fileProperty = virtualFileManager.fromUrl(fileUrl2) this.fileProperty = virtualFileManager.fromUrl(fileUrl3) } assertEquals(fileUrl3, modifiedEntity.fileProperty.url) val virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles(modifiedEntity.id) assertEquals(1, virtualFiles.size) assertEquals(modifiedEntity.fileProperty, virtualFiles.first()) } @Test fun `add entity with nullable vfu`() { val builder = createEmptyBuilder() val entity = builder.addNullableVFUEntity("hello", null, virtualFileManager) assertNull(entity.fileProperty) assertTrue(builder.indexes.virtualFileIndex.getVirtualFiles(entity.id).isEmpty()) } @Test fun `add entity with two properties`() { val fileUrl = "/user/opt/app/a.txt" val secondUrl = "/user/opt/app/b.txt" val builder = createEmptyBuilder() val entity = builder.addVFU2Entity("hello", fileUrl, secondUrl, virtualFileManager) assertEquals(fileUrl, entity.fileProperty.url) assertEquals(secondUrl, entity.secondFileProperty.url) val virtualFiles = builder.indexes.virtualFileIndex.getVirtualFiles(entity.id) assertEquals(2, virtualFiles.size) assertTrue(virtualFiles.contains(entity.fileProperty)) assertTrue(virtualFiles.contains(entity.secondFileProperty)) } @Test fun `add entity with vfu list`() { val fileUrlList = listOf("/user/a.txt", "/user/opt/app/a.txt", "/user/opt/app/b.txt") val builder = createEmptyBuilder() val entity = builder.addListVFUEntity("hello", fileUrlList, virtualFileManager) assertEquals(fileUrlList, entity.fileProperty.map { it.url }.sorted()) assertEquals(fileUrlList.size, builder.indexes.virtualFileIndex.getVirtualFiles(entity.id).size) } @Test fun `add entity to diff`() { val fileUrlA = "/user/opt/app/a.txt" val fileUrlB = "/user/opt/app/b.txt" val builder = createEmptyBuilder() val entityA = builder.addVFUEntity("bar", fileUrlA, virtualFileManager) assertEquals(fileUrlA, entityA.fileProperty.url) assertEquals(entityA.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) val diff = createBuilderFrom(builder.toStorage()) val entityB = diff.addVFUEntity("foo", fileUrlB, virtualFileManager) assertEquals(fileUrlB, entityB.fileProperty.url) assertEquals(entityA.fileProperty, diff.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) assertEquals(entityB.fileProperty, diff.indexes.virtualFileIndex.getVirtualFiles(entityB.id).first()) assertTrue(builder.indexes.virtualFileIndex.getVirtualFiles(entityB.id).isEmpty()) builder.addDiff(diff) assertEquals(entityA.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) assertEquals(entityB.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityB.id).first()) } @Test fun `remove entity from diff`() { val fileUrlA = "/user/opt/app/a.txt" val fileUrlB = "/user/opt/app/b.txt" val builder = createEmptyBuilder() val entityA = builder.addVFUEntity("bar", fileUrlA, virtualFileManager) val entityB = builder.addVFUEntity("foo", fileUrlB, virtualFileManager) assertEquals(entityA.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) assertEquals(entityB.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityB.id).first()) val diff = createBuilderFrom(builder.toStorage()) assertEquals(entityA.fileProperty, diff.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) assertEquals(entityB.fileProperty, diff.indexes.virtualFileIndex.getVirtualFiles(entityB.id).first()) diff.removeEntity(entityB) assertEquals(entityA.fileProperty, diff.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) assertTrue(diff.indexes.virtualFileIndex.getVirtualFiles(entityB.id).isEmpty()) assertEquals(entityB.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityB.id).first()) builder.addDiff(diff) assertEquals(entityA.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) assertTrue(builder.indexes.virtualFileIndex.getVirtualFiles(entityB.id).isEmpty()) } @Test fun `update entity in diff`() { val fileUrlA = "/user/opt/app/a.txt" val fileUrlB = "/user/opt/app/b.txt" val fileUrlC = "/user/opt/app/c.txt" val builder = createEmptyBuilder() val entityA = builder.addVFUEntity("bar", fileUrlA, virtualFileManager) var entityB = builder.addVFUEntity("foo", fileUrlB, virtualFileManager) assertEquals(entityA.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) assertEquals(entityB.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityB.id).first()) val diff = createBuilderFrom(builder.toStorage()) assertEquals(entityA.fileProperty, diff.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) var virtualFile = diff.indexes.virtualFileIndex.getVirtualFiles(entityB.id) assertNotNull(virtualFile) assertEquals(fileUrlB, entityB.fileProperty.url) assertEquals(entityB.fileProperty, virtualFile.first()) entityB = diff.modifyEntity(ModifiableVFUEntity::class.java, entityB) { fileProperty = virtualFileManager.fromUrl(fileUrlC) } assertEquals(entityA.fileProperty, diff.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) virtualFile = diff.indexes.virtualFileIndex.getVirtualFiles(entityB.id) assertNotNull(virtualFile) assertEquals(fileUrlC, entityB.fileProperty.url) assertEquals(fileUrlC, virtualFile.first().url) assertNotEquals(fileUrlB, entityB.fileProperty.url) assertEquals(entityB.fileProperty, virtualFile.first()) builder.addDiff(diff) assertEquals(entityA.fileProperty, builder.indexes.virtualFileIndex.getVirtualFiles(entityA.id).first()) virtualFile = builder.indexes.virtualFileIndex.getVirtualFiles(entityB.id) assertNotNull(virtualFile) assertEquals(fileUrlC, entityB.fileProperty.url) assertEquals(fileUrlC, virtualFile.first().url) assertNotEquals(fileUrlB, entityB.fileProperty.url) assertEquals(entityB.fileProperty, virtualFile.first()) } }
apache-2.0
7d8419f833d28bca090dbc137d03259e
46.903614
140
0.770218
4.33061
false
true
false
false
GPortas/PaymentKeyboards
payment-keyboards/src/main/java/com/gportas/paymentkeyboards/managers/IKeyboardManager.kt
1
1365
package com.gportas.paymentkeyboards.managers import android.support.v7.app.AppCompatActivity import com.gportas.paymentkeyboards.R import com.gportas.paymentkeyboards.view.BaseKeyboardFragment /** * Created by guillermo on 16/10/17. */ interface IKeyboardManager { var isKeyboardOpened: Boolean fun openKeyboardWithSlideUpAnimation(activity: AppCompatActivity, keyboard: BaseKeyboardFragment, frameLayoutResId: Int) { isKeyboardOpened = true val fm = activity.supportFragmentManager val transaction = fm.beginTransaction() transaction.setCustomAnimations(R.anim.keyboard_slide_in_up, R.anim.keyboard_slide_out_up) transaction.replace(frameLayoutResId, keyboard).commit() } fun openKeyboard(activity: AppCompatActivity, keyboard: BaseKeyboardFragment, frameLayoutResId: Int) { isKeyboardOpened = true val fm = activity.supportFragmentManager val transaction = fm.beginTransaction() transaction.replace(frameLayoutResId, keyboard).commit() } fun hideKeyboard(activity: AppCompatActivity, frameLayoutResId: Int){ if(!isKeyboardOpened) return val fm = activity.supportFragmentManager val transaction = fm.beginTransaction() transaction.remove(fm.findFragmentById(frameLayoutResId)).commit() isKeyboardOpened = false } }
mit
6be9daefc5b9fd445f3f17309e310dc3
35.918919
126
0.744322
4.658703
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.kt
1
83273
// 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.openapi.wm.impl import com.intellij.BundleBase import com.intellij.DynamicBundle import com.intellij.diagnostic.LoadingState import com.intellij.diagnostic.runActivity import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.ide.IdeEventQueue import com.intellij.ide.UiActivity import com.intellij.ide.UiActivityMonitor import com.intellij.ide.actions.ActivateToolWindowAction import com.intellij.ide.actions.MaximizeActiveDialogAction import com.intellij.ide.plugins.PluginManagerCore import com.intellij.internal.statistic.collectors.fus.actions.persistence.ToolWindowCollector import com.intellij.notification.impl.NotificationsManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.MnemonicHelper import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.impl.ExtensionPointImpl import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.impl.EditorsSplitters import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapManagerListener import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.* import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.ui.FrameWrapper import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.Splitter import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.* import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.* import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.ex.ToolWindowManagerEx import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.ui.BalloonImpl import com.intellij.ui.ComponentUtil import com.intellij.ui.GuiUtils import com.intellij.ui.awt.RelativePoint import com.intellij.util.BitUtil import com.intellij.util.EventDispatcher import com.intellij.util.SingleAlarm import com.intellij.util.SystemProperties import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.addIfNotNull import com.intellij.util.ui.* import org.intellij.lang.annotations.JdkConstants import org.jdom.Element import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.awt.* import java.awt.event.* import java.beans.PropertyChangeListener import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference import java.util.function.Predicate import java.util.function.Supplier import javax.swing.* import javax.swing.event.HyperlinkEvent import javax.swing.event.HyperlinkListener private val LOG = logger<ToolWindowManagerImpl>() @State( name = "ToolWindowManager", defaultStateAsResource = true, storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)] ) open class ToolWindowManagerImpl(val project: Project) : ToolWindowManagerEx(), PersistentStateComponent<Element?> { private val dispatcher = EventDispatcher.create(ToolWindowManagerListener::class.java) private var layout = DesktopLayout() private val idToEntry: MutableMap<String, ToolWindowEntry> = HashMap() private val activeStack = ActiveStack() private val sideStack = SideStack() private var toolWindowPane: ToolWindowsPane? = null private var frame: ProjectFrameHelper? = null private var layoutToRestoreLater: DesktopLayout? = null private var currentState = KeyState.WAITING private var waiterForSecondPress: SingleAlarm? = null private val recentToolWindows: MutableList<String> = LinkedList<String>() private val pendingSetLayoutTask = AtomicReference<Runnable?>() fun isToolWindowRegistered(id: String) = idToEntry.containsKey(id) init { if (project.isDefault) { waiterForSecondPress = null } else { runActivity("toolwindow factory class preloading") { processDescriptors { bean, pluginDescriptor -> bean.getToolWindowFactory(pluginDescriptor) } } } } companion object { /** * Setting this [client property][JComponent.putClientProperty] allows to specify 'effective' parent for a component which will be used * to find a tool window to which component belongs (if any). This can prevent tool windows in non-default view modes (e.g. 'Undock') * to close when focus is transferred to a component not in tool window hierarchy, but logically belonging to it (e.g. when component * is added to the window's layered pane). * * @see ComponentUtil.putClientProperty */ @JvmField val PARENT_COMPONENT: Key<JComponent> = Key.create("tool.window.parent.component") @JvmStatic @ApiStatus.Internal fun getRegisteredMutableInfoOrLogError(decorator: InternalDecoratorImpl): WindowInfoImpl { val toolWindow = decorator.toolWindow return toolWindow.toolWindowManager.getRegisteredMutableInfoOrLogError(toolWindow.id) } } internal fun getFrame() = frame private fun runPendingLayoutTask() { pendingSetLayoutTask.getAndSet(null)?.run() } @Service private class ToolWindowManagerAppLevelHelper { companion object { private fun handleFocusEvent(event: FocusEvent) { if (event.id == FocusEvent.FOCUS_LOST) { if (event.oppositeComponent == null || event.isTemporary) { return } val project = IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project ?: return if (project.isDisposed || project.isDefault) { return } val toolWindowManager = getInstance(project) as ToolWindowManagerImpl val toolWindowId = toolWindowManager.activeToolWindowId ?: return val activeEntry = toolWindowManager.idToEntry[toolWindowId] ?: return val windowInfo = activeEntry.readOnlyWindowInfo // just removed if (!windowInfo.isVisible) { return } if (!(windowInfo.isAutoHide || windowInfo.type == ToolWindowType.SLIDING)) { return } // let's check that it is a toolwindow who loses the focus if (isInActiveToolWindow(event.source, activeEntry.toolWindow) && !isInActiveToolWindow(event.oppositeComponent, activeEntry.toolWindow)) { // a toolwindow lost focus val focusGoesToPopup = JBPopupFactory.getInstance().getParentBalloonFor(event.oppositeComponent) != null if (!focusGoesToPopup) { val info = toolWindowManager.getRegisteredMutableInfoOrLogError(toolWindowId) toolWindowManager.doDeactivateToolWindow(info, activeEntry) } } } else if (event.id == FocusEvent.FOCUS_GAINED) { val component = event.component ?: return processOpenedProjects { project -> for (composite in FileEditorManagerEx.getInstanceEx(project).splitters.editorComposites) { if (composite.editors.any { SwingUtilities.isDescendingFrom(component, it.component) }) { (getInstance(project) as ToolWindowManagerImpl).activeStack.clear() } } } } } private inline fun process(processor: (manager: ToolWindowManagerImpl) -> Unit) { processOpenedProjects { project -> processor(getInstance(project) as ToolWindowManagerImpl) } } class MyListener : AWTEventListener { override fun eventDispatched(event: AWTEvent?) { if (event is FocusEvent) { handleFocusEvent(event) } else if (event is WindowEvent && event.getID() == WindowEvent.WINDOW_LOST_FOCUS) { process { manager -> val frame = event.getSource() as? JFrame if (frame === manager.frame?.frame) { manager.resetHoldState() } } } } } } init { val awtFocusListener = MyListener() Toolkit.getDefaultToolkit().addAWTEventListener(awtFocusListener, AWTEvent.FOCUS_EVENT_MASK or AWTEvent.WINDOW_FOCUS_EVENT_MASK) val updateHeadersAlarm = SingleAlarm(Runnable { processOpenedProjects { project -> (getInstance(project) as ToolWindowManagerImpl).updateToolWindowHeaders() } }, 50, ApplicationManager.getApplication()) val focusListener = PropertyChangeListener { updateHeadersAlarm.cancelAndRequest() } KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", focusListener) Disposer.register(ApplicationManager.getApplication()) { KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", focusListener) } val connection = ApplicationManager.getApplication().messageBus.connect() connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosingBeforeSave(project: Project) { val manager = (project.serviceIfCreated<ToolWindowManager>() as ToolWindowManagerImpl?) ?: return for (entry in manager.idToEntry.values) { manager.saveFloatingOrWindowedState(entry, manager.layout.getInfo(entry.id) ?: continue) } } override fun projectClosed(project: Project) { (project.serviceIfCreated<ToolWindowManager>() as ToolWindowManagerImpl?)?.projectClosed() } }) connection.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener { override fun activeKeymapChanged(keymap: Keymap?) { process { manager -> manager.idToEntry.values.forEach { it.stripeButton.updatePresentation() } } } }) connection.subscribe(AnActionListener.TOPIC, object : AnActionListener { override fun beforeActionPerformed(action: AnAction, dataContext: DataContext, event: AnActionEvent) { process { manager -> if (manager.currentState != KeyState.HOLD) { manager.resetHoldState() } } } }) IdeEventQueue.getInstance().addDispatcher(IdeEventQueue.EventDispatcher { event -> if (event is KeyEvent) { process { manager -> manager.dispatchKeyEvent(event) } } false }, ApplicationManager.getApplication()) } } private fun updateToolWindowHeaders() { focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) { for (entry in idToEntry.values) { if (entry.readOnlyWindowInfo.isVisible) { entry.toolWindow.decoratorComponent?.repaint() } } }) } private fun dispatchKeyEvent(e: KeyEvent): Boolean { if ((e.keyCode != KeyEvent.VK_CONTROL) && ( e.keyCode != KeyEvent.VK_ALT) && (e.keyCode != KeyEvent.VK_SHIFT) && (e.keyCode != KeyEvent.VK_META)) { if (e.modifiers == 0) { resetHoldState() } return false } if (e.id != KeyEvent.KEY_PRESSED && e.id != KeyEvent.KEY_RELEASED) { return false } val parent = UIUtil.findUltimateParent(e.component) if (parent is IdeFrame) { if ((parent as IdeFrame).project !== project) { resetHoldState() return false } } val vks = activateToolWindowVKsMask if (vks == 0) { resetHoldState() return false } val mouseMask = InputEvent.BUTTON1_DOWN_MASK or InputEvent.BUTTON2_DOWN_MASK or InputEvent.BUTTON3_DOWN_MASK if (BitUtil.isSet(vks, keyCodeToInputMask(e.keyCode)) && (e.modifiersEx and mouseMask) == 0) { val pressed = e.id == KeyEvent.KEY_PRESSED val modifiers = e.modifiers if (areAllModifiersPressed(modifiers, vks) || !pressed) { processState(pressed) } else { resetHoldState() } } return false } private fun resetHoldState() { currentState = KeyState.WAITING processHoldState() } private fun processState(pressed: Boolean) { if (pressed) { if (currentState == KeyState.WAITING) { currentState = KeyState.PRESSED } else if (currentState == KeyState.RELEASED) { currentState = KeyState.HOLD processHoldState() } } else { if (currentState == KeyState.PRESSED) { currentState = KeyState.RELEASED waiterForSecondPress?.cancelAndRequest() } else { resetHoldState() } } } private fun processHoldState() { toolWindowPane?.setStripesOverlayed(currentState == KeyState.HOLD) } @ApiStatus.Internal override fun init(frameHelper: ProjectFrameHelper): ToolWindowsPane { toolWindowPane?.let { return it } // manager is used in light tests (light project is never disposed), so, earlyDisposable must be used val disposable = (project as ProjectEx).earlyDisposable waiterForSecondPress = SingleAlarm(task = Runnable { if (currentState != KeyState.HOLD) { resetHoldState() } }, delay = SystemProperties.getIntProperty("actionSystem.keyGestureDblClickTime", 650), parentDisposable = disposable) val connection = project.messageBus.connect(disposable) connection.subscribe(ToolWindowManagerListener.TOPIC, dispatcher.multicaster) connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { override fun fileClosed(source: FileEditorManager, file: VirtualFile) { focusManager.doWhenFocusSettlesDown(ExpirableRunnable.forProject(project) { if (!FileEditorManager.getInstance(project).hasOpenFiles()) { focusToolWindowByDefault() } }) } }) frame = frameHelper val rootPane = frameHelper.rootPane!! val toolWindowPane = rootPane.toolWindowPane toolWindowPane.initDocumentComponent(project) this.toolWindowPane = toolWindowPane return toolWindowPane } // must be executed in EDT private fun beforeProjectOpenedTask( tasks: List<RegisterToolWindowTask>, app: Application, ) = Runnable { frame!!.rootPane!!.updateToolbar() runPendingLayoutTask() // FacetDependentToolWindowManager - strictly speaking, computeExtraToolWindowBeans should be executed not in EDT, but for now it is not safe because: // 1. read action is required to read facet list (might cause a deadlock) // 2. delay between collection and adding ProjectWideFacetListener (should we introduce a new method in RegisterToolWindowTaskProvider to add listeners?) val list = ArrayList(tasks) + (app.extensionArea as ExtensionsAreaImpl) .getExtensionPoint<RegisterToolWindowTaskProvider>("com.intellij.registerToolWindowTaskProvider") .computeExtraToolWindowBeans() if (toolWindowPane == null) { if (!app.isUnitTestMode) { LOG.error("ProjectFrameAllocator is not used - use ProjectManager.openProject to open project in a correct way") } val toolWindowsPane = init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project)) // cannot be executed because added layered pane is not yet validated and size is not known app.invokeLater(Runnable { runPendingLayoutTask() initToolWindows(list, toolWindowsPane) }, project.disposed) } else { initToolWindows(list, toolWindowPane!!) } registerEPListeners() } private fun computeToolWindowBeans(): List<RegisterToolWindowTask> { val list = mutableListOf<RegisterToolWindowTask>() processDescriptors { bean, pluginDescriptor -> val condition = bean.getCondition(pluginDescriptor) if (condition == null || condition.value(project)) { list.addIfNotNull(beanToTask(bean, pluginDescriptor)) } } return list } private fun ExtensionPointImpl<RegisterToolWindowTaskProvider>.computeExtraToolWindowBeans(): List<RegisterToolWindowTask> { val list = mutableListOf<RegisterToolWindowTask>() this.processImplementations(true) { supplier, epPluginDescriptor -> if (epPluginDescriptor.pluginId == PluginManagerCore.CORE_ID) for (bean in supplier.get().getTasks(project)) { list.addIfNotNull(beanToTask(bean)) } else { LOG.error("Only bundled plugin can define registerToolWindowTaskProvider: $epPluginDescriptor") } } return list } private fun beanToTask( bean: ToolWindowEP, pluginDescriptor: PluginDescriptor = bean.pluginDescriptor, ): RegisterToolWindowTask? { val factory = bean.getToolWindowFactory(pluginDescriptor) return if (factory != null && factory.isApplicable(project)) beanToTask(bean, pluginDescriptor, factory) else null } private fun beanToTask( bean: ToolWindowEP, pluginDescriptor: PluginDescriptor, factory: ToolWindowFactory, ) = RegisterToolWindowTask( id = bean.id, icon = findIconFromBean(bean, factory, pluginDescriptor), anchor = getToolWindowAnchor(factory, bean), sideTool = bean.secondary || (@Suppress("DEPRECATION") bean.side), canCloseContent = bean.canCloseContents, canWorkInDumbMode = DumbService.isDumbAware(factory), shouldBeAvailable = factory.shouldBeAvailable(project), contentFactory = factory, stripeTitle = getStripeTitleSupplier(bean.id, pluginDescriptor), ) // This method cannot be inlined because of magic Kotlin compilation bug: it 'captured' "list" local value and cause class-loader leak // See IDEA-CR-61904 private fun registerEPListeners() { ToolWindowEP.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<ToolWindowEP> { override fun extensionAdded(extension: ToolWindowEP, pluginDescriptor: PluginDescriptor) { initToolWindow(extension, pluginDescriptor) } override fun extensionRemoved(extension: ToolWindowEP, pluginDescriptor: PluginDescriptor) { doUnregisterToolWindow(extension.id) } }, project) } private fun getToolWindowAnchor(factory: ToolWindowFactory?, bean: ToolWindowEP) = (factory as? ToolWindowFactoryEx)?.anchor ?: ToolWindowAnchor.fromText(bean.anchor ?: ToolWindowAnchor.LEFT.toString()) private fun initToolWindows(list: List<RegisterToolWindowTask>, toolWindowsPane: ToolWindowsPane) { runActivity("toolwindow creating") { val entries = ArrayList<String>(list.size) for (task in list) { try { entries.add(doRegisterToolWindow(task, toolWindowsPane).id) } catch (e: ProcessCanceledException) { throw e } catch (t: Throwable) { LOG.error("Cannot init toolwindow ${task.contentFactory}", t) } } project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(entries, this) toolWindowPane!!.revalidateNotEmptyStripes() } toolWindowsPane.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, Iterable { idToEntry.values.asSequence().mapNotNull { val component = it.toolWindow.decoratorComponent if (component != null && component.parent == null) component else null }.iterator() }) service<ToolWindowManagerAppLevelHelper>() } override fun initToolWindow(bean: ToolWindowEP) { initToolWindow(bean, bean.pluginDescriptor) } private fun initToolWindow(bean: ToolWindowEP, pluginDescriptor: PluginDescriptor) { val condition = bean.getCondition(pluginDescriptor) if (condition != null && !condition.value(project)) { return } val factory = bean.getToolWindowFactory(bean.pluginDescriptor) ?: return if (!factory.isApplicable(project)) { return } val toolWindowPane = toolWindowPane ?: init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project)) val anchor = getToolWindowAnchor(factory, bean) @Suppress("DEPRECATION") val sideTool = bean.secondary || bean.side val entry = doRegisterToolWindow(RegisterToolWindowTask( id = bean.id, icon = findIconFromBean(bean, factory, pluginDescriptor), anchor = anchor, sideTool = sideTool, canCloseContent = bean.canCloseContents, canWorkInDumbMode = DumbService.isDumbAware(factory), shouldBeAvailable = factory.shouldBeAvailable(project), contentFactory = factory, stripeTitle = getStripeTitleSupplier(bean.id, pluginDescriptor) ), toolWindowPane) project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(listOf(entry.id), this) toolWindowPane.getStripeFor(anchor).revalidate() toolWindowPane.validate() toolWindowPane.repaint() } fun projectClosed() { if (frame == null) { return } frame!!.releaseFrame() toolWindowPane!!.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, null) // hide all tool windows - frame maybe reused for another project for (entry in idToEntry.values) { try { removeDecoratorWithoutUpdatingState(entry, layout.getInfo(entry.id) ?: continue, dirtyMode = true) } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error(e) } finally { Disposer.dispose(entry.disposable) } } toolWindowPane!!.reset() frame = null } override fun addToolWindowManagerListener(listener: ToolWindowManagerListener) { dispatcher.addListener(listener) } override fun addToolWindowManagerListener(listener: ToolWindowManagerListener, parentDisposable: Disposable) { project.messageBus.connect(parentDisposable).subscribe(ToolWindowManagerListener.TOPIC, listener) } override fun removeToolWindowManagerListener(listener: ToolWindowManagerListener) { dispatcher.removeListener(listener) } override fun activateEditorComponent() { if (!EditorsSplitters.focusDefaultComponentInSplittersIfPresent(project)) { // see note about requestFocus in focusDefaultComponentInSplittersIfPresent frame?.rootPane?.requestFocus() } } open fun activateToolWindow(id: String, runnable: Runnable?, autoFocusContents: Boolean, source: ToolWindowEventSource? = null) { ApplicationManager.getApplication().assertIsDispatchThread() val activity = UiActivity.Focus("toolWindow:$id") UiActivityMonitor.getInstance().addActivity(project, activity, ModalityState.NON_MODAL) activateToolWindow(idToEntry[id]!!, getRegisteredMutableInfoOrLogError(id), autoFocusContents, source) ApplicationManager.getApplication().invokeLater(Runnable { runnable?.run() UiActivityMonitor.getInstance().removeActivity(project, activity) }, project.disposed) } private fun activateToolWindow(entry: ToolWindowEntry, info: WindowInfoImpl, autoFocusContents: Boolean = true, source: ToolWindowEventSource? = null) { LOG.debug { "activateToolWindow($entry)" } if (source != null) { ToolWindowCollector.getInstance().recordActivation(project, entry.id, info, source) } recentToolWindows.remove(entry.id) recentToolWindows.add(0, entry.id) if (!entry.toolWindow.isAvailable) { // Tool window can be "logically" active but not focused. For example, // when the user switched to another application. So we just need to bring // tool window's window to front. if (autoFocusContents && !entry.toolWindow.hasFocus) { entry.toolWindow.requestFocusInToolWindow() } return } if (!entry.readOnlyWindowInfo.isVisible) { showToolWindowImpl(entry, info, dirtyMode = false, source = source) } if (autoFocusContents && ApplicationManager.getApplication().isActive) { entry.toolWindow.requestFocusInToolWindow() } else { activeStack.push(entry) } fireStateChanged() } fun getRecentToolWindows() = ArrayList(recentToolWindows) internal fun updateToolWindow(toolWindow: ToolWindowImpl, component: Component) { toolWindow.setFocusedComponent(component) if (toolWindow.isAvailable && !toolWindow.isActive) { activateToolWindow(toolWindow.id, null, autoFocusContents = true) } activeStack.push(idToEntry[toolWindow.id] ?: return) } // mutate operation must use info from layout and not from decorator private fun getRegisteredMutableInfoOrLogError(id: String): WindowInfoImpl { val info = layout.getInfo(id) ?: throw IllegalThreadStateException("window with id=\"$id\" is unknown") if (!isToolWindowRegistered(id)) { LOG.error("window with id=\"$id\" isn't registered") } return info } private fun doDeactivateToolWindow(info: WindowInfoImpl, entry: ToolWindowEntry, dirtyMode: Boolean = false, source: ToolWindowEventSource? = null) { LOG.debug { "enter: deactivateToolWindowImpl(${info.id})" } setHiddenState(info, entry, source) updateStateAndRemoveDecorator(info, entry, dirtyMode = dirtyMode) entry.applyWindowInfo(info.copy()) } private fun setHiddenState(info: WindowInfoImpl, entry: ToolWindowEntry, source: ToolWindowEventSource?) { ToolWindowCollector.getInstance().recordHidden(project, info, source) info.isActiveOnStart = false info.isVisible = false activeStack.remove(entry, false) } override val toolWindowIds: Array<String> get() = idToEntry.keys.toTypedArray() override val toolWindowIdSet: Set<String> get() = HashSet(idToEntry.keys) override val activeToolWindowId: String? get() { EDT.assertIsEdt() val frame = frame?.frame ?: return null if (frame.isActive) { val focusOwner = focusManager.getLastFocusedFor(frame) ?: return null var parent: Component? = focusOwner while (parent != null) { if (parent is InternalDecoratorImpl) { return parent.toolWindow.id } parent = parent.parent } } else { // let's check floating and windowed for (entry in idToEntry.values) { if (entry.floatingDecorator?.isActive == true || entry.windowedDecorator?.isActive == true) { return entry.id } } } return null } override val lastActiveToolWindowId: String? get() = getLastActiveToolWindow(condition = null)?.id override fun getLastActiveToolWindow(condition: Predicate<in JComponent>?): ToolWindow? { EDT.assertIsEdt() for (i in 0 until activeStack.persistentSize) { val toolWindow = activeStack.peekPersistent(i).toolWindow if (toolWindow.isAvailable && (condition == null || condition.test(toolWindow.component))) { return toolWindow } } return null } /** * @return floating decorator for the tool window with specified `ID`. */ private fun getFloatingDecorator(id: String) = idToEntry[id]?.floatingDecorator /** * @return windowed decorator for the tool window with specified `ID`. */ private fun getWindowedDecorator(id: String) = idToEntry[id]?.windowedDecorator /** * @return tool button for the window with specified `ID`. */ @TestOnly fun getStripeButton(id: String) = idToEntry[id]!!.stripeButton override fun getIdsOn(anchor: ToolWindowAnchor) = getVisibleToolWindowsOn(anchor).map { it.id }.toList() @ApiStatus.Internal fun getToolWindowsOn(anchor: ToolWindowAnchor, excludedId: String): List<ToolWindowEx> { return getVisibleToolWindowsOn(anchor) .filter { it.id != excludedId } .map { it.toolWindow } .toList() } @ApiStatus.Internal fun getDockedInfoAt(anchor: ToolWindowAnchor?, side: Boolean): WindowInfo? { for (entry in idToEntry.values) { val info = entry.readOnlyWindowInfo if (info.isVisible && info.isDocked && info.anchor == anchor && side == info.isSplit) { return info } } return null } override fun getLocationIcon(id: String, fallbackIcon: Icon): Icon { val info = layout.getInfo(id) ?: return fallbackIcon val type = info.type if (type == ToolWindowType.FLOATING || type == ToolWindowType.WINDOWED) { return AllIcons.Actions.MoveToWindow } val anchor = info.anchor val splitMode = info.isSplit return when (anchor) { ToolWindowAnchor.BOTTOM -> { if (splitMode) AllIcons.Actions.MoveToBottomRight else AllIcons.Actions.MoveToBottomLeft } ToolWindowAnchor.LEFT -> { if (splitMode) AllIcons.Actions.MoveToLeftBottom else AllIcons.Actions.MoveToLeftTop } ToolWindowAnchor.RIGHT -> { if (splitMode) AllIcons.Actions.MoveToRightBottom else AllIcons.Actions.MoveToRightTop } ToolWindowAnchor.TOP -> { if (splitMode) AllIcons.Actions.MoveToTopRight else AllIcons.Actions.MoveToTopLeft } else -> fallbackIcon } } private fun getVisibleToolWindowsOn(anchor: ToolWindowAnchor): Sequence<ToolWindowEntry> { return idToEntry.values .asSequence() .filter { it.readOnlyWindowInfo.anchor == anchor && it.toolWindow.isAvailable } } // cannot be ToolWindowEx because of backward compatibility override fun getToolWindow(id: String?): ToolWindow? { return idToEntry[id ?: return null]?.toolWindow } open fun showToolWindow(id: String) { LOG.debug { "enter: showToolWindow($id)" } EDT.assertIsEdt() val info = layout.getInfo(id) ?: throw IllegalThreadStateException("window with id=\"$id\" is unknown") val entry = idToEntry[id]!! if (entry.readOnlyWindowInfo.isVisible) { LOG.assertTrue(entry.toolWindow.getComponentIfInitialized() != null) return } if (showToolWindowImpl(entry, info, dirtyMode = false)) { checkInvariants("id: $id") fireStateChanged() } } internal fun removeFromSideBar(id: String, source: ToolWindowEventSource?) { val info = getRegisteredMutableInfoOrLogError(id) if (!info.isShowStripeButton) { return } val entry = idToEntry[info.id!!]!! info.isShowStripeButton = false setHiddenState(info, entry, source) updateStateAndRemoveDecorator(info, entry, dirtyMode = false) entry.applyWindowInfo(info.copy()) if (Registry.`is`("ide.new.stripes.ui")) { toolWindowPane?.onStripeButtonRemoved(project, entry.toolWindow) } fireStateChanged() } override fun hideToolWindow(id: String, hideSide: Boolean) { hideToolWindow(id, hideSide, moveFocus = true) } open fun hideToolWindow(id: String, hideSide: Boolean, moveFocus: Boolean, source: ToolWindowEventSource? = null) { EDT.assertIsEdt() val entry = idToEntry[id]!! if (!entry.readOnlyWindowInfo.isVisible) { return } val info = getRegisteredMutableInfoOrLogError(id) val moveFocusAfter = moveFocus && entry.toolWindow.isActive doHide(entry, info, dirtyMode = false, hideSide = hideSide, source = source) fireStateChanged() if (moveFocusAfter) { activateEditorComponent() } } private fun doHide(entry: ToolWindowEntry, info: WindowInfoImpl, dirtyMode: Boolean, hideSide: Boolean = false, source: ToolWindowEventSource? = null) { // hide and deactivate doDeactivateToolWindow(info, entry, dirtyMode = dirtyMode, source = source) if (hideSide && info.type != ToolWindowType.FLOATING && info.type != ToolWindowType.WINDOWED) { for (each in getVisibleToolWindowsOn(info.anchor)) { activeStack.remove(each, false) } if (isStackEnabled) { while (!sideStack.isEmpty(info.anchor)) { sideStack.pop(info.anchor) } } for (otherEntry in idToEntry.values) { val otherInfo = layout.getInfo(otherEntry.id) ?: continue if (otherInfo.isVisible && otherInfo.anchor == info.anchor) { doDeactivateToolWindow(otherInfo, otherEntry, dirtyMode = dirtyMode, source = ToolWindowEventSource.HideSide) } } } else { // first of all we have to find tool window that was located at the same side and was hidden if (isStackEnabled) { var info2: WindowInfoImpl? = null while (!sideStack.isEmpty(info.anchor)) { val storedInfo = sideStack.pop(info.anchor) if (storedInfo.isSplit != info.isSplit) { continue } val currentInfo = getRegisteredMutableInfoOrLogError(storedInfo.id!!) // SideStack contains copies of real WindowInfos. It means that // these stored infos can be invalid. The following loop removes invalid WindowInfos. if (storedInfo.anchor == currentInfo.anchor && storedInfo.type == currentInfo.type && storedInfo.isAutoHide == currentInfo.isAutoHide) { info2 = storedInfo break } } if (info2 != null) { val entry2 = idToEntry[info2.id!!]!! if (!entry2.readOnlyWindowInfo.isVisible) { showToolWindowImpl(entry2, info2, dirtyMode = dirtyMode) } } } activeStack.remove(entry, false) } } /** * @param dirtyMode if `true` then all UI operations are performed in dirty mode. */ private fun showToolWindowImpl(entry: ToolWindowEntry, toBeShownInfo: WindowInfoImpl, dirtyMode: Boolean, source: ToolWindowEventSource? = null): Boolean { if (!entry.toolWindow.isAvailable) { return false } ToolWindowCollector.getInstance().recordShown(project, source, toBeShownInfo) toBeShownInfo.isVisible = true toBeShownInfo.isShowStripeButton = true val snapshotInfo = toBeShownInfo.copy() entry.applyWindowInfo(snapshotInfo) doShowWindow(entry, snapshotInfo, dirtyMode) if (entry.readOnlyWindowInfo.type == ToolWindowType.WINDOWED && entry.toolWindow.getComponentIfInitialized() != null) { UIUtil.toFront(ComponentUtil.getWindow(entry.toolWindow.component)) } return true } private fun doShowWindow(entry: ToolWindowEntry, info: WindowInfo, dirtyMode: Boolean) { if (entry.readOnlyWindowInfo.type == ToolWindowType.FLOATING) { addFloatingDecorator(entry, info) } else if (entry.readOnlyWindowInfo.type == ToolWindowType.WINDOWED) { addWindowedDecorator(entry, info) } else { // docked and sliding windows // If there is tool window on the same side then we have to hide it, i.e. // clear place for tool window to be shown. // // We store WindowInfo of hidden tool window in the SideStack (if the tool window // is docked and not auto-hide one). Therefore it's possible to restore the // hidden tool window when showing tool window will be closed. for (otherEntry in idToEntry.values) { if (entry.id == otherEntry.id) { continue } val otherInfo = otherEntry.readOnlyWindowInfo if (otherInfo.isVisible && otherInfo.type == info.type && otherInfo.anchor == info.anchor && otherInfo.isSplit == info.isSplit) { val otherLayoutInto = layout.getInfo(otherEntry.id)!! // hide and deactivate tool window setHiddenState(otherLayoutInto, otherEntry, ToolWindowEventSource.HideOnShowOther) val otherInfoCopy = otherLayoutInto.copy() otherEntry.applyWindowInfo(otherInfoCopy) otherEntry.toolWindow.decoratorComponent?.let { decorator -> toolWindowPane!!.removeDecorator(otherInfoCopy, decorator, false, this) } // store WindowInfo into the SideStack if (isStackEnabled && otherInfo.isDocked && !otherInfo.isAutoHide) { sideStack.push(otherInfoCopy) } } } toolWindowPane!!.addDecorator(entry.toolWindow.getOrCreateDecoratorComponent(), info, dirtyMode, this) // remove tool window from the SideStack if (isStackEnabled) { sideStack.remove(entry.id) } } entry.toolWindow.scheduleContentInitializationIfNeeded() fireToolWindowShown(entry.toolWindow) } override fun registerToolWindow(task: RegisterToolWindowTask): ToolWindow { val toolWindowPane = toolWindowPane ?: init((WindowManager.getInstance() as WindowManagerImpl).allocateFrame(project)) val entry = doRegisterToolWindow(task, toolWindowPane = toolWindowPane) project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(listOf(entry.id), this) toolWindowPane.getStripeFor(entry.toolWindow.anchor).revalidate() toolWindowPane.validate() toolWindowPane.repaint() fireStateChanged() return entry.toolWindow } private fun doRegisterToolWindow(task: RegisterToolWindowTask, toolWindowPane: ToolWindowsPane): ToolWindowEntry { LOG.debug { "enter: installToolWindow($task)" } ApplicationManager.getApplication().assertIsDispatchThread() if (idToEntry.containsKey(task.id)) { throw IllegalArgumentException("window with id=\"${task.id}\" is already registered") } val info = layout.getOrCreate(task) val disposable = Disposer.newDisposable(task.id) Disposer.register(project, disposable) val contentFactory = task.contentFactory val windowInfoSnapshot = info.copy() if (windowInfoSnapshot.isVisible && (contentFactory == null || !task.shouldBeAvailable)) { // isVisible cannot be true if contentFactory is null, because we cannot show toolwindow without content windowInfoSnapshot.isVisible = false } @Suppress("HardCodedStringLiteral") val stripeTitle = task.stripeTitle?.get() ?: task.id val toolWindow = ToolWindowImpl(this, task.id, task.canCloseContent, task.canWorkInDumbMode, task.component, disposable, windowInfoSnapshot, contentFactory, isAvailable = task.shouldBeAvailable, stripeTitle = stripeTitle) toolWindow.windowInfoDuringInit = windowInfoSnapshot try { contentFactory?.init(toolWindow) } finally { toolWindow.windowInfoDuringInit = null } // contentFactory.init can set icon if (toolWindow.icon == null) { task.icon?.let { toolWindow.doSetIcon(it) } } ActivateToolWindowAction.ensureToolWindowActionRegistered(toolWindow) val button = StripeButton(toolWindowPane, toolWindow) val entry = ToolWindowEntry(button, toolWindow, disposable) idToEntry[task.id] = entry // only after added to idToEntry map button.isSelected = windowInfoSnapshot.isVisible button.updatePresentation() addStripeButton(button, toolWindowPane.getStripeFor((contentFactory as? ToolWindowFactoryEx)?.anchor ?: info.anchor)) if (Registry.`is`("ide.new.stripes.ui")) { toolWindow.largeStripeAnchor = if (toolWindow.largeStripeAnchor == ToolWindowAnchor.NONE) task.anchor else toolWindow.largeStripeAnchor } // If preloaded info is visible or active then we have to show/activate the installed // tool window. This step has sense only for windows which are not in the auto hide // mode. But if tool window was active but its mode doesn't allow to activate it again // (for example, tool window is in auto hide mode) then we just activate editor component. if (contentFactory != null /* not null on init tool window from EP */) { if (windowInfoSnapshot.isVisible) { showToolWindowImpl(entry, info, dirtyMode = false) // do not activate tool window that is the part of project frame - default component should be focused if (windowInfoSnapshot.isActiveOnStart && (windowInfoSnapshot.type == ToolWindowType.WINDOWED || windowInfoSnapshot.type == ToolWindowType.FLOATING) && ApplicationManager.getApplication().isActive) { entry.toolWindow.requestFocusInToolWindow() } } } return entry } @Suppress("OverridingDeprecatedMember") override fun unregisterToolWindow(id: String) { doUnregisterToolWindow(id) fireStateChanged() } internal fun doUnregisterToolWindow(id: String) { LOG.debug { "enter: unregisterToolWindow($id)" } ApplicationManager.getApplication().assertIsDispatchThread() val entry = idToEntry.remove(id) ?: return val toolWindow = entry.toolWindow val info = layout.getInfo(id) if (info != null) { // remove decorator and tool button from the screen - removing will also save current bounds updateStateAndRemoveDecorator(info, entry, false) // save recent appearance of tool window activeStack.remove(entry, true) if (isStackEnabled) { sideStack.remove(id) } removeStripeButton(entry.stripeButton) toolWindowPane!!.validate() toolWindowPane!!.repaint() } if (!project.isDisposed) { project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowUnregistered(id, (toolWindow)) } Disposer.dispose(entry.disposable) } private fun updateStateAndRemoveDecorator(info: WindowInfoImpl, entry: ToolWindowEntry, dirtyMode: Boolean) { saveFloatingOrWindowedState(entry, info) removeDecoratorWithoutUpdatingState(entry, info, dirtyMode) } private fun removeDecoratorWithoutUpdatingState(entry: ToolWindowEntry, info: WindowInfoImpl, dirtyMode: Boolean) { entry.windowedDecorator?.let { entry.windowedDecorator = null Disposer.dispose(it) return } entry.floatingDecorator?.let { entry.floatingDecorator = null it.dispose() return } entry.toolWindow.decoratorComponent?.let { toolWindowPane!!.removeDecorator(info, it, dirtyMode, this) return } } private fun saveFloatingOrWindowedState(entry: ToolWindowEntry, info: WindowInfoImpl) { entry.floatingDecorator?.let { info.floatingBounds = it.bounds info.isActiveOnStart = it.isActive return } entry.windowedDecorator?.let { windowedDecorator -> info.isActiveOnStart = windowedDecorator.isActive val frame = windowedDecorator.getFrame() if (frame.isShowing) { val maximized = (frame as JFrame).extendedState == Frame.MAXIMIZED_BOTH if (maximized) { frame.extendedState = Frame.NORMAL frame.invalidate() frame.revalidate() } val bounds = getRootBounds(frame) info.floatingBounds = bounds info.isMaximized = maximized } return } } override fun getLayout(): DesktopLayout { ApplicationManager.getApplication().assertIsDispatchThread() return layout } override fun setLayoutToRestoreLater(layout: DesktopLayout?) { layoutToRestoreLater = layout } override fun getLayoutToRestoreLater() = layoutToRestoreLater override fun setLayout(newLayout: DesktopLayout) { ApplicationManager.getApplication().assertIsDispatchThread() if (idToEntry.isEmpty()) { layout = newLayout return } data class LayoutData(val old: WindowInfoImpl, val new: WindowInfoImpl, val entry: ToolWindowEntry) val list = mutableListOf<LayoutData>() for (entry in idToEntry.values) { val old = layout.getInfo(entry.id) ?: entry.readOnlyWindowInfo as WindowInfoImpl val new = newLayout.getInfo(entry.id) // just copy if defined in the old layout but not in the new if (new == null) { newLayout.addInfo(entry.id, old.copy()) } else if (old != new) { list.add(LayoutData(old = old, new = new, entry = entry)) } } this.layout = newLayout if (list.isEmpty()) { return } for (item in list) { item.entry.applyWindowInfo(item.new) if (item.old.isVisible && !item.new.isVisible) { updateStateAndRemoveDecorator(item.new, item.entry, dirtyMode = true) } if (item.old.anchor != item.new.anchor || item.old.order != item.new.order) { setToolWindowAnchorImpl(item.entry, item.old, item.new, item.new.anchor, item.new.order) } var toShowWindow = false if (item.old.isSplit != item.new.isSplit) { val wasVisible = item.old.isVisible // we should hide the window and show it in a 'new place' to automatically hide possible window that is already located in a 'new place' if (wasVisible) { hideToolWindow(item.entry.id, hideSide = false, moveFocus = true) } if (wasVisible) { toShowWindow = true } } if (item.old.type != item.new.type) { val dirtyMode = item.old.type == ToolWindowType.DOCKED || item.old.type == ToolWindowType.SLIDING updateStateAndRemoveDecorator(item.old, item.entry, dirtyMode) if (item.new.isVisible) { toShowWindow = true } } else if (!item.old.isVisible && item.new.isVisible) { toShowWindow = true } if (toShowWindow) { doShowWindow(item.entry, item.new, dirtyMode = true) } } val toolWindowPane = toolWindowPane!! toolWindowPane.revalidateNotEmptyStripes() toolWindowPane.validate() toolWindowPane.repaint() activateEditorComponent() val frame = frame!! val rootPane = frame.rootPane ?: return rootPane.revalidate() rootPane.repaint() fireStateChanged() checkInvariants("") } override fun invokeLater(runnable: Runnable) { ApplicationManager.getApplication().invokeLater(runnable, project.disposed) } override val focusManager: IdeFocusManager get() = IdeFocusManager.getInstance(project)!! override fun canShowNotification(toolWindowId: String): Boolean { return toolWindowPane?.getStripeFor(idToEntry[toolWindowId]?.readOnlyWindowInfo?.anchor ?: return false)?.getButtonFor(toolWindowId) != null } override fun notifyByBalloon(toolWindowId: String, type: MessageType, @NlsContexts.NotificationContent htmlBody: String) { notifyByBalloon(toolWindowId, type, htmlBody, null, null) } override fun notifyByBalloon(options: ToolWindowBalloonShowOptions) { if (Registry.`is`("ide.new.stripes.ui")) { notifySquareButtonByBalloon(options) return } val entry = idToEntry[options.toolWindowId]!! val existing = entry.balloon if (existing != null) { Disposer.dispose(existing) } val stripe = toolWindowPane!!.getStripeFor(entry.readOnlyWindowInfo.anchor) if (!entry.toolWindow.isAvailable) { entry.toolWindow.isPlaceholderMode = true stripe.updatePresentation() stripe.revalidate() stripe.repaint() } val anchor = entry.readOnlyWindowInfo.anchor val position = Ref.create(Balloon.Position.below) when { ToolWindowAnchor.TOP == anchor -> position.set(Balloon.Position.below) ToolWindowAnchor.BOTTOM == anchor -> position.set(Balloon.Position.above) ToolWindowAnchor.LEFT == anchor -> position.set(Balloon.Position.atRight) ToolWindowAnchor.RIGHT == anchor -> position.set(Balloon.Position.atLeft) } val balloon = createBalloon(options, entry) val button = stripe.getButtonFor(options.toolWindowId) LOG.assertTrue(button != null, ("Button was not found, popup won't be shown. $options")) if (button == null) { return } val show = Runnable { val tracker: PositionTracker<Balloon> if (entry.toolWindow.isVisible && (entry.toolWindow.type == ToolWindowType.WINDOWED || entry.toolWindow.type == ToolWindowType.FLOATING)) { tracker = createPositionTracker(entry.toolWindow.component, ToolWindowAnchor.BOTTOM) } else if (!button.isShowing) { tracker = createPositionTracker(toolWindowPane!!, anchor) } else { tracker = object : PositionTracker<Balloon>(button) { override fun recalculateLocation(`object`: Balloon): RelativePoint? { val otherEntry = idToEntry[options.toolWindowId] ?: return null val stripeButton = otherEntry.stripeButton if (otherEntry.readOnlyWindowInfo.anchor != anchor) { `object`.hide() return null } return RelativePoint(stripeButton, Point(stripeButton.bounds.width / 2, stripeButton.height / 2 - 2)) } } } if (!balloon.isDisposed) { balloon.show(tracker, position.get()) } } if (button.isValid) { show.run() } else { SwingUtilities.invokeLater(show) } } fun notifySquareButtonByBalloon(options: ToolWindowBalloonShowOptions) { val entry = idToEntry[options.toolWindowId]!! val existing = entry.balloon if (existing != null) { Disposer.dispose(existing) } val anchor = entry.readOnlyWindowInfo.largeStripeAnchor val position = Ref.create(Balloon.Position.atLeft) when (anchor) { ToolWindowAnchor.TOP -> position.set(Balloon.Position.atRight) ToolWindowAnchor.RIGHT -> position.set(Balloon.Position.atRight) ToolWindowAnchor.BOTTOM -> position.set(Balloon.Position.atLeft) ToolWindowAnchor.LEFT -> position.set(Balloon.Position.atLeft) } val balloon = createBalloon(options, entry) var button = toolWindowPane!!.getSquareStripeFor(entry.readOnlyWindowInfo.largeStripeAnchor)?.getButtonFor(options.toolWindowId) as ActionButton? if (button == null || !button.isShowing) { button = (toolWindowPane!!.getSquareStripeFor(ToolWindowAnchor.LEFT) as? ToolwindowLeftToolbar)?.moreButton!! position.set(Balloon.Position.atLeft) } val show = Runnable { val tracker: PositionTracker<Balloon> if (entry.toolWindow.isVisible && (entry.toolWindow.type == ToolWindowType.WINDOWED || entry.toolWindow.type == ToolWindowType.FLOATING)) { tracker = createPositionTracker(entry.toolWindow.component, ToolWindowAnchor.BOTTOM) } else { tracker = object : PositionTracker<Balloon>(button) { override fun recalculateLocation(`object`: Balloon): RelativePoint? { val otherEntry = idToEntry[options.toolWindowId] ?: return null if (otherEntry.readOnlyWindowInfo.largeStripeAnchor != anchor) { `object`.hide() return null } return RelativePoint(button, Point(if (position.get() == Balloon.Position.atRight) 0 else button.bounds.width, button.height / 2)) } } } if (!balloon.isDisposed) { balloon.show(tracker, position.get()) } } if (button.isValid) { show.run() } else { SwingUtilities.invokeLater(show) } } private fun createPositionTracker(component: Component, anchor: ToolWindowAnchor): PositionTracker<Balloon> { return object : PositionTracker<Balloon>(component) { override fun recalculateLocation(`object`: Balloon): RelativePoint { val bounds = component.bounds val target = StartupUiUtil.getCenterPoint(bounds, Dimension(1, 1)) when { ToolWindowAnchor.TOP == anchor -> target.y = 0 ToolWindowAnchor.BOTTOM == anchor -> target.y = bounds.height - 3 ToolWindowAnchor.LEFT == anchor -> target.x = 0 ToolWindowAnchor.RIGHT == anchor -> target.x = bounds.width } return RelativePoint(component, target) } } } private fun createBalloon(options: ToolWindowBalloonShowOptions, entry: ToolWindowEntry): Balloon { val listenerWrapper = BalloonHyperlinkListener(options.listener) @Suppress("HardCodedStringLiteral") val content = options.htmlBody.replace("\n", "<br>") val balloonBuilder = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(content, options.icon, options.type.titleForeground, options.type.popupBackground, listenerWrapper) .setBorderColor(options.type.borderColor) .setHideOnClickOutside(false) .setHideOnFrameResize(false) options.balloonCustomizer?.accept(balloonBuilder) val balloon = balloonBuilder.createBalloon() if (balloon is BalloonImpl) { NotificationsManagerImpl.frameActivateBalloonListener(balloon, Runnable { AppExecutorUtil.getAppScheduledExecutorService().schedule({ balloon.setHideOnClickOutside(true) }, 100, TimeUnit.MILLISECONDS) }) } listenerWrapper.balloon = balloon entry.balloon = balloon Disposer.register(balloon, Disposable { entry.toolWindow.isPlaceholderMode = false entry.balloon = null }) Disposer.register(entry.disposable, balloon) return balloon } override fun getToolWindowBalloon(id: String) = idToEntry[id]?.balloon override val isEditorComponentActive: Boolean get() { ApplicationManager.getApplication().assertIsDispatchThread() return ComponentUtil.getParentOfType(EditorsSplitters::class.java, focusManager.focusOwner) != null } fun setToolWindowAnchor(id: String, anchor: ToolWindowAnchor) { ApplicationManager.getApplication().assertIsDispatchThread() setToolWindowAnchor(id, anchor, -1) } // used by Rider @Suppress("MemberVisibilityCanBePrivate") fun setToolWindowAnchor(id: String, anchor: ToolWindowAnchor, order: Int) { val entry = idToEntry[id]!! val info = entry.readOnlyWindowInfo if (anchor == info.anchor && (order == info.order || order == -1)) { return } ApplicationManager.getApplication().assertIsDispatchThread() setToolWindowAnchorImpl(entry, info, getRegisteredMutableInfoOrLogError(id), anchor, order) toolWindowPane!!.validateAndRepaint() fireStateChanged() } fun setLargeStripeAnchor(id: String, anchor: ToolWindowAnchor) { val entry = idToEntry[id]!! val info = entry.readOnlyWindowInfo ApplicationManager.getApplication().assertIsDispatchThread() setToolWindowLargeAnchorImpl(entry, info, getRegisteredMutableInfoOrLogError(id), anchor) toolWindowPane!!.validateAndRepaint() fireStateChanged() } fun setVisibleOnLargeStripe(id: String, visible: Boolean) { val info = getRegisteredMutableInfoOrLogError(id) info.isVisibleOnLargeStripe = visible idToEntry[info.id]!!.applyWindowInfo(info.copy()) fireStateChanged() } private fun setToolWindowAnchorImpl(entry: ToolWindowEntry, currentInfo: WindowInfo, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor, order: Int) { // if tool window isn't visible or only order number is changed then just remove/add stripe button val toolWindowPane = toolWindowPane!! if (!currentInfo.isVisible || anchor == currentInfo.anchor || currentInfo.type == ToolWindowType.FLOATING || currentInfo.type == ToolWindowType.WINDOWED) { doSetAnchor(entry, layoutInfo, anchor, order) } else { val wasFocused = entry.toolWindow.isActive // for docked and sliding windows we have to move buttons and window's decorators layoutInfo.isVisible = false toolWindowPane.removeDecorator(currentInfo, entry.toolWindow.decoratorComponent, /* dirtyMode = */ true, this) doSetAnchor(entry, layoutInfo, anchor, order) showToolWindowImpl(entry, layoutInfo, false) if (wasFocused) { entry.toolWindow.requestFocusInToolWindow() } } } private fun doSetAnchor(entry: ToolWindowEntry, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor, order: Int) { val toolWindowPane = toolWindowPane!! removeStripeButton(entry.stripeButton) layout.setAnchor(layoutInfo, anchor, order) // update infos for all window. Actually we have to update only infos affected by setAnchor method for (otherEntry in idToEntry.values) { val otherInfo = layout.getInfo(otherEntry.id)?.copy() ?: continue otherEntry.applyWindowInfo(otherInfo) } val stripe = toolWindowPane.getStripeFor(anchor) addStripeButton(entry.stripeButton, stripe) stripe.revalidate() } private fun setToolWindowLargeAnchorImpl(entry: ToolWindowEntry, currentInfo: WindowInfo, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor) { val toolWindowPane = toolWindowPane!! if (!currentInfo.isVisible || anchor == currentInfo.largeStripeAnchor || currentInfo.type == ToolWindowType.FLOATING || currentInfo.type == ToolWindowType.WINDOWED) { doSetLargeAnchor(entry, layoutInfo, anchor) } else { val wasFocused = entry.toolWindow.isActive // for docked and sliding windows we have to move buttons and window's decorators layoutInfo.isVisible = false toolWindowPane.removeDecorator(currentInfo, entry.toolWindow.decoratorComponent, true, this) doSetLargeAnchor(entry, layoutInfo, anchor) showToolWindowImpl(entry, layoutInfo, false) if (wasFocused) { entry.toolWindow.requestFocusInToolWindow() } } } private fun doSetLargeAnchor(entry: ToolWindowEntry, layoutInfo: WindowInfoImpl, anchor: ToolWindowAnchor) { toolWindowPane!!.onStripeButtonAdded(project, entry.toolWindow, anchor, layoutInfo) layout.setAnchor(layoutInfo, anchor, -1) // update infos for all window. Actually we have to update only infos affected by setAnchor method for (otherEntry in idToEntry.values) { val otherInfo = layout.getInfo(otherEntry.id)?.copy() ?: continue otherEntry.applyWindowInfo(otherInfo) } } fun setOrderOnLargeStripe(id: String, order: Int) { val info = getRegisteredMutableInfoOrLogError(id) info.orderOnLargeStripe = order idToEntry[info.id]!!.applyWindowInfo(info.copy()) fireStateChanged() } internal fun setSideTool(id: String, isSplit: Boolean) { val entry = idToEntry[id] if (entry == null) { LOG.error("Cannot set side tool: toolwindow $id is not registered") return } if (entry.readOnlyWindowInfo.isSplit != isSplit) { setSideTool(entry, getRegisteredMutableInfoOrLogError(id), isSplit) fireStateChanged() } } private fun setSideTool(entry: ToolWindowEntry, info: WindowInfoImpl, isSplit: Boolean) { if (isSplit == info.isSplit) { return } // we should hide the window and show it in a 'new place' to automatically hide possible window that is already located in a 'new place' hideIfNeededAndShowAfterTask(entry, info) { info.isSplit = isSplit for (otherEntry in idToEntry.values) { otherEntry.applyWindowInfo((layout.getInfo(otherEntry.id) ?: continue).copy()) } } toolWindowPane!!.getStripeFor(entry.readOnlyWindowInfo.anchor).revalidate() } fun setContentUiType(id: String, type: ToolWindowContentUiType) { val info = getRegisteredMutableInfoOrLogError(id) info.contentUiType = type idToEntry[info.id!!]!!.applyWindowInfo(info.copy()) fireStateChanged() } fun setSideToolAndAnchor(id: String, anchor: ToolWindowAnchor, order: Int, isSplit: Boolean) { val entry = idToEntry[id]!! val info = getRegisteredMutableInfoOrLogError(id) if (anchor == entry.readOnlyWindowInfo.anchor && order == entry.readOnlyWindowInfo.order && entry.readOnlyWindowInfo.isSplit == isSplit) { return } hideIfNeededAndShowAfterTask(entry, info) { info.isSplit = isSplit doSetAnchor(entry, info, anchor, order) } fireStateChanged() } private fun hideIfNeededAndShowAfterTask(entry: ToolWindowEntry, info: WindowInfoImpl, source: ToolWindowEventSource? = null, task: () -> Unit) { val wasVisible = entry.readOnlyWindowInfo.isVisible val wasFocused = entry.toolWindow.isActive if (wasVisible) { doHide(entry, info, dirtyMode = true) } task() if (wasVisible) { ToolWindowCollector.getInstance().recordShown(project, source, info) info.isVisible = true val infoSnapshot = info.copy() entry.applyWindowInfo(infoSnapshot) doShowWindow(entry, infoSnapshot, dirtyMode = true) if (wasFocused) { getShowingComponentToRequestFocus(entry.toolWindow)?.requestFocusInWindow() } } toolWindowPane!!.validateAndRepaint() } protected open fun fireStateChanged() { project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).stateChanged(this) } private fun fireToolWindowShown(toolWindow: ToolWindow) { project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowShown(toolWindow) } internal fun setToolWindowAutoHide(id: String, autoHide: Boolean) { ApplicationManager.getApplication().assertIsDispatchThread() val info = getRegisteredMutableInfoOrLogError(id) if (info.isAutoHide == autoHide) { return } info.isAutoHide = autoHide val entry = idToEntry[id] ?: return val newInfo = info.copy() entry.applyWindowInfo(newInfo) fireStateChanged() } fun setToolWindowType(id: String, type: ToolWindowType) { ApplicationManager.getApplication().assertIsDispatchThread() val entry = idToEntry[id]!! if (entry.readOnlyWindowInfo.type == type) { return } setToolWindowTypeImpl(entry, getRegisteredMutableInfoOrLogError(entry.id), type) fireStateChanged() } private fun setToolWindowTypeImpl(entry: ToolWindowEntry, info: WindowInfoImpl, type: ToolWindowType) { if (!entry.readOnlyWindowInfo.isVisible) { info.type = type entry.applyWindowInfo(info.copy()) return } val dirtyMode = entry.readOnlyWindowInfo.type == ToolWindowType.DOCKED || entry.readOnlyWindowInfo.type == ToolWindowType.SLIDING updateStateAndRemoveDecorator(info, entry, dirtyMode) info.type = type val newInfo = info.copy() entry.applyWindowInfo(newInfo) doShowWindow(entry, newInfo, dirtyMode) if (ApplicationManager.getApplication().isActive) { entry.toolWindow.requestFocusInToolWindow() } val frame = frame!! val rootPane = frame.rootPane ?: return rootPane.revalidate() rootPane.repaint() } override fun clearSideStack() { if (isStackEnabled) { sideStack.clear() } } override fun getState(): Element? { // do nothing if the project was not opened if (frame == null) { return null } val element = Element("state") if (isEditorComponentActive) { element.addContent(Element(EDITOR_ELEMENT).setAttribute(ACTIVE_ATTR_VALUE, "true")) } // save layout of tool windows layout.writeExternal(DesktopLayout.TAG)?.let { element.addContent(it) } layoutToRestoreLater?.writeExternal(LAYOUT_TO_RESTORE)?.let { element.addContent(it) } if (recentToolWindows.isNotEmpty()) { val recentState = Element(RECENT_TW_TAG) recentToolWindows.forEach { recentState.addContent(Element("value").apply { addContent(it) }) } element.addContent(recentState) } return element } override fun noStateLoaded() { scheduleSetLayout(WindowManagerEx.getInstanceEx().layout.copy()) } override fun loadState(state: Element) { for (element in state.children) { if (DesktopLayout.TAG == element.name) { val layout = DesktopLayout() layout.readExternal(element) scheduleSetLayout(layout) } else if (LAYOUT_TO_RESTORE == element.name) { layoutToRestoreLater = DesktopLayout() layoutToRestoreLater!!.readExternal(element) } else if (RECENT_TW_TAG == element.name) { recentToolWindows.clear() element.content.forEach { recentToolWindows.add(it.value) } } } } private fun scheduleSetLayout(newLayout: DesktopLayout) { val app = ApplicationManager.getApplication() val task = Runnable { setLayout(newLayout) } if (app.isDispatchThread) { pendingSetLayoutTask.set(null) task.run() } else { pendingSetLayoutTask.set(task) app.invokeLater(Runnable { runPendingLayoutTask() }, project.disposed) } } internal fun setDefaultState(toolWindow: ToolWindowImpl, anchor: ToolWindowAnchor?, type: ToolWindowType?, floatingBounds: Rectangle?) { val info = getRegisteredMutableInfoOrLogError(toolWindow.id) if (info.isFromPersistentSettings) { return } if (floatingBounds != null) { info.floatingBounds = floatingBounds } if (anchor != null) { toolWindow.setAnchor(anchor, null) } if (type != null) { toolWindow.setType(type, null) } } internal fun setDefaultContentUiType(toolWindow: ToolWindowImpl, type: ToolWindowContentUiType) { val info = getRegisteredMutableInfoOrLogError(toolWindow.id) if (info.isFromPersistentSettings) { return } toolWindow.setContentUiType(type, null) } internal fun stretchWidth(toolWindow: ToolWindowImpl, value: Int) { toolWindowPane!!.stretchWidth(toolWindow, value) } override fun isMaximized(window: ToolWindow) = toolWindowPane!!.isMaximized(window) override fun setMaximized(window: ToolWindow, maximized: Boolean) { if (window.type == ToolWindowType.FLOATING && window is ToolWindowImpl) { MaximizeActiveDialogAction.doMaximize(getFloatingDecorator(window.id)) return } if (window.type == ToolWindowType.WINDOWED && window is ToolWindowImpl) { val decorator = getWindowedDecorator(window.id) val frame = if (decorator != null && decorator.getFrame() is Frame) decorator.getFrame() as Frame else return val state = frame.state if (state == Frame.NORMAL) { frame.state = Frame.MAXIMIZED_BOTH } else if (state == Frame.MAXIMIZED_BOTH) { frame.state = Frame.NORMAL } return } toolWindowPane!!.setMaximized(window, maximized) } internal fun stretchHeight(toolWindow: ToolWindowImpl?, value: Int) { toolWindowPane!!.stretchHeight((toolWindow)!!, value) } private class BalloonHyperlinkListener constructor(private val listener: HyperlinkListener?) : HyperlinkListener { var balloon: Balloon? = null override fun hyperlinkUpdate(e: HyperlinkEvent) { val balloon = balloon if (balloon != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) { balloon.hide() } listener?.hyperlinkUpdate(e) } } private fun addFloatingDecorator(entry: ToolWindowEntry, info: WindowInfo) { val frame = frame!!.frame val floatingDecorator = FloatingDecorator(frame!!, entry.toolWindow.getOrCreateDecoratorComponent() as InternalDecoratorImpl) floatingDecorator.apply(info) entry.floatingDecorator = floatingDecorator val bounds = info.floatingBounds if ((bounds != null && bounds.width > 0 && bounds.height > 0 && WindowManager.getInstance().isInsideScreenBounds(bounds.x, bounds.y, bounds.width))) { floatingDecorator.bounds = Rectangle(bounds) } else { val decorator = entry.toolWindow.decorator // place new frame at the center of main frame if there are no floating bounds var size = decorator.size if (size.width == 0 || size.height == 0) { size = decorator.preferredSize } floatingDecorator.size = size floatingDecorator.setLocationRelativeTo(frame) } @Suppress("DEPRECATION") floatingDecorator.show() } private fun addWindowedDecorator(entry: ToolWindowEntry, info: WindowInfo) { if (ApplicationManager.getApplication().isHeadlessEnvironment) { return } val id = entry.id val decorator = entry.toolWindow.getOrCreateDecoratorComponent() val windowedDecorator = FrameWrapper(project, title = "$id - ${project.name}", component = decorator) val window = windowedDecorator.getFrame() MnemonicHelper.init((window as RootPaneContainer).contentPane) val shouldBeMaximized = info.isMaximized val bounds = info.floatingBounds if ((bounds != null && bounds.width > 0 && (bounds.height > 0) && WindowManager.getInstance().isInsideScreenBounds(bounds.x, bounds.y, bounds.width))) { window.bounds = Rectangle(bounds) } else { // place new frame at the center of main frame if there are no floating bounds var size = decorator.size if (size.width == 0 || size.height == 0) { size = decorator.preferredSize } window.size = size window.setLocationRelativeTo(frame!!.frame) } entry.windowedDecorator = windowedDecorator Disposer.register(windowedDecorator, Disposable { if (idToEntry[id]?.windowedDecorator != null) { hideToolWindow(id, false) } }) windowedDecorator.show(false) val rootPane = (window as RootPaneContainer).rootPane val rootPaneBounds = rootPane.bounds val point = rootPane.locationOnScreen val windowBounds = window.bounds window.setLocation(2 * windowBounds.x - point.x, 2 * windowBounds.y - point.y) window.setSize(2 * windowBounds.width - rootPaneBounds.width, 2 * windowBounds.height - rootPaneBounds.height) if (shouldBeMaximized && window is Frame) { window.extendedState = Frame.MAXIMIZED_BOTH } window.toFront() } /** * Notifies window manager about focus traversal in a tool window */ internal class ToolWindowFocusWatcher(private val toolWindow: ToolWindowImpl, component: JComponent) : FocusWatcher() { private val id = toolWindow.id init { install(component) Disposer.register(toolWindow.disposable, Disposable { deinstall(component) }) } override fun isFocusedComponentChangeValid(component: Component?, cause: AWTEvent?) = component != null override fun focusedComponentChanged(component: Component?, cause: AWTEvent?) { if (component == null || !toolWindow.isActive) { return } val toolWindowManager = toolWindow.toolWindowManager toolWindowManager.focusManager .doWhenFocusSettlesDown(ExpirableRunnable.forProject(toolWindowManager.project) { GuiUtils.invokeLaterIfNeeded(Runnable { val entry = toolWindowManager.idToEntry[id] ?: return@Runnable val windowInfo = entry.readOnlyWindowInfo if (!windowInfo.isVisible) { return@Runnable } toolWindowManager.activateToolWindow(entry, toolWindowManager.getRegisteredMutableInfoOrLogError(entry.id), autoFocusContents = false) }, ModalityState.defaultModalityState(), toolWindowManager.project.disposed) }) } } /** * Spies on IdeToolWindow properties and applies them to the window * state. */ internal fun toolWindowPropertyChanged(toolWindow: ToolWindowImpl, property: ToolWindowProperty) { val entry = idToEntry[toolWindow.id] if (property == ToolWindowProperty.AVAILABLE && !toolWindow.isAvailable && entry?.readOnlyWindowInfo?.isVisible == true) { hideToolWindow(toolWindow.id, false) } val stripeButton = entry?.stripeButton if (stripeButton != null) { if (property == ToolWindowProperty.ICON) { stripeButton.updateIcon(toolWindow.icon) } else { stripeButton.updatePresentation() } } ActivateToolWindowAction.updateToolWindowActionPresentation(toolWindow) } internal fun activated(toolWindow: ToolWindowImpl, source: ToolWindowEventSource?) { activateToolWindow(idToEntry[toolWindow.id]!!, getRegisteredMutableInfoOrLogError(toolWindow.id), source = source) } /** * Handles event from decorator and modify weight/floating bounds of the * tool window depending on decoration type. */ @ApiStatus.Internal fun resized(source: InternalDecoratorImpl) { if (!source.isShowing) { // do not recalculate the tool window size if it is not yet shown (and, therefore, has 0,0,0,0 bounds) return } val toolWindow = source.toolWindow val info = getRegisteredMutableInfoOrLogError(toolWindow.id) if (info.type == ToolWindowType.FLOATING) { val owner = SwingUtilities.getWindowAncestor(source) if (owner != null) { info.floatingBounds = owner.bounds } } else if (info.type == ToolWindowType.WINDOWED) { val decorator = getWindowedDecorator(toolWindow.id) val frame = decorator?.getFrame() if (frame == null || !frame.isShowing) { return } info.floatingBounds = getRootBounds(frame as JFrame) info.isMaximized = frame.extendedState == Frame.MAXIMIZED_BOTH } else { // docked and sliding windows val anchor = info.anchor var another: InternalDecoratorImpl? = null if (source.parent is Splitter) { var sizeInSplit = if (anchor.isSplitVertically) source.height.toFloat() else source.width.toFloat() val splitter = source.parent as Splitter if (splitter.secondComponent === source) { sizeInSplit += splitter.dividerWidth.toFloat() another = splitter.firstComponent as InternalDecoratorImpl } else { another = splitter.secondComponent as InternalDecoratorImpl } if (anchor.isSplitVertically) { info.sideWeight = sizeInSplit / splitter.height } else { info.sideWeight = sizeInSplit / splitter.width } } val size = toolWindowPane!!.size var paneWeight = if (anchor.isHorizontal) source.height.toFloat() / size.height else source.width.toFloat() / size.width info.weight = paneWeight if (another != null && anchor.isSplitVertically) { paneWeight = if (anchor.isHorizontal) another.height.toFloat() / size.height else another.width.toFloat() / size.width getRegisteredMutableInfoOrLogError(another.toolWindow.id).weight = paneWeight } } } private fun focusToolWindowByDefault() { var toFocus: ToolWindowEntry? = null for (each in activeStack.stack) { if (each.readOnlyWindowInfo.isVisible) { toFocus = each break } } if (toFocus == null) { for (each in activeStack.persistentStack) { if (each.readOnlyWindowInfo.isVisible) { toFocus = each break } } } if (toFocus != null && !ApplicationManager.getApplication().isDisposed) { activateToolWindow(toFocus, getRegisteredMutableInfoOrLogError(toFocus.id)) } } fun setShowStripeButton(id: String, visibleOnPanel: Boolean) { val info = getRegisteredMutableInfoOrLogError(id) if (visibleOnPanel == info.isShowStripeButton) { return } info.isShowStripeButton = visibleOnPanel idToEntry[info.id!!]!!.applyWindowInfo(info.copy()) fireStateChanged() } internal class InitToolWindowsActivity : StartupActivity { override fun runActivity(project: Project) { val app = ApplicationManager.getApplication() if (app.isUnitTestMode || app.isHeadlessEnvironment) { return } LOG.assertTrue(!app.isDispatchThread) val manager = getInstance(project) as ToolWindowManagerImpl val tasks = runActivity("toolwindow init command creation") { manager.computeToolWindowBeans() } app.invokeLater( manager.beforeProjectOpenedTask(tasks, app), project.disposed, ) } } private fun checkInvariants(additionalMessage: String) { if (!ApplicationManager.getApplication().isEAP && !ApplicationManager.getApplication().isInternal) { return } val violations = mutableListOf<String>() for (entry in idToEntry.values) { val info = layout.getInfo(entry.id) ?: continue if (!info.isVisible) { continue } if (info.type == ToolWindowType.FLOATING) { if (entry.floatingDecorator == null) { violations.add("Floating window has no decorator: ${entry.id}") } } else if (info.type == ToolWindowType.WINDOWED) { if (entry.windowedDecorator == null) { violations.add("Windowed window has no decorator: ${entry.id}") } } } if (violations.isNotEmpty()) { LOG.error("Invariants failed: \n${violations.joinToString("\n")}\nContext: $additionalMessage") } } private inline fun processDescriptors(crossinline handler: (bean: ToolWindowEP, pluginDescriptor: PluginDescriptor) -> Unit) { ToolWindowEP.EP_NAME.processWithPluginDescriptor { bean, pluginDescriptor -> try { handler(bean, pluginDescriptor) } catch (e: ProcessCanceledException) { throw e } catch (e: Throwable) { LOG.error("Cannot process toolwindow ${bean.id}", e) } } } } private enum class KeyState { WAITING, PRESSED, RELEASED, HOLD } private fun areAllModifiersPressed(@JdkConstants.InputEventMask modifiers: Int, @JdkConstants.InputEventMask mask: Int): Boolean { return (modifiers xor mask) == 0 } @JdkConstants.InputEventMask private fun keyCodeToInputMask(code: Int): Int { return when (code) { KeyEvent.VK_SHIFT -> Event.SHIFT_MASK KeyEvent.VK_CONTROL -> Event.CTRL_MASK KeyEvent.VK_META -> Event.META_MASK KeyEvent.VK_ALT -> Event.ALT_MASK else -> 0 } } // We should filter out 'mixed' mask like InputEvent.META_MASK | InputEvent.META_DOWN_MASK @get:JdkConstants.InputEventMask private val activateToolWindowVKsMask: Int get() { if (!LoadingState.COMPONENTS_LOADED.isOccurred) { return 0 } if (Registry.`is`("toolwindow.disable.overlay.by.double.key")) { return 0 } val keymap = KeymapManager.getInstance().activeKeymap val baseShortcut = keymap.getShortcuts("ActivateProjectToolWindow") var baseModifiers = if (SystemInfo.isMac) InputEvent.META_MASK else InputEvent.ALT_MASK for (each in baseShortcut) { if (each is KeyboardShortcut) { val keyStroke = each.firstKeyStroke baseModifiers = keyStroke.modifiers if (baseModifiers > 0) { break } } } // We should filter out 'mixed' mask like InputEvent.META_MASK | InputEvent.META_DOWN_MASK return baseModifiers and (InputEvent.SHIFT_MASK or InputEvent.CTRL_MASK or InputEvent.META_MASK or InputEvent.ALT_MASK) } private val isStackEnabled: Boolean get() = Registry.`is`("ide.enable.toolwindow.stack") private fun getRootBounds(frame: JFrame): Rectangle { val rootPane = frame.rootPane val bounds = rootPane.bounds bounds.setLocation(frame.x + rootPane.x, frame.y + rootPane.y) return bounds } private const val EDITOR_ELEMENT = "editor" private const val ACTIVE_ATTR_VALUE = "active" private const val LAYOUT_TO_RESTORE = "layout-to-restore" private const val RECENT_TW_TAG = "recentWindows" internal enum class ToolWindowProperty { TITLE, ICON, AVAILABLE, STRIPE_TITLE } private fun isInActiveToolWindow(component: Any?, activeToolWindow: ToolWindowImpl): Boolean { var source = if (component is JComponent) component else null val activeToolWindowComponent = activeToolWindow.getComponentIfInitialized() if (activeToolWindowComponent != null) { while (source != null && source !== activeToolWindowComponent) { source = ComponentUtil.getClientProperty(source, ToolWindowManagerImpl.PARENT_COMPONENT) ?: source.parent as? JComponent } } return source != null } fun findIconFromBean(bean: ToolWindowEP, factory: ToolWindowFactory, pluginDescriptor: PluginDescriptor): Icon? { try { return IconLoader.findIcon(bean.icon ?: return null, factory.javaClass, pluginDescriptor.pluginClassLoader, null, true) } catch (e: Exception) { LOG.error(e) return EmptyIcon.ICON_13 } } fun getStripeTitleSupplier(id: String, pluginDescriptor: PluginDescriptor): Supplier<String>? { val classLoader = pluginDescriptor.pluginClassLoader val bundleName = when (pluginDescriptor.pluginId) { PluginManagerCore.CORE_ID -> IdeBundle.BUNDLE else -> pluginDescriptor.resourceBundleBaseName ?: return null } try { val bundle = DynamicBundle.INSTANCE.getResourceBundle(bundleName, classLoader) val key = "toolwindow.stripe.${id}".replace(" ", "_") @Suppress("HardCodedStringLiteral", "UnnecessaryVariable") val fallback = id val label = BundleBase.messageOrDefault(bundle, key, fallback) return Supplier { label } } catch (e: MissingResourceException) { LOG.warn("Missing bundle $bundleName at $classLoader", e) } return null } private fun addStripeButton(button: StripeButton, stripe: Stripe) { stripe.addButton(button) { o1, o2 -> windowInfoComparator.compare(o1.windowInfo, o2.windowInfo) } } private fun removeStripeButton(button: StripeButton) { (button.parent as? Stripe)?.removeButton(button) } @ApiStatus.Internal interface RegisterToolWindowTaskProvider { fun getTasks(project: Project): Collection<ToolWindowEP> } //Adding or removing items? Don't forget to increment the version in ToolWindowEventLogGroup.GROUP enum class ToolWindowEventSource { StripeButton, SquareStripeButton, ToolWindowHeader, ToolWindowHeaderAltClick, Content, Switcher, SwitcherSearch, ToolWindowsWidget, RemoveStripeButtonAction, HideOnShowOther, HideSide, CloseFromSwitcher, ActivateActionMenu, ActivateActionKeyboardShortcut, ActivateActionGotoAction, ActivateActionOther, CloseAction, HideButton, HideToolWindowAction, HideSideWindowsAction, HideAllWindowsAction, JumpToLastWindowAction, ToolWindowSwitcher }
apache-2.0
11272a4ce1eff4d37b0776571af4a57b
34.955527
207
0.691929
4.954957
false
false
false
false
deadpixelsociety/roto-ld34
core/src/com/thedeadpixelsociety/ld34/screens/GameScreenService.kt
1
1680
package com.thedeadpixelsociety.ld34.screens import com.badlogic.gdx.Gdx import com.badlogic.gdx.utils.Disposable import com.thedeadpixelsociety.ld34.TimeKeeper import java.util.* class GameScreenService() : Disposable { private val screens = Stack<GameScreen>() private var accumulator = 0f fun <T : GameScreen> push(screen: T) { screens.push(screen) screen.show() screen.resize(Gdx.graphics.width, Gdx.graphics.height) } private fun <T : GameScreen> remove(screen: T) { screens.remove(screen) screen.hide() screen.dispose() } private fun draw() { screens.forEach { it.draw() } } private fun update() { if (screens.size == 0) return var top = true for (i in 0..screens.size - 1) { val screen = screens[screens.size - 1 - i] if (top) { screen.input() screen.update() } if (!top) remove(screen) if (!screen.overlay) top = false } } fun pause() { screens.forEach { it.pause() } } fun resize(width: Int, height: Int) { screens.forEach { it.resize(width, height) } } fun render(delta: Float) { accumulator += Math.min(delta, TimeKeeper.MAX_DT) while (accumulator >= TimeKeeper.DT) { TimeKeeper.deltaTime = TimeKeeper.DT update() accumulator -= TimeKeeper.DT } draw() TimeKeeper.reset() } fun resume() { screens.forEach { it.resume() } } override fun dispose() { screens.forEach { it.dispose() } } }
mit
8c01be12115c09e2d2a217dd32698dba
21.702703
62
0.555952
4.07767
false
false
false
false
xranby/modern-jogl-examples
src/main/kotlin/main/tut07/worldWithUBO.kt
1
19720
package main.tut07 import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL2ES2.GL_STREAM_DRAW import com.jogamp.opengl.GL2ES3.* import com.jogamp.opengl.GL3 import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP import extensions.intBufferBig import glm.MatrixStack import glsl.Program import main.* import main.framework.Framework import main.framework.Semantic import main.framework.component.Mesh import mat.Mat4 import one.util.streamex.StreamEx import vec._3.Vec3 import vec._4.Vec4 import kotlin.properties.Delegates /** * Created by elect on 02/03/17. */ fun main(args: Array<String>) { WorldWithUBO_() } class WorldWithUBO_ : Framework("Tutorial 07 - World Scene") { val MESHES_SOURCE = arrayOf("UnitConeTint.xml", "UnitCylinderTint.xml", "UnitCubeTint.xml", "UnitCubeColor.xml", "UnitPlane.xml") object MESH { val CONE = 0 val CYLINDER = 1 val CUBE_TINT = 2 val CUBE_COLOR = 3 val PLANE = 4 val MAX = 5 } var uniformColor by Delegates.notNull<ProgramData>() var objectColor by Delegates.notNull<ProgramData>() var uniformColorTint by Delegates.notNull<ProgramData>() var meshes by Delegates.notNull<Array<Mesh>>() val sphereCamRelPos = Vec3(67.5f, -46.0f, 150.0f) val camTarget = Vec3(0.0f, 0.4f, 0.0f) var drawLookAtPoint = false val globalMatricesBufferName = intBufferBig(1) override fun init(gl: GL3) = with(gl) { initializeProgram(gl) meshes = Array<Mesh>(MESH.MAX, { Mesh(gl, this::class.java, "tut07/${MESHES_SOURCE[it]}") }) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glFrontFace(GL_CW) glEnable(GL_DEPTH_TEST) glDepthMask(true) glDepthFunc(GL_LEQUAL) glDepthRangef(0.0f, 1.0f) glEnable(GL_DEPTH_CLAMP) } fun initializeProgram(gl: GL3) = with(gl) { uniformColor = ProgramData(gl, "pos-only-world-transform-ubo.vert", "color-uniform.frag") objectColor = ProgramData(gl, "pos-color-world-transform-ubo.vert", "color-passthrough.frag") uniformColorTint = ProgramData(gl, "pos-color-world-transform-ubo.vert", "color-mult-uniform.frag") glGenBuffers(1, globalMatricesBufferName) glBindBuffer(GL_UNIFORM_BUFFER, globalMatricesBufferName[0]) glBufferData(GL_UNIFORM_BUFFER, Mat4.SIZE * 2.L, null, GL_STREAM_DRAW) glBindBuffer(GL_UNIFORM_BUFFER, 0) glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.GLOBAL_MATRICES, globalMatricesBufferName[0], 0, Mat4.SIZE * 2.L) } override fun display(gl: GL3) = with(gl) { glClearBufferfv(GL_DEPTH, 0, clearDepth.put(0, 1.0f)) glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0.0f).put(1, 0.0f).put(2, 0.0f).put(3, 0.0f)) val camPos = resolveCamPosition() // camMat calcLookAtMatrix(camPos, camTarget, Vec3(0.0f, 1.0f, 0.0f)) to matBuffer glBindBuffer(GL_UNIFORM_BUFFER, globalMatricesBufferName[0]) glBufferSubData(GL_UNIFORM_BUFFER, Mat4.SIZE.L, Mat4.SIZE.L, matBuffer) glBindBuffer(GL_UNIFORM_BUFFER, 0) val modelMatrix = MatrixStack() // Render the ground plane modelMatrix run { scale(100.0f, 1.0f, 100.0f) glUseProgram(uniformColor.theProgram) glUniformMatrix4fv(uniformColor.modelToWorldMatrixUnif, 1, false, top() to matBuffer) glUniform4f(uniformColor.baseColorUnif, 0.302f, 0.416f, 0.0589f, 1.0f) meshes[MESH.PLANE].render(gl) glUseProgram(0) } // Draw the trees drawForest(gl, modelMatrix) // Draw the building modelMatrix run { translate(20.0f, 0.0f, -10.0f) drawParthenon(gl, modelMatrix) } if (drawLookAtPoint) { glDisable(GL3.GL_DEPTH_TEST) modelMatrix run { translate(0.0f, 0.0f, glm.length(camTarget)) scale(1.0f) glUseProgram(objectColor.theProgram) glUniformMatrix4fv(objectColor.modelToWorldMatrixUnif, 1, false, top() to matBuffer) meshes[MESH.CUBE_COLOR].render(gl) glUseProgram(0) } glEnable(GL3.GL_DEPTH_TEST) } } fun resolveCamPosition(): Vec3 { val phi = sphereCamRelPos.x.rad val theta = (sphereCamRelPos.y + 90.0f).rad val sinTheta = glm.sin(theta) val cosTheta = glm.cos(theta) val cosPhi = glm.cos(phi) val sinPhi = glm.sin(phi) val dirToCamera = Vec3(sinTheta * cosPhi, cosTheta, sinTheta * sinPhi) 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 rotMat = Mat4(1.0f) rotMat[0] = Vec4(rightDir, 0.0f) rotMat[1] = Vec4(perpUpDir, 0.0f) rotMat[2] = Vec4(-lookDir, 0.0f) rotMat.transpose_() val transMat = Mat4(1.0f) transMat[3] = Vec4(-cameraPt, 1.0f) return rotMat * transMat } fun drawForest(gl: GL3, modelMatrix: MatrixStack) = forest.forEach { modelMatrix run { translate(it.xPos, 1.0f, it.zPos) drawTree(gl, modelMatrix, it.trunkHeight, it.coneHeight) } } fun drawTree(gl: GL3, modelStack: MatrixStack, trunkHeight: Float, coneHeight: Float) = with(gl) { // Draw trunk modelStack run { scale(1.0f, trunkHeight, 1.0f) translate(0.0f, 0.5f, 0.0f) glUseProgram(uniformColorTint.theProgram) glUniformMatrix4fv(uniformColorTint.modelToWorldMatrixUnif, 1, false, top() to matBuffer) glUniform4f(uniformColorTint.baseColorUnif, 0.694f, 0.4f, 0.106f, 1.0f) meshes[MESH.CYLINDER].render(gl) glUseProgram(0) } run { // Draw the treetop translate(0.0f, trunkHeight, 0.0f) scale(3.0f, coneHeight, 3.0f) glUseProgram(uniformColorTint.theProgram) glUniformMatrix4fv(uniformColorTint.modelToWorldMatrixUnif, 1, false, top() to matBuffer) glUniform4f(uniformColorTint.baseColorUnif, 0.0f, 1.0f, 0.0f, 1.0f) meshes[MESH.CONE].render(gl) glUseProgram(0) } } fun drawParthenon(gl: GL3, modelMatrix: MatrixStack) = with(gl) { val parthenonWidth = 14.0f val parthenonLength = 20.0f val parthenonColumnHeight = 5.0f val parthenonBaseHeight = 1.0f val parthenonTopHeight = 2.0f // Draw base modelMatrix run { scale(Vec3(parthenonWidth, parthenonBaseHeight, parthenonLength)) translate(Vec3(0.0f, 0.5f, 0.0f)) glUseProgram(uniformColorTint.theProgram) glUniformMatrix4fv(uniformColorTint.modelToWorldMatrixUnif, 1, false, top() to matBuffer) glUniform4f(uniformColorTint.baseColorUnif, 0.9f, 0.9f, 0.9f, 0.9f) meshes[MESH.CUBE_TINT].render(gl) glUseProgram(0) } run { // Draw top translate(0.0f, parthenonColumnHeight + parthenonBaseHeight, 0.0f) scale(parthenonWidth, parthenonTopHeight, parthenonLength) translate(0.0f, 0.5f, 0.0f) glUseProgram(uniformColorTint.theProgram) glUniformMatrix4fv(uniformColorTint.modelToWorldMatrixUnif, 1, false, top() to matBuffer) glUniform4f(uniformColorTint.baseColorUnif, 0.9f, 0.9f, 0.9f, 0.9f) meshes[MESH.CUBE_TINT].render(gl) glUseProgram(0) } // Draw columns val frontZval = parthenonLength / 2.0f - 1.0f val rightXval = parthenonWidth / 2.0f - 1.0f repeat((parthenonWidth / 2.0f).i) { modelMatrix run { translate(2.0f * it - parthenonWidth / 2 + 1.0f, parthenonBaseHeight, frontZval) drawColumn(gl, modelMatrix, parthenonColumnHeight) } run { translate(2.0f * it - parthenonWidth / 2.0f + 1.0f, parthenonBaseHeight, -frontZval) drawColumn(gl, modelMatrix, parthenonColumnHeight) } } //Don't draw the first or last columns, since they've been drawn already. for (iColumnNum in 1 until ((parthenonLength - 2.0f) / 2.0f).i - 1) { modelMatrix run { translate(rightXval, parthenonBaseHeight, 2.0f * iColumnNum - parthenonLength / 2.0f + 1.0f) drawColumn(gl, modelMatrix, parthenonColumnHeight) } run { translate(-rightXval, parthenonBaseHeight, 2.0f * iColumnNum - parthenonLength / 2.0f + 1.0f) drawColumn(gl, modelMatrix, parthenonColumnHeight) } } // Draw interior modelMatrix run { translate(0.0f, 1.0f, 0.0f) scale(parthenonWidth - 6.0f, parthenonColumnHeight, parthenonLength - 6.0f) translate(0.0f, 0.5f, 0.0f) glUseProgram(objectColor.theProgram) glUniformMatrix4fv(objectColor.modelToWorldMatrixUnif, 1, false, top() to matBuffer) meshes[MESH.CUBE_COLOR].render(gl) glUseProgram(0) } run { // Draw headpiece translate( 0.0f, parthenonColumnHeight + parthenonBaseHeight + parthenonTopHeight / 2.0f, parthenonLength / 2.0f) rotateX(-135.0f) rotateY(45.0f) glUseProgram(objectColor.theProgram) glUniformMatrix4fv(objectColor.modelToWorldMatrixUnif, 1, false, top() to matBuffer) meshes[MESH.CUBE_COLOR].render(gl) glUseProgram(0) } } //Columns are 1x1 in the X/Z, and fHieght units in the Y. fun drawColumn(gl: GL3, modelMatrix: MatrixStack, parthenonColumnHeight: Float) = with(gl) { val columnBaseHeight = 0.25f //Draw the bottom of the column. modelMatrix run { scale(1.0f, columnBaseHeight, 1.0f) translate(0.0f, 0.5f, 0.0f) glUseProgram(uniformColorTint.theProgram) glUniformMatrix4fv(uniformColorTint.modelToWorldMatrixUnif, 1, false, top() to matBuffer) glUniform4f(uniformColorTint.baseColorUnif, 1.0f, 1.0f, 1.0f, 1.0f) meshes[MESH.CUBE_TINT].render(gl) glUseProgram(0) } run { //Draw the top of the column. translate(0.0f, parthenonColumnHeight - columnBaseHeight, 0.0f) scale(1.0f, columnBaseHeight, 1.0f) translate(0.0f, 0.5f, 0.0f) glUseProgram(uniformColorTint.theProgram) glUniformMatrix4fv(uniformColorTint.modelToWorldMatrixUnif, 1, false, top() to matBuffer) glUniform4f(uniformColorTint.baseColorUnif, 0.9f, 0.9f, 0.9f, 0.9f) meshes[MESH.CUBE_TINT].render(gl) glUseProgram(0) } run { //Draw the main column. translate(0.0f, columnBaseHeight, 0.0f) scale(0.8f, parthenonColumnHeight - columnBaseHeight * 2.0f, 0.8f) translate(0.0f, 0.5f, 0.0f) glUseProgram(uniformColorTint.theProgram) glUniformMatrix4fv(uniformColorTint.modelToWorldMatrixUnif, 1, false, top() to matBuffer) glUniform4f(uniformColorTint.baseColorUnif, 0.9f, 0.9f, 0.9f, 0.9f) meshes[MESH.CYLINDER].render(gl) glUseProgram(0) } } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { val zNear = 1.0f val zFar = 1000.0f glm.perspective(45.0f, w / h.f, zNear, zFar) to matBuffer glBindBuffer(GL_UNIFORM_BUFFER, globalMatricesBufferName[0]) glBufferSubData(GL_UNIFORM_BUFFER, 0, Mat4.SIZE.L, matBuffer) glBindBuffer(GL_UNIFORM_BUFFER, 0) glViewport(0, 0, w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(uniformColor.theProgram) glDeleteProgram(objectColor.theProgram) glDeleteProgram(uniformColorTint.theProgram) StreamEx.of<Mesh>(*meshes).forEach { mesh -> mesh.dispose(gl) } } override fun keyPressed(e: KeyEvent) { when (e.keyCode) { KeyEvent.VK_W -> camTarget.z = camTarget.z - if (e.isShiftDown) 0.4f else 4.0f KeyEvent.VK_S -> camTarget.z = camTarget.z + if (e.isShiftDown) 0.4f else 4.0f KeyEvent.VK_D -> camTarget.x = camTarget.x + if (e.isShiftDown) 0.4f else 4.0f KeyEvent.VK_A -> camTarget.x = camTarget.x - if (e.isShiftDown) 0.4f else 4.0f KeyEvent.VK_E -> camTarget.y = camTarget.y - if (e.isShiftDown) 0.4f else 4.0f KeyEvent.VK_Q -> camTarget.y = camTarget.y + if (e.isShiftDown) 0.4f else 4.0f KeyEvent.VK_I -> sphereCamRelPos.y = sphereCamRelPos.y - if (e.isShiftDown) 1.125f else 11.25f KeyEvent.VK_K -> sphereCamRelPos.y = sphereCamRelPos.y + if (e.isShiftDown) 1.125f else 11.25f KeyEvent.VK_J -> sphereCamRelPos.x = sphereCamRelPos.x - if (e.isShiftDown) 1.125f else 11.25f KeyEvent.VK_L -> sphereCamRelPos.x = sphereCamRelPos.x + if (e.isShiftDown) 1.125f else 11.25f KeyEvent.VK_O -> sphereCamRelPos.z = sphereCamRelPos.z - if (e.isShiftDown) 1.125f else 11.25f KeyEvent.VK_U -> sphereCamRelPos.z = sphereCamRelPos.z + if (e.isShiftDown) 1.125f else 11.25f KeyEvent.VK_SPACE -> drawLookAtPoint = !drawLookAtPoint KeyEvent.VK_ESCAPE -> { animator.remove(window) window.destroy() } } // camTarget.print("Target"); TODO // sphereCamRelPos.print("Position"); sphereCamRelPos.y = glm.clamp(sphereCamRelPos.y, -78.75f, -1.0f) camTarget.y = glm.clamp(camTarget.y, 0.0f, camTarget.y) sphereCamRelPos.z = glm.clamp(sphereCamRelPos.z, 5.0f, sphereCamRelPos.z) } class ProgramData(gl: GL3, vert: String, frag: String) { val theProgram = Program(gl, this::class.java, "tut07", vert, frag).name val modelToWorldMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToWorldMatrix") val baseColorUnif = gl.glGetUniformLocation(theProgram, "baseColor") init { val globalUniformBlockIndex = gl.glGetUniformBlockIndex(theProgram, "GlobalMatrices") gl.glUniformBlockBinding(theProgram, globalUniformBlockIndex, Semantic.Uniform.GLOBAL_MATRICES) } } val forest = arrayOf( TreeData(-45.0f, -40.0f, 2.0f, 3.0f), TreeData(-42.0f, -35.0f, 2.0f, 3.0f), TreeData(-39.0f, -29.0f, 2.0f, 4.0f), TreeData(-44.0f, -26.0f, 3.0f, 3.0f), TreeData(-40.0f, -22.0f, 2.0f, 4.0f), TreeData(-36.0f, -15.0f, 3.0f, 3.0f), TreeData(-41.0f, -11.0f, 2.0f, 3.0f), TreeData(-37.0f, -6.0f, 3.0f, 3.0f), TreeData(-45.0f, 0.0f, 2.0f, 3.0f), TreeData(-39.0f, 4.0f, 3.0f, 4.0f), TreeData(-36.0f, 8.0f, 2.0f, 3.0f), TreeData(-44.0f, 13.0f, 3.0f, 3.0f), TreeData(-42.0f, 17.0f, 2.0f, 3.0f), TreeData(-38.0f, 23.0f, 3.0f, 4.0f), TreeData(-41.0f, 27.0f, 2.0f, 3.0f), TreeData(-39.0f, 32.0f, 3.0f, 3.0f), TreeData(-44.0f, 37.0f, 3.0f, 4.0f), TreeData(-36.0f, 42.0f, 2.0f, 3.0f), TreeData(-32.0f, -45.0f, 2.0f, 3.0f), TreeData(-30.0f, -42.0f, 2.0f, 4.0f), TreeData(-34.0f, -38.0f, 3.0f, 5.0f), TreeData(-33.0f, -35.0f, 3.0f, 4.0f), TreeData(-29.0f, -28.0f, 2.0f, 3.0f), TreeData(-26.0f, -25.0f, 3.0f, 5.0f), TreeData(-35.0f, -21.0f, 3.0f, 4.0f), TreeData(-31.0f, -17.0f, 3.0f, 3.0f), TreeData(-28.0f, -12.0f, 2.0f, 4.0f), TreeData(-29.0f, -7.0f, 3.0f, 3.0f), TreeData(-26.0f, -1.0f, 2.0f, 4.0f), TreeData(-32.0f, 6.0f, 2.0f, 3.0f), TreeData(-30.0f, 10.0f, 3.0f, 5.0f), TreeData(-33.0f, 14.0f, 2.0f, 4.0f), TreeData(-35.0f, 19.0f, 3.0f, 4.0f), TreeData(-28.0f, 22.0f, 2.0f, 3.0f), TreeData(-33.0f, 26.0f, 3.0f, 3.0f), TreeData(-29.0f, 31.0f, 3.0f, 4.0f), TreeData(-32.0f, 38.0f, 2.0f, 3.0f), TreeData(-27.0f, 41.0f, 3.0f, 4.0f), TreeData(-31.0f, 45.0f, 2.0f, 4.0f), TreeData(-28.0f, 48.0f, 3.0f, 5.0f), TreeData(-25.0f, -48.0f, 2.0f, 3.0f), TreeData(-20.0f, -42.0f, 3.0f, 4.0f), TreeData(-22.0f, -39.0f, 2.0f, 3.0f), TreeData(-19.0f, -34.0f, 2.0f, 3.0f), TreeData(-23.0f, -30.0f, 3.0f, 4.0f), TreeData(-24.0f, -24.0f, 2.0f, 3.0f), TreeData(-16.0f, -21.0f, 2.0f, 3.0f), TreeData(-17.0f, -17.0f, 3.0f, 3.0f), TreeData(-25.0f, -13.0f, 2.0f, 4.0f), TreeData(-23.0f, -8.0f, 2.0f, 3.0f), TreeData(-17.0f, -2.0f, 3.0f, 3.0f), TreeData(-16.0f, 1.0f, 2.0f, 3.0f), TreeData(-19.0f, 4.0f, 3.0f, 3.0f), TreeData(-22.0f, 8.0f, 2.0f, 4.0f), TreeData(-21.0f, 14.0f, 2.0f, 3.0f), TreeData(-16.0f, 19.0f, 2.0f, 3.0f), TreeData(-23.0f, 24.0f, 3.0f, 3.0f), TreeData(-18.0f, 28.0f, 2.0f, 4.0f), TreeData(-24.0f, 31.0f, 2.0f, 3.0f), TreeData(-20.0f, 36.0f, 2.0f, 3.0f), TreeData(-22.0f, 41.0f, 3.0f, 3.0f), TreeData(-21.0f, 45.0f, 2.0f, 3.0f), TreeData(-12.0f, -40.0f, 2.0f, 4.0f), TreeData(-11.0f, -35.0f, 3.0f, 3.0f), TreeData(-10.0f, -29.0f, 1.0f, 3.0f), TreeData(-9.0f, -26.0f, 2.0f, 2.0f), TreeData(-6.0f, -22.0f, 2.0f, 3.0f), TreeData(-15.0f, -15.0f, 1.0f, 3.0f), TreeData(-8.0f, -11.0f, 2.0f, 3.0f), TreeData(-14.0f, -6.0f, 2.0f, 4.0f), TreeData(-12.0f, 0.0f, 2.0f, 3.0f), TreeData(-7.0f, 4.0f, 2.0f, 2.0f), TreeData(-13.0f, 8.0f, 2.0f, 2.0f), TreeData(-9.0f, 13.0f, 1.0f, 3.0f), TreeData(-13.0f, 17.0f, 3.0f, 4.0f), TreeData(-6.0f, 23.0f, 2.0f, 3.0f), TreeData(-12.0f, 27.0f, 1.0f, 2.0f), TreeData(-8.0f, 32.0f, 2.0f, 3.0f), TreeData(-10.0f, 37.0f, 3.0f, 3.0f), TreeData(-11.0f, 42.0f, 2.0f, 2.0f), TreeData(15.0f, 5.0f, 2.0f, 3.0f), TreeData(15.0f, 10.0f, 2.0f, 3.0f), TreeData(15.0f, 15.0f, 2.0f, 3.0f), TreeData(15.0f, 20.0f, 2.0f, 3.0f), TreeData(15.0f, 25.0f, 2.0f, 3.0f), TreeData(15.0f, 30.0f, 2.0f, 3.0f), TreeData(15.0f, 35.0f, 2.0f, 3.0f), TreeData(15.0f, 40.0f, 2.0f, 3.0f), TreeData(15.0f, 45.0f, 2.0f, 3.0f), TreeData(25.0f, 5.0f, 2.0f, 3.0f), TreeData(25.0f, 10.0f, 2.0f, 3.0f), TreeData(25.0f, 15.0f, 2.0f, 3.0f), TreeData(25.0f, 20.0f, 2.0f, 3.0f), TreeData(25.0f, 25.0f, 2.0f, 3.0f), TreeData(25.0f, 30.0f, 2.0f, 3.0f), TreeData(25.0f, 35.0f, 2.0f, 3.0f), TreeData(25.0f, 40.0f, 2.0f, 3.0f), TreeData(25.0f, 45.0f, 2.0f, 3.0f)) class TreeData(val xPos: Float, val zPos: Float, val trunkHeight: Float, val coneHeight: Float) }
mit
a876b8970d5775906a03e68df6091580
35.588126
133
0.575
3.178082
false
false
false
false
leafclick/intellij-community
platform/statistics/src/com/intellij/internal/statistic/collectors/fus/os/SystemRuntimeCollector.kt
1
4419
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.collectors.fus.os import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.newMetric import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.Version import com.intellij.util.containers.ContainerUtil import com.intellij.util.lang.JavaVersion import java.lang.management.ManagementFactory import java.util.* class SystemRuntimeCollector : ApplicationUsagesCollector() { override fun getGroupId(): String { return "system.runtime" } override fun getVersion(): Int { return 2 } override fun getMetrics(): Set<MetricEvent> { val result = HashSet<MetricEvent>() Runtime.getRuntime().totalMemory() val cores = Runtime.getRuntime().availableProcessors() result.add(newMetric("cores", cores, null)) for (gc in ManagementFactory.getGarbageCollectorMXBeans()) { result.add(newMetric("garbage.collector", FeatureUsageData().addData("name", gc.name))) } val jvmData = FeatureUsageData(). addVersion(Version(1, JavaVersion.current().feature, 0)). addData("bit", if (SystemInfo.is32Bit) "32" else "64"). addData("vendor", getJavaVendor()) result.add(newMetric("jvm", jvmData)) for (argument in ManagementFactory.getRuntimeMXBean().inputArguments) { val data = convertOptionToData(argument) if (data != null) { result.add(newMetric("jvm.option", data)) } } return result } private fun getJavaVendor() : String { return when { SystemInfo.isJetBrainsJvm -> "JetBrains" SystemInfo.isAppleJvm -> "Apple" SystemInfo.isOracleJvm -> "Oracle" SystemInfo.isSunJvm -> "Sun" SystemInfo.isIbmJvm -> "IBM" SystemInfo.isAzulJvm -> "Azul" else -> "Other" } } companion object { private val knownOptions = ContainerUtil.newHashSet( "-Xms", "-Xmx", "-XX:SoftRefLRUPolicyMSPerMB", "-XX:ReservedCodeCacheSize" ) fun convertOptionToData(arg: String): FeatureUsageData? { val value = getMegabytes(arg).toLong() if (value < 0) return null when { arg.startsWith("-Xmx") -> { return FeatureUsageData(). addData("name", "Xmx"). addData("value", roundDown(value, 512, 750, 1000, 1024, 1500, 2000, 2048, 3000, 4000, 4096, 6000, 8000)) } arg.startsWith("-Xms") -> { return FeatureUsageData(). addData("name", "Xms"). addData("value", roundDown(value, 64, 128, 256, 512)) } arg.startsWith("-XX:SoftRefLRUPolicyMSPerMB") -> { return FeatureUsageData(). addData("name", "SoftRefLRUPolicyMSPerMB"). addData("value", roundDown(value, 50, 100)) } arg.startsWith("-XX:ReservedCodeCacheSize") -> { return FeatureUsageData(). addData("name", "ReservedCodeCacheSize"). addData("value", roundDown(value, 240, 300, 400, 500)) } else -> { return null } } } private fun getMegabytes(s: String): Int { var num = knownOptions.firstOrNull { s.startsWith(it) } ?.let { s.substring(it.length).toUpperCase().trim() } if (num == null) return -1 if (num.startsWith("=")) num = num.substring(1) if (num.last().isDigit()) { return try { Integer.parseInt(num) } catch (e: Exception) { -1 } } try { val size = Integer.parseInt(num.substring(0, num.length - 1)) when (num.last()) { 'B' -> return size / (1024 * 1024) 'K' -> return size / 1024 'M' -> return size 'G' -> return size * 1024 } } catch (e: Exception) { return -1 } return -1 } fun roundDown(value: Long, vararg steps: Long): Long { val length = steps.size if (length == 0 || steps[0] < 0) return -1 var ind = 0 while (ind < length && value >= steps[ind]) { ind++ } return if (ind == 0) 0 else steps[ind - 1] } } }
apache-2.0
f39d1754a24d58ee1a278ed1db5778e8
30.571429
140
0.61575
4.265444
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/controlFlow/ifStatement.kt
2
1903
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* class Controller { var result = "" suspend fun <T> suspendWithResult(value: T): T = suspendCoroutineOrReturn { c -> c.resume(value) COROUTINE_SUSPENDED } } fun builder(c: suspend Controller.() -> Unit): String { val controller = Controller() c.startCoroutine(controller, EmptyContinuation) return controller.result } fun box(): String { var value = builder { if (suspendWithResult(true)) { result = "OK" } } if (value != "OK") return "fail: suspend as if condition: $value" value = builder { for (x in listOf(true, false)) { if (x) { result += suspendWithResult("O") } else { result += "K" } } } if (value != "OK") return "fail: suspend in then branch: $value" value = builder { for (x in listOf(true, false)) { if (x) { result += "O" } else { result += suspendWithResult("K") } } } if (value != "OK") return "fail: suspend in else branch: $value" value = builder { for (x in listOf(true, false)) { if (x) { result += suspendWithResult("O") } else { result += suspendWithResult("K") } } } if (value != "OK") return "fail: suspend in both branches: $value" value = builder { for (x in listOf(true, false)) { if (x) { result += suspendWithResult("O") } result += ";" } } if (value != "O;;") return "fail: suspend in then branch without else: $value" return "OK" }
apache-2.0
270361354947abce91e1e0f477127938
23.397436
84
0.496584
4.315193
false
false
false
false
openmhealth/schemas
kotlin-schema-sdk/src/test/kotlin/org/openmhealth/schema/support/DataFileSource.kt
1
1842
package org.openmhealth.schema.support import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource import org.junit.jupiter.params.support.AnnotationConsumer import org.junit.platform.commons.JUnitException import org.openmhealth.schema.configuration.JacksonConfiguration.objectMapper import org.openmhealth.schema.domain.SchemaId import java.io.IOException import java.util.stream.Stream import kotlin.annotation.AnnotationRetention.RUNTIME import kotlin.annotation.AnnotationTarget.FUNCTION import kotlin.io.path.Path @Target(FUNCTION) @Retention(RUNTIME) @ArgumentsSource(DataFileArgumentsProvider::class) annotation class DataFileSource( val baseDirectory: String = "../test-data", val schemaId: String, val filename: String, ) class DataFileArgumentsProvider : ArgumentsProvider, AnnotationConsumer<DataFileSource> { private lateinit var path: String override fun accept(annotation: DataFileSource) { val schemaId = SchemaId.fromString(annotation.schemaId) path = listOf( schemaId.namespace, schemaId.name, schemaId.version, "shouldPass", annotation.filename ) .joinToString(separator = "/", prefix = annotation.baseDirectory + "/") } override fun provideArguments(context: ExtensionContext): Stream<out Arguments> { val file = Path(path).toFile() val jsonNode = try { objectMapper.readTree(file) } catch (e: IOException) { throw JUnitException("File [$path] could not be read", e) } return listOf(jsonNode) .stream() .map { Arguments.of(it) } } }
apache-2.0
d87bc58269bb47351a4b9e73bb34ad96
31.315789
89
0.718241
4.58209
false
false
false
false
FrimaStudio/slf4j-kotlin-extensions
src/test/kotlin/ExtensionsTest.kt
1
13526
/* * Copyright 2017 Frima Studio * * 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. */ import com.nhaarman.mockitokotlin2.* import org.junit.jupiter.api.Test import org.slf4j.* import java.util.* class ExtensionsTest { private val logger: Logger = mock() private val marker: Marker = mock() private val throwable: Throwable = mock() @Test fun trace_enabled() { given(logger.isTraceEnabled).willReturn(true) logger.trace { TEST_STR } val order = inOrder(logger) then(logger).should(order).isTraceEnabled then(logger).should(order).trace(TEST_STR) order.verifyNoMoreInteractions() } @Test fun trace_disabled() { given(logger.isTraceEnabled).willReturn(false) logger.trace { TEST_STR } then(logger).should().isTraceEnabled verifyNoMoreInteractions(logger) } @Test fun trace_marker_enabled() { given(logger.isTraceEnabled(marker)).willReturn(true) logger.trace(marker) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isTraceEnabled(marker) then(logger).should(order).trace(marker, TEST_STR) order.verifyNoMoreInteractions() } @Test fun trace_marker_disabled() { given(logger.isTraceEnabled(marker)).willReturn(false) logger.trace(marker) { TEST_STR } then(logger).should().isTraceEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun traceThrowable_enabled() { given(logger.isTraceEnabled).willReturn(true) logger.trace(throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isTraceEnabled then(logger).should(order).trace(TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun traceThrowable_disabled() { given(logger.isTraceEnabled).willReturn(false) logger.trace(throwable) { TEST_STR } then(logger).should().isTraceEnabled verifyNoMoreInteractions(logger) } @Test fun traceThrowable_marker_enabled() { given(logger.isTraceEnabled(marker)).willReturn(true) logger.trace(marker, throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isTraceEnabled(marker) then(logger).should(order).trace(marker, TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun traceThrowable_marker_disabled() { given(logger.isTraceEnabled(marker)).willReturn(false) logger.trace(marker, throwable) { TEST_STR } then(logger).should().isTraceEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun debug_enabled() { given(logger.isDebugEnabled).willReturn(true) logger.debug { TEST_STR } val order = inOrder(logger) then(logger).should(order).isDebugEnabled then(logger).should(order).debug(TEST_STR) order.verifyNoMoreInteractions() } @Test fun debug_disabled() { given(logger.isDebugEnabled).willReturn(false) logger.debug { TEST_STR } then(logger).should().isDebugEnabled verifyNoMoreInteractions(logger) } @Test fun debug_marker_enabled() { given(logger.isDebugEnabled(marker)).willReturn(true) logger.debug(marker) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isDebugEnabled(marker) then(logger).should(order).debug(marker, TEST_STR) order.verifyNoMoreInteractions() } @Test fun debug_marker_disabled() { given(logger.isDebugEnabled(marker)).willReturn(false) logger.debug(marker) { TEST_STR } then(logger).should().isDebugEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun debugThrowable_enabled() { given(logger.isDebugEnabled).willReturn(true) logger.debug(throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isDebugEnabled then(logger).should(order).debug(TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun debugThrowable_disabled() { given(logger.isDebugEnabled).willReturn(false) logger.debug(throwable) { TEST_STR } then(logger).should().isDebugEnabled verifyNoMoreInteractions(logger) } @Test fun debugThrowable_marker_enabled() { given(logger.isDebugEnabled(marker)).willReturn(true) logger.debug(marker, throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isDebugEnabled(marker) then(logger).should(order).debug(marker, TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun debugThrowable_marker_disabled() { given(logger.isDebugEnabled(marker)).willReturn(false) logger.debug(marker, throwable) { TEST_STR } then(logger).should().isDebugEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun info_enabled() { given(logger.isInfoEnabled).willReturn(true) logger.info { TEST_STR } val order = inOrder(logger) then(logger).should(order).isInfoEnabled then(logger).should(order).info(TEST_STR) order.verifyNoMoreInteractions() } @Test fun info_disabled() { given(logger.isInfoEnabled).willReturn(false) logger.info { TEST_STR } then(logger).should().isInfoEnabled verifyNoMoreInteractions(logger) } @Test fun info_marker_enabled() { given(logger.isInfoEnabled(marker)).willReturn(true) logger.info(marker) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isInfoEnabled(marker) then(logger).should(order).info(marker, TEST_STR) order.verifyNoMoreInteractions() } @Test fun info_marker_disabled() { given(logger.isInfoEnabled(marker)).willReturn(false) logger.info(marker) { TEST_STR } then(logger).should().isInfoEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun infoThrowable_enabled() { given(logger.isInfoEnabled).willReturn(true) logger.info(throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isInfoEnabled then(logger).should(order).info(TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun infoThrowable_disabled() { given(logger.isInfoEnabled).willReturn(false) logger.info(throwable) { TEST_STR } then(logger).should().isInfoEnabled verifyNoMoreInteractions(logger) } @Test fun infoThrowable_marker_enabled() { given(logger.isInfoEnabled(marker)).willReturn(true) logger.info(marker, throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isInfoEnabled(marker) then(logger).should(order).info(marker, TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun infoThrowable_marker_disabled() { given(logger.isInfoEnabled(marker)).willReturn(false) logger.info(marker, throwable) { TEST_STR } then(logger).should().isInfoEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun warn_enabled() { given(logger.isWarnEnabled).willReturn(true) logger.warn { TEST_STR } val order = inOrder(logger) then(logger).should(order).isWarnEnabled then(logger).should(order).warn(TEST_STR) order.verifyNoMoreInteractions() } @Test fun warn_disabled() { given(logger.isWarnEnabled).willReturn(false) logger.warn { TEST_STR } then(logger).should().isWarnEnabled verifyNoMoreInteractions(logger) } @Test fun warn_marker_enabled() { given(logger.isWarnEnabled(marker)).willReturn(true) logger.warn(marker) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isWarnEnabled(marker) then(logger).should(order).warn(marker, TEST_STR) order.verifyNoMoreInteractions() } @Test fun warn_marker_disabled() { given(logger.isWarnEnabled(marker)).willReturn(false) logger.warn(marker) { TEST_STR } then(logger).should().isWarnEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun warnThrowable_enabled() { given(logger.isWarnEnabled).willReturn(true) logger.warn(throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isWarnEnabled then(logger).should(order).warn(TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun warnThrowable_disabled() { given(logger.isWarnEnabled).willReturn(false) logger.warn(throwable) { TEST_STR } then(logger).should().isWarnEnabled verifyNoMoreInteractions(logger) } @Test fun warnThrowable_marker_enabled() { given(logger.isWarnEnabled(marker)).willReturn(true) logger.warn(marker, throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isWarnEnabled(marker) then(logger).should(order).warn(marker, TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun warnThrowable_marker_disabled() { given(logger.isWarnEnabled(marker)).willReturn(false) logger.warn(marker, throwable) { TEST_STR } then(logger).should().isWarnEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun error_enabled() { given(logger.isErrorEnabled).willReturn(true) logger.error { TEST_STR } val order = inOrder(logger) then(logger).should(order).isErrorEnabled then(logger).should(order).error(TEST_STR) order.verifyNoMoreInteractions() } @Test fun error_disabled() { given(logger.isErrorEnabled).willReturn(false) logger.error { TEST_STR } then(logger).should().isErrorEnabled verifyNoMoreInteractions(logger) } @Test fun error_marker_enabled() { given(logger.isErrorEnabled(marker)).willReturn(true) logger.error(marker) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isErrorEnabled(marker) then(logger).should(order).error(marker, TEST_STR) order.verifyNoMoreInteractions() } @Test fun error_marker_disabled() { given(logger.isErrorEnabled(marker)).willReturn(false) logger.error(marker) { TEST_STR } then(logger).should().isErrorEnabled(marker) verifyNoMoreInteractions(logger) } @Test fun errorThrowable_enabled() { given(logger.isErrorEnabled).willReturn(true) logger.error(throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isErrorEnabled then(logger).should(order).error(TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun errorThrowable_disabled() { given(logger.isErrorEnabled).willReturn(false) logger.error(throwable) { TEST_STR } then(logger).should().isErrorEnabled verifyNoMoreInteractions(logger) } @Test fun errorThrowable_marker_enabled() { given(logger.isErrorEnabled(marker)).willReturn(true) logger.error(marker, throwable) { TEST_STR } val order = inOrder(logger) then(logger).should(order).isErrorEnabled(marker) then(logger).should(order).error(marker, TEST_STR, throwable) order.verifyNoMoreInteractions() } @Test fun errorThrowable_marker_disabled() { given(logger.isErrorEnabled(marker)).willReturn(false) logger.error(marker, throwable) { TEST_STR } then(logger).should().isErrorEnabled(marker) verifyNoMoreInteractions(logger) } companion object { private val TEST_STR = UUID.randomUUID().toString() } }
apache-2.0
5e89a7e7bdf02ad0e22199b9f3c0a634
23.592727
75
0.609345
4.578876
false
true
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/social/ChatMessage.kt
1
1509
package com.habitrpg.android.habitica.models.social import com.habitrpg.android.habitica.models.user.Backer import com.habitrpg.android.habitica.models.user.ContributorInfo import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.Ignore import io.realm.annotations.PrimaryKey open class ChatMessage : RealmObject() { @PrimaryKey var id: String = "" set(value) { field = value likes?.forEach { it.messageId = value } userStyles?.id = id contributor?.userId = id backer?.id = id } var text: String? = null @Ignore var parsedText: CharSequence? = null var timestamp: Long? = null var likes: RealmList<ChatMessageLike>? = null var flagCount: Int = 0 var uuid: String? = null var userID: String? = null var contributor: ContributorInfo? = null var backer: Backer? = null var user: String? = null var sent: Boolean = false var groupId: String? = null var isInboxMessage: Boolean = false var userStyles: UserStyles? = null val isSystemMessage: Boolean get() = uuid == "system" val likeCount: Int get() = likes?.size ?: 0 var username: String? = null val formattedUsername: String? get() = if (username != null) "@$username" else null fun userLikesMessage(userId: String?): Boolean { return likes?.any { userId == it.id } ?: false } }
gpl-3.0
a5cc057eb519a11edb7188412045c6ef
21.578125
64
0.621604
4.203343
false
false
false
false
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonElasticLoadBalancing.kt
1
3113
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.elasticloadbalancing.AbstractAmazonElasticLoadBalancing import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancing import com.amazonaws.services.elasticloadbalancing.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAmazonElasticLoadBalancing(val context: IacContext) : AbstractAmazonElasticLoadBalancing(), AmazonElasticLoadBalancing { override fun addTags(request: AddTagsRequest): AddTagsResult { return with (context) { request.registerWithAutoName() AddTagsResult().registerWithSameNameAs(request) } } override fun attachLoadBalancerToSubnets(request: AttachLoadBalancerToSubnetsRequest): AttachLoadBalancerToSubnetsResult { return with (context) { request.registerWithAutoName() makeProxy<AttachLoadBalancerToSubnetsRequest, AttachLoadBalancerToSubnetsResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( AttachLoadBalancerToSubnetsRequest::getSubnets to AttachLoadBalancerToSubnetsResult::getSubnets ) ) } } override fun createAppCookieStickinessPolicy(request: CreateAppCookieStickinessPolicyRequest): CreateAppCookieStickinessPolicyResult { return with (context) { request.registerWithAutoName() CreateAppCookieStickinessPolicyResult().registerWithSameNameAs(request) } } override fun createLBCookieStickinessPolicy(request: CreateLBCookieStickinessPolicyRequest): CreateLBCookieStickinessPolicyResult { return with (context) { request.registerWithAutoName() CreateLBCookieStickinessPolicyResult().registerWithSameNameAs(request) } } override fun createLoadBalancer(request: CreateLoadBalancerRequest): CreateLoadBalancerResult { return with (context) { request.registerWithAutoName() makeProxy<CreateLoadBalancerRequest, CreateLoadBalancerResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createLoadBalancerListeners(request: CreateLoadBalancerListenersRequest): CreateLoadBalancerListenersResult { return with (context) { request.registerWithAutoName() CreateLoadBalancerListenersResult().registerWithSameNameAs(request) } } override fun createLoadBalancerPolicy(request: CreateLoadBalancerPolicyRequest): CreateLoadBalancerPolicyResult { return with (context) { request.registerWithAutoName() CreateLoadBalancerPolicyResult().registerWithSameNameAs(request) } } } class DeferredAmazonElasticLoadBalancing(context: IacContext) : BaseDeferredAmazonElasticLoadBalancing(context)
mit
8f969f0bb438bcbe5e6dbcf5cd78a171
41.067568
143
0.714423
5.321368
false
false
false
false
siosio/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/gutter/ConsoleIndicatorRenderer.kt
1
668
// 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.console.gutter import com.intellij.openapi.editor.markup.GutterIconRenderer class ConsoleIndicatorRenderer(iconWithTooltip: IconWithTooltip) : GutterIconRenderer() { private val icon = iconWithTooltip.icon private val tooltip = iconWithTooltip.tooltip override fun getIcon() = icon override fun getTooltipText() = tooltip override fun hashCode() = icon.hashCode() override fun equals(other: Any?) = icon == (other as? ConsoleIndicatorRenderer)?.icon }
apache-2.0
9b76b0c35be60ead86ca05bf4763a876
40.8125
158
0.767964
4.638889
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-common/src/org/jetbrains/kotlin/platform/impl/JvmIdePlatformKind.kt
1
3199
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("JvmIdePlatformUtil") @file:Suppress("DEPRECATION_ERROR", "DeprecatedCallableAddReplaceWith") package org.jetbrains.kotlin.platform.impl import com.intellij.util.text.VersionComparatorUtil import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.platform.IdePlatform import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.jvm.isJvm object JvmIdePlatformKind : IdePlatformKind<JvmIdePlatformKind>() { override fun supportsTargetPlatform(platform: TargetPlatform): Boolean = platform.isJvm() override fun platformByCompilerArguments(arguments: CommonCompilerArguments): TargetPlatform? { if (arguments !is K2JVMCompilerArguments) return null val jvmTargetDescription = arguments.jvmTarget ?: return JvmPlatforms.defaultJvmPlatform val jvmTarget = JvmTarget.values() .firstOrNull { VersionComparatorUtil.COMPARATOR.compare(it.description, jvmTargetDescription) >= 0 } ?: return JvmPlatforms.defaultJvmPlatform return JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget) } @Deprecated( message = "IdePlatform is deprecated and will be removed soon, please, migrate to org.jetbrains.kotlin.platform.TargetPlatform", level = DeprecationLevel.ERROR ) override fun getDefaultPlatform(): Platform = Platform(JvmTarget.DEFAULT) override fun createArguments(): CommonCompilerArguments { return K2JVMCompilerArguments() } val platforms: List<TargetPlatform> = JvmTarget.values() .map { ver -> JvmPlatforms.jvmPlatformByTargetVersion(ver) } + listOf(JvmPlatforms.unspecifiedJvmPlatform) override val defaultPlatform get() = JvmPlatforms.defaultJvmPlatform override val argumentsClass get() = K2JVMCompilerArguments::class.java override val name get() = "JVM" @Deprecated( message = "IdePlatform is deprecated and will be removed soon, please, migrate to org.jetbrains.kotlin.platform.TargetPlatform", level = DeprecationLevel.ERROR ) data class Platform(override val version: JvmTarget) : IdePlatform<JvmIdePlatformKind, K2JVMCompilerArguments>() { override val kind get() = JvmIdePlatformKind override fun createArguments(init: K2JVMCompilerArguments.() -> Unit) = K2JVMCompilerArguments() .apply(init) .apply { jvmTarget = [email protected] } } } val IdePlatformKind<*>?.isJvm get() = this is JvmIdePlatformKind @Deprecated( message = "IdePlatform is deprecated and will be removed soon, please, migrate to org.jetbrains.kotlin.platform.TargetPlatform", level = DeprecationLevel.ERROR ) val IdePlatform<*, *>.isJvm: Boolean get() = this is JvmIdePlatformKind.Platform
apache-2.0
9df7924550a61ea67d2945ebaef61698
42.243243
158
0.758987
5.077778
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/codeInspection/incorrectFormatting/IncorrectFormattingFix.kt
3
3133
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.incorrectFormatting import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo.EMPTY import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.lang.LangBundle import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.project.Project import com.intellij.profile.codeInspection.InspectionProjectProfileManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.annotations.Nls import java.util.concurrent.atomic.AtomicBoolean class ReplaceQuickFix(val replacements: List<Pair<RangeMarker, String>>) : LocalQuickFix { override fun getFamilyName() = LangBundle.message("inspection.incorrect.formatting.fix.replace") override fun getFileModifierForPreview(target: PsiFile) = ReplaceQuickFix(replacements) private val applied = AtomicBoolean(false) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { if (!applied.compareAndSet(false, true)) return descriptor .psiElement .containingFile ?.viewProvider ?.document ?.let { doc -> replacements .sortedByDescending { (range, _) -> range.startOffset } .forEach { (range, replacement) -> if (range.isValid) { doc.replaceString(range.startOffset, range.endOffset, replacement) } } PsiDocumentManager.getInstance(project).commitDocument(doc) } } } object ReformatQuickFix : LocalQuickFix { override fun getFamilyName() = LangBundle.message("inspection.incorrect.formatting.fix.reformat") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val innerFile = descriptor.psiElement.containingFile val file = innerFile.viewProvider.run { getPsi(baseLanguage) } CodeStyleManager.getInstance(project).reformatText(file, 0, file.textLength) } } abstract class ReconfigureQuickFix(@Nls val family: String, val reconfigure: IncorrectFormattingInspection.() -> Unit) : LocalQuickFix { override fun getFamilyName() = family override fun startInWriteAction() = false override fun generatePreview(project: Project, previewDescriptor: ProblemDescriptor) = EMPTY override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val file = descriptor.psiElement.containingFile InspectionProjectProfileManager .getInstance(project) .currentProfile .modifyToolSettings(INSPECTION_KEY, file) { inspection -> inspection.reconfigure() } } } object ShowDetailedReportIntention : ReconfigureQuickFix( LangBundle.message("inspection.incorrect.formatting.fix.show.details"), { reportPerFile = false } ) object HideDetailedReportIntention : ReconfigureQuickFix( LangBundle.message("inspection.incorrect.formatting.fix.hide.details"), { reportPerFile = true } )
apache-2.0
831ea98325e4737c1586254b98025ee2
37.679012
158
0.764762
4.949447
false
true
false
false
jwren/intellij-community
plugins/kotlin/compiler-plugins/compiler-plugin-support/maven/src/org/jetbrains/kotlin/idea/maven/compilerPlugin/AbstractMavenImportHandler.kt
1
2961
// 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.maven.compilerPlugin import org.jdom.Element import org.jdom.Text import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup.PluginOption import org.jetbrains.kotlin.idea.compilerPlugin.modifyCompilerArgumentsForPlugin import org.jetbrains.kotlin.idea.facet.KotlinFacet import org.jetbrains.kotlin.idea.maven.KotlinMavenImporter.Companion.KOTLIN_PLUGIN_ARTIFACT_ID import org.jetbrains.kotlin.idea.maven.KotlinMavenImporter.Companion.KOTLIN_PLUGIN_GROUP_ID import org.jetbrains.kotlin.idea.maven.MavenProjectImportHandler abstract class AbstractMavenImportHandler : MavenProjectImportHandler { abstract val compilerPluginId: String abstract val pluginName: String abstract val mavenPluginArtifactName: String abstract val pluginJarFileFromIdea: String override fun invoke(facet: KotlinFacet, mavenProject: MavenProject) { modifyCompilerArgumentsForPlugin(facet, getPluginSetup(mavenProject), compilerPluginId = compilerPluginId, pluginName = pluginName) } abstract fun getOptions( mavenProject: MavenProject, enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String> ): List<PluginOption>? private fun getPluginSetup(mavenProject: MavenProject): CompilerPluginSetup? { val kotlinPlugin = mavenProject.plugins.firstOrNull { it.groupId == KOTLIN_PLUGIN_GROUP_ID && it.artifactId == KOTLIN_PLUGIN_ARTIFACT_ID } ?: return null val configuration = kotlinPlugin.configurationElement ?: return null val enabledCompilerPlugins = configuration.getElement("compilerPlugins") ?.getElements() ?.flatMap { plugin -> plugin.content.mapNotNull { (it as? Text)?.text } } ?: emptyList() val compilerPluginOptions = configuration.getElement("pluginOptions") ?.getElements() ?.flatMap { it.content } ?.mapTo(mutableListOf()) { (it as Text).text } ?: mutableListOf<String>() // We can't use the plugin from Gradle as it may have the incompatible version val classpath = listOf(pluginJarFileFromIdea) val options = getOptions(mavenProject, enabledCompilerPlugins, compilerPluginOptions) ?: return null return CompilerPluginSetup(options, classpath) } private fun Element.getElement(name: String) = content.firstOrNull { it is Element && it.name == name } as? Element @Suppress("UNCHECKED_CAST") private fun Element.getElements() = content.filterIsInstance<Element>() }
apache-2.0
cbf7aea90c533e2162f6a276cb747dcf
46.015873
158
0.717325
5.140625
false
true
false
false
JetBrains/kotlin-native
backend.native/tests/coverage/basic/jumps/main.kt
4
1435
package coverage.basic.jumps fun simpleReturn(n: Int) { if (n == 0) return println(n) } fun returnFromIfBranch(n: Int) { if (n > 0) { if (n > 10) { return } } else if (n < -10) { return } else if (n == 0) { return } println(n) } fun returnFromWhenBranch(n: Int) { when { n == 0 -> return n == 1 -> return n == 2 -> { println(n) return } else -> println(n) } } fun breakFromWhile() { var a = 7 while (true) { if (a < 4) break println(a) a-- } } fun continueFromDoWhile() { var a = 0 do { if (a % 3 == 0) { a++ continue } println(a) a++ } while (a < 10) } fun singleReturn() { return } fun nestedReturn() { while (true) { while (true) { while (true) { if (1 < 2) { return } println() } println() } } println() } fun main() { simpleReturn(0) simpleReturn(1) returnFromIfBranch(1) returnFromIfBranch(11) returnFromIfBranch(-11) returnFromIfBranch(0) returnFromWhenBranch(0) returnFromWhenBranch(1) returnFromWhenBranch(2) breakFromWhile() continueFromDoWhile() singleReturn() nestedReturn() }
apache-2.0
7a2651a66f1e0ba34243c73fc4959b9d
14.955556
34
0.451568
3.560794
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/BasicTextField.kt
3
20358
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.VisualTransformation /** * Basic composable that enables users to edit text via hardware or software keyboard, but * provides no decorations like hint or placeholder. * * Whenever the user edits the text, [onValueChange] is called with the most up to date state * represented by [String] with which developer is expected to update their state. * * Unlike [TextFieldValue] overload, this composable does not let the developer to control * selection, cursor and text composition information. Please check [TextFieldValue] and * corresponding [BasicTextField] overload for more information. * * It is crucial that the value provided in the [onValueChange] is fed back into [BasicTextField] in * order to have the final state of the text being displayed. * * Example usage: * @sample androidx.compose.foundation.samples.BasicTextFieldWithStringSample * * Please keep in mind that [onValueChange] is useful to be informed about the latest state of the * text input by users, however it is generally not recommended to modify the value that you get * via [onValueChange] callback. Any change to this value may result in a context reset and end * up with input session restart. Such a scenario would cause glitches in the UI or text input * experience for users. * * This composable provides basic text editing functionality, however does not include any * decorations such as borders, hints/placeholder. A design system based implementation such as * Material Design Filled text field is typically what is needed to cover most of the needs. This * composable is designed to be used when a custom implementation for different design system is * needed. * * For example, if you need to include a placeholder in your TextField, you can write a composable * using the decoration box like this: * @sample androidx.compose.foundation.samples.PlaceholderBasicTextFieldSample * * If you want to add decorations to your text field, such as icon or similar, and increase the * hit target area, use the decoration box: * @sample androidx.compose.foundation.samples.TextFieldWithIconSample * * In order to create formatted text field, for example for entering a phone number or a social * security number, use a [visualTransformation] parameter. Below is the example of the text field * for entering a credit card number: * @sample androidx.compose.foundation.samples.CreditCardSample * * @param value the input [String] text to be shown in the text field * @param onValueChange the callback that is triggered when the input service updates the text. An * updated text comes as a parameter of the callback * @param modifier optional [Modifier] for this text field. * @param enabled controls the enabled state of the [BasicTextField]. When `false`, the text * field will be neither editable nor focusable, the input of the text field will not be selectable * @param readOnly controls the editable state of the [BasicTextField]. When `true`, the text * field can not be modified, however, a user can focus it and copy text from it. Read-only text * fields are usually used to display pre-filled forms that user can not edit * @param textStyle Style configuration that applies at character level such as color, font etc. * @param keyboardOptions software keyboard options that contains configuration such as * [KeyboardType] and [ImeAction]. * @param keyboardActions when the input service emits an IME action, the corresponding callback * is called. Note that this IME action may be different from what you specified in * [KeyboardOptions.imeAction]. * @param singleLine when set to true, this text field becomes a single horizontally scrolling * text field instead of wrapping onto multiple lines. The keyboard will be informed to not show * the return key as the [ImeAction]. [maxLines] and [minLines] are ignored as both are * automatically set to 1. * @param maxLines the maximum height in terms of maximum number of visible lines. It is required * that 1 <= [minLines] <= [maxLines]. This parameter is ignored when [singleLine] is true. * @param minLines the minimum height in terms of minimum number of visible lines. It is required * that 1 <= [minLines] <= [maxLines]. This parameter is ignored when [singleLine] is true. * @param visualTransformation The visual transformation filter for changing the visual * representation of the input. By default no visual transformation is applied. * @param onTextLayout Callback that is executed when a new text layout is calculated. A * [TextLayoutResult] object that callback provides contains paragraph information, size of the * text, baselines and other details. The callback can be used to add additional decoration or * functionality to the text. For example, to draw a cursor or selection around the text. * @param interactionSource the [MutableInteractionSource] representing the stream of * [Interaction]s for this TextField. You can create and pass in your own remembered * [MutableInteractionSource] if you want to observe [Interaction]s and customize the * appearance / behavior of this TextField in different [Interaction]s. * @param cursorBrush [Brush] to paint cursor with. If [SolidColor] with [Color.Unspecified] * provided, there will be no cursor drawn * @param decorationBox Composable lambda that allows to add decorations around text field, such * as icon, placeholder, helper messages or similar, and automatically increase the hit target area * of the text field. To allow you to control the placement of the inner text field relative to your * decorations, the text field implementation will pass in a framework-controlled composable * parameter "innerTextField" to the decorationBox lambda you provide. You must call * innerTextField exactly once. */ @Composable fun BasicTextField( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, singleLine: Boolean = false, maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE, minLines: Int = 1, visualTransformation: VisualTransformation = VisualTransformation.None, onTextLayout: (TextLayoutResult) -> Unit = {}, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, cursorBrush: Brush = SolidColor(Color.Black), decorationBox: @Composable (innerTextField: @Composable () -> Unit) -> Unit = @Composable { innerTextField -> innerTextField() } ) { // Holds the latest internal TextFieldValue state. We need to keep it to have the correct value // of the composition. var textFieldValueState by remember { mutableStateOf(TextFieldValue(text = value)) } // Holds the latest TextFieldValue that BasicTextField was recomposed with. We couldn't simply // pass `TextFieldValue(text = value)` to the CoreTextField because we need to preserve the // composition. val textFieldValue = textFieldValueState.copy(text = value) SideEffect { if (textFieldValue.selection != textFieldValueState.selection || textFieldValue.composition != textFieldValueState.composition) { textFieldValueState = textFieldValue } } // Last String value that either text field was recomposed with or updated in the onValueChange // callback. We keep track of it to prevent calling onValueChange(String) for same String when // CoreTextField's onValueChange is called multiple times without recomposition in between. var lastTextValue by remember(value) { mutableStateOf(value) } CoreTextField( value = textFieldValue, onValueChange = { newTextFieldValueState -> textFieldValueState = newTextFieldValueState val stringChangedSinceLastInvocation = lastTextValue != newTextFieldValueState.text lastTextValue = newTextFieldValueState.text if (stringChangedSinceLastInvocation) { onValueChange(newTextFieldValueState.text) } }, modifier = modifier, textStyle = textStyle, visualTransformation = visualTransformation, onTextLayout = onTextLayout, interactionSource = interactionSource, cursorBrush = cursorBrush, imeOptions = keyboardOptions.toImeOptions(singleLine = singleLine), keyboardActions = keyboardActions, softWrap = !singleLine, minLines = if (singleLine) 1 else minLines, maxLines = if (singleLine) 1 else maxLines, decorationBox = decorationBox, enabled = enabled, readOnly = readOnly ) } /** * Basic composable that enables users to edit text via hardware or software keyboard, but * provides no decorations like hint or placeholder. * * Whenever the user edits the text, [onValueChange] is called with the most up to date state * represented by [TextFieldValue]. [TextFieldValue] contains the text entered by user, as well * as selection, cursor and text composition information. Please check [TextFieldValue] for the * description of its contents. * * It is crucial that the value provided in the [onValueChange] is fed back into [BasicTextField] in * order to have the final state of the text being displayed. * * Example usage: * @sample androidx.compose.foundation.samples.BasicTextFieldSample * * Please keep in mind that [onValueChange] is useful to be informed about the latest state of the * text input by users, however it is generally not recommended to modify the values in the * [TextFieldValue] that you get via [onValueChange] callback. Any change to the values in * [TextFieldValue] may result in a context reset and end up with input session restart. Such * a scenario would cause glitches in the UI or text input experience for users. * * This composable provides basic text editing functionality, however does not include any * decorations such as borders, hints/placeholder. A design system based implementation such as * Material Design Filled text field is typically what is needed to cover most of the needs. This * composable is designed to be used when a custom implementation for different design system is * needed. * * For example, if you need to include a placeholder in your TextField, you can write a composable * using the decoration box like this: * @sample androidx.compose.foundation.samples.PlaceholderBasicTextFieldSample * * * If you want to add decorations to your text field, such as icon or similar, and increase the * hit target area, use the decoration box: * @sample androidx.compose.foundation.samples.TextFieldWithIconSample * * @param value The [androidx.compose.ui.text.input.TextFieldValue] to be shown in the * [BasicTextField]. * @param onValueChange Called when the input service updates the values in [TextFieldValue]. * @param modifier optional [Modifier] for this text field. * @param enabled controls the enabled state of the [BasicTextField]. When `false`, the text * field will be neither editable nor focusable, the input of the text field will not be selectable * @param readOnly controls the editable state of the [BasicTextField]. When `true`, the text * field can not be modified, however, a user can focus it and copy text from it. Read-only text * fields are usually used to display pre-filled forms that user can not edit * @param textStyle Style configuration that applies at character level such as color, font etc. * @param keyboardOptions software keyboard options that contains configuration such as * [KeyboardType] and [ImeAction]. * @param keyboardActions when the input service emits an IME action, the corresponding callback * is called. Note that this IME action may be different from what you specified in * [KeyboardOptions.imeAction]. * @param singleLine when set to true, this text field becomes a single horizontally scrolling * text field instead of wrapping onto multiple lines. The keyboard will be informed to not show * the return key as the [ImeAction]. [maxLines] and [minLines] are ignored as both are * automatically set to 1. * @param maxLines the maximum height in terms of maximum number of visible lines. It is required * that 1 <= [minLines] <= [maxLines]. This parameter is ignored when [singleLine] is true. * @param minLines the minimum height in terms of minimum number of visible lines. It is required * that 1 <= [minLines] <= [maxLines]. This parameter is ignored when [singleLine] is true. * @param visualTransformation The visual transformation filter for changing the visual * representation of the input. By default no visual transformation is applied. * @param onTextLayout Callback that is executed when a new text layout is calculated. A * [TextLayoutResult] object that callback provides contains paragraph information, size of the * text, baselines and other details. The callback can be used to add additional decoration or * functionality to the text. For example, to draw a cursor or selection around the text. * @param interactionSource the [MutableInteractionSource] representing the stream of * [Interaction]s for this TextField. You can create and pass in your own remembered * [MutableInteractionSource] if you want to observe [Interaction]s and customize the * appearance / behavior of this TextField in different [Interaction]s. * @param cursorBrush [Brush] to paint cursor with. If [SolidColor] with [Color.Unspecified] * provided, there will be no cursor drawn * @param decorationBox Composable lambda that allows to add decorations around text field, such * as icon, placeholder, helper messages or similar, and automatically increase the hit target area * of the text field. To allow you to control the placement of the inner text field relative to your * decorations, the text field implementation will pass in a framework-controlled composable * parameter "innerTextField" to the decorationBox lambda you provide. You must call * innerTextField exactly once. */ @Composable fun BasicTextField( value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, singleLine: Boolean = false, maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE, minLines: Int = 1, visualTransformation: VisualTransformation = VisualTransformation.None, onTextLayout: (TextLayoutResult) -> Unit = {}, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, cursorBrush: Brush = SolidColor(Color.Black), decorationBox: @Composable (innerTextField: @Composable () -> Unit) -> Unit = @Composable { innerTextField -> innerTextField() } ) { CoreTextField( value = value, onValueChange = { if (value != it) { onValueChange(it) } }, modifier = modifier, textStyle = textStyle, visualTransformation = visualTransformation, onTextLayout = onTextLayout, interactionSource = interactionSource, cursorBrush = cursorBrush, imeOptions = keyboardOptions.toImeOptions(singleLine = singleLine), keyboardActions = keyboardActions, softWrap = !singleLine, minLines = if (singleLine) 1 else minLines, maxLines = if (singleLine) 1 else maxLines, decorationBox = decorationBox, enabled = enabled, readOnly = readOnly ) } @Deprecated("Maintained for binary compatibility", level = DeprecationLevel.HIDDEN) @Composable fun BasicTextField( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, singleLine: Boolean = false, maxLines: Int = Int.MAX_VALUE, visualTransformation: VisualTransformation = VisualTransformation.None, onTextLayout: (TextLayoutResult) -> Unit = {}, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, cursorBrush: Brush = SolidColor(Color.Black), decorationBox: @Composable (innerTextField: @Composable () -> Unit) -> Unit = @Composable { innerTextField -> innerTextField() } ) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier, enabled = enabled, readOnly = readOnly, textStyle = textStyle, keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, singleLine = singleLine, minLines = 1, maxLines = maxLines, visualTransformation = visualTransformation, onTextLayout = onTextLayout, interactionSource = interactionSource, cursorBrush = cursorBrush, decorationBox = decorationBox ) } @Deprecated("Maintained for binary compatibility", level = DeprecationLevel.HIDDEN) @Composable fun BasicTextField( value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, singleLine: Boolean = false, maxLines: Int = Int.MAX_VALUE, visualTransformation: VisualTransformation = VisualTransformation.None, onTextLayout: (TextLayoutResult) -> Unit = {}, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, cursorBrush: Brush = SolidColor(Color.Black), decorationBox: @Composable (innerTextField: @Composable () -> Unit) -> Unit = @Composable { innerTextField -> innerTextField() } ) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier, enabled = enabled, readOnly = readOnly, textStyle = textStyle, keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, singleLine = singleLine, minLines = 1, maxLines = maxLines, visualTransformation = visualTransformation, onTextLayout = onTextLayout, interactionSource = interactionSource, cursorBrush = cursorBrush, decorationBox = decorationBox ) }
apache-2.0
bd6df29e0f840473d99be8b9f03165bd
51.202564
100
0.747176
4.918579
false
false
false
false
holisticon/ranked
extensions/src/main/kotlin/Spring.kt
1
1391
package de.holisticon.ranked.extension import org.springframework.aop.support.AopUtils import org.springframework.boot.runApplication import org.springframework.context.SmartLifecycle import kotlin.reflect.KClass /** * @return the targetClass of a Spring Bean as KClass */ fun Any.getTargetClass(): KClass<out Any> { return AopUtils.getTargetClass(this).kotlin } inline fun <reified T : kotlin.Any> runApplicationExpr(vararg args: kotlin.String): Unit { runApplication<T>(*args) } inline fun defaultSmartLifecycle(thePhase:Int, crossinline action:() ->Unit) = object: DefaultSmartLifecycle(thePhase) { override fun onStart() { action() } } /** * Opinionated best guess implementation of [SmartLifecycle], just override [onStart] and [getPhase] * to get an auto-started, startable and stoppable lifecycle manager. * * object: DefaultSmartLifecycle(50) { * override fun onStart() { ... } * } */ abstract class DefaultSmartLifecycle(private val thePhase : Int) : SmartLifecycle { private var running: Boolean = false override fun start() { onStart() this.running = true } abstract fun onStart() override fun isAutoStartup() = true override fun stop(callback: Runnable?) { callback?.run() this.running = false } override fun stop() = stop(null) override fun isRunning() = running override fun getPhase(): Int = thePhase }
bsd-3-clause
b9018add8d26612a1f434b66b27977d2
23.839286
120
0.726815
3.997126
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/platform/DesktopPlatform.desktop.kt
3
1820
/* * 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. */ /* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform internal enum class DesktopPlatform { Linux, Windows, MacOS, Unknown; companion object { /** * Identify OS on which the application is currently running. */ val Current: DesktopPlatform by lazy { val name = System.getProperty("os.name") when { name?.startsWith("Linux") == true -> Linux name?.startsWith("Win") == true -> Windows name == "Mac OS X" -> MacOS else -> Unknown } } } }
apache-2.0
e9a187dc3d302cb9cef882724b5260bf
32.109091
75
0.665385
4.471744
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/nullability/LocalValReassignment.kt
13
731
internal class A { /* rare nullable, handle with caution */ fun nullableString(): String? { return if (Math.random() > 0.999) { "a string" } else null } fun takesNotNullString(s: String) { println(s.substring(1)) } fun aVoid() { var aString: String? if (nullableString() != null) { aString = nullableString() if (aString != null) { for (i in 0..9) { takesNotNullString(aString!!) // Bang-bang here aString = nullableString() } } else { aString = "aaa" } } else { aString = "bbbb" } } }
apache-2.0
755ad0dbb8ca6f4978e1ae8986eeacbe
24.241379
67
0.440492
4.597484
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/HeaderPanel.kt
2
5525
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.intellij.openapi.util.SystemInfo import com.intellij.ui.HyperlinkLabel import com.intellij.ui.RelativeFont import com.intellij.util.ui.AsyncProcessIcon import com.intellij.util.ui.components.BorderLayoutPanel import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.ui.util.scrollbarWidth import kotlinx.coroutines.Deferred import java.awt.BorderLayout import java.awt.FlowLayout import javax.swing.JLabel @Suppress("MagicNumber") // Swing dimension constants internal class HeaderPanel( onUpdateAllLinkClicked: (List<PackageSearchOperation<*>>) -> Unit ) : BorderLayoutPanel() { private val titleLabel = JLabel().apply { border = emptyBorder(right = 10) font = RelativeFont.BOLD.derive(font) } private val countLabel = JLabel().apply { foreground = PackageSearchUI.Colors.infoLabelForeground border = emptyBorder(right = 8) } private val progressAnimation = AsyncProcessIcon("pkgs-header-progress").apply { isVisible = false suspend() } private val updateAllLink = HyperlinkLabel( PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgradeAll.text") ).apply { isVisible = false border = emptyBorder(top = 4) insets.top = 3.scaled() } private var updateAllOperations:List<PackageSearchOperation<*>>? = null init { PackageSearchUI.setHeightPreScaled(this, PackageSearchUI.smallHeaderHeight.get()) border = emptyBorder(top = 5, left = 5, right = 1 + scrollbarWidth()) background = PackageSearchUI.Colors.sectionHeaderBackground add( PackageSearchUI.flowPanel(PackageSearchUI.Colors.sectionHeaderBackground) { layout = FlowLayout(FlowLayout.LEFT, 6.scaled(), 0) add(titleLabel) add(countLabel) add(progressAnimation) }, BorderLayout.WEST ) add( PackageSearchUI.flowPanel(PackageSearchUI.Colors.sectionHeaderBackground) { layout = FlowLayout(FlowLayout.RIGHT, 6.scaled(), 0) add(updateAllLink) }, BorderLayout.EAST ) updateAllLink.addHyperlinkListener { updateAllOperations?.let { onUpdateAllLinkClicked(it) } PackageSearchEventsLogger.logUpgradeAll() } } fun showBusyIndicator(showIndicator: Boolean) { if (showIndicator) { progressAnimation.isVisible = true progressAnimation.resume() } else { progressAnimation.isVisible = false progressAnimation.suspend() } } fun display(viewModel: PackagesHeaderData) { titleLabel.text = viewModel.labelText countLabel.isVisible = true countLabel.text = viewModel.count.toString() updateAllOperations = viewModel.updateOperations if (viewModel.availableUpdatesCount > 0) { updateAllLink.setHyperlinkText( PackageSearchBundle.message( "packagesearch.ui.toolwindow.actions.upgradeAll.text.withCount", viewModel.availableUpdatesCount ) ) updateAllLink.isVisible = true } else { updateAllLink.isVisible = false } } fun adjustForScrollbar(scrollbarVisible: Boolean, scrollbarOpaque: Boolean) { // Non-opaque scrollbars for JTable are supported on Mac only (as of IJ 2020.3): // See JBScrollPane.Layout#isAlwaysOpaque val isAlwaysOpaque = !SystemInfo.isMac /* && ScrollSettings.isNotSupportedYet(view), == true for JTable */ val includeScrollbar = scrollbarVisible && (isAlwaysOpaque || scrollbarOpaque) @ScaledPixels val rightBorder = if (includeScrollbar) scrollbarWidth() else 1.scaled() border = emptyBorder(top = 5, left = 5, right = rightBorder) updateAndRepaint() } override fun getBackground() = PackageSearchUI.Colors.sectionHeaderBackground }
apache-2.0
f1f42467b745a7cc8c85c92b72c35048
38.464286
114
0.678552
5.120482
false
false
false
false
jwren/intellij-community
platform/execution-impl/src/com/intellij/execution/lineMarker/ExecutorAction.kt
1
5028
// 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.execution.lineMarker import com.intellij.execution.Executor import com.intellij.execution.actions.RunContextAction import com.intellij.openapi.actionSystem.* import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolderBase import org.jetbrains.annotations.NonNls /** * @param order corresponding sorting happens here: [com.intellij.execution.actions.BaseRunConfigurationAction.getOrderedConfiguration] */ @Suppress("ComponentNotRegistered") class ExecutorAction private constructor(val origin: AnAction, val executor: Executor, val order: Int) : ActionGroup(), ActionWithDelegate<AnAction>, UpdateInBackground { init { copyFrom(origin) } override fun isUpdateInBackground() = UpdateInBackground.isUpdateInBackground(origin) companion object { @JvmStatic val orderKey: DataKey<Int> = DataKey.create("Order") @JvmStatic @JvmOverloads fun getActions(order: Int = 0) = getActionList(order).toTypedArray() @JvmStatic @JvmOverloads fun getActionList(order: Int = 0): List<AnAction> { val actionManager = ActionManager.getInstance() val createAction = actionManager.getAction("CreateRunConfiguration") val extensions = Executor.EXECUTOR_EXTENSION_NAME.extensionList val result = ArrayList<AnAction>(extensions.size + (if (createAction == null) 0 else 2)) extensions .mapNotNullTo(result) { executor -> actionManager.getAction(executor.contextActionId)?.let { ExecutorAction(it, executor, order) } } if (createAction != null) { result.add(object : EmptyAction.MyDelegatingActionGroup(createAction as ActionGroup) { override fun update(e: AnActionEvent) { super.update(wrapEvent(e, order)) } override fun actionPerformed(e: AnActionEvent) { super.actionPerformed(wrapEvent(e, order)) } override fun getChildren(e: AnActionEvent?): Array<AnAction> { return super.getChildren(e?.let { wrapEvent(e, order)}) } }) } return result } private fun wrapEvent(e: AnActionEvent, order : Int): AnActionEvent { val dataContext = wrapContext(e.dataContext, order) return AnActionEvent(e.inputEvent, dataContext, e.place, e.presentation, e.actionManager, e.modifiers) } private fun wrapContext(dataContext: DataContext, order : Int): DataContext { return if (order == 0) dataContext else MyDataContext(dataContext, order) } @JvmStatic fun wrap(runContextAction: RunContextAction, order: Int): AnAction { return ExecutorAction(runContextAction, runContextAction.executor, order) } } override fun getDelegate(): AnAction { return origin } override fun update(e: AnActionEvent) { origin.update(wrapEvent(e, order)) if (origin !is ActionGroup) { e.presentation.isPerformGroup = true } } override fun actionPerformed(e: AnActionEvent) { origin.actionPerformed(wrapEvent(e, order)) } override fun getChildren(e: AnActionEvent?): Array<AnAction> = (origin as? ActionGroup)?.getChildren(e?.let { wrapEvent(it, order) }) ?: AnAction.EMPTY_ARRAY override fun isDumbAware() = origin.isDumbAware override fun isPopup() = origin !is ActionGroup || origin.isPopup override fun hideIfNoVisibleChildren() = origin is ActionGroup && origin.hideIfNoVisibleChildren() override fun disableIfNoVisibleChildren() = origin is ActionGroup && origin.disableIfNoVisibleChildren() override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is ExecutorAction) { return false } if (origin != other.origin) return false if (executor != other.executor) return false if (order != other.order) return false return true } override fun hashCode(): Int { var result = origin.hashCode() result = 31 * result + executor.hashCode() result = 31 * result + order return result } private class MyDataContext(private val myDelegate: DataContext, val order: Int) : UserDataHolderBase(), DataContext { @Synchronized override fun getData(dataId: @NonNls String): Any? { if (orderKey.`is`(dataId)) { return order } return myDelegate.getData(dataId) } override fun <T : Any?> getUserData(key: Key<T>): T? { if (myDelegate is UserDataHolder) { return myDelegate.getUserData(key) } return super.getUserData(key) } override fun <T : Any?> putUserData(key: Key<T>, value: T?) { if (myDelegate is UserDataHolder) { myDelegate.putUserData(key, value) } else{ super.putUserData(key, value) } } } }
apache-2.0
9b0a4feeeb386f8688a84d6bd70ff482
32.085526
159
0.677605
4.61708
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/note/selection/activity/SelectableNotesActivityBase.kt
1
5107
package com.maubis.scarlet.base.note.selection.activity import android.os.Bundle import android.view.View import android.widget.GridLayout import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.github.bijoysingh.starter.async.MultiAsyncTask import com.github.bijoysingh.starter.recyclerview.RecyclerViewBuilder import com.maubis.scarlet.base.R import com.maubis.scarlet.base.config.ApplicationBase.Companion.instance import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppPreferences import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme import com.maubis.scarlet.base.core.note.sort import com.maubis.scarlet.base.database.room.note.Note import com.maubis.scarlet.base.main.recycler.EmptyRecyclerItem import com.maubis.scarlet.base.note.folder.SelectorFolderRecyclerItem import com.maubis.scarlet.base.note.recycler.NoteAppAdapter import com.maubis.scarlet.base.note.recycler.NoteRecyclerItem import com.maubis.scarlet.base.note.recycler.getSelectableRecyclerItemControllerList import com.maubis.scarlet.base.settings.sheet.STORE_KEY_LINE_COUNT import com.maubis.scarlet.base.settings.sheet.SettingsOptionsBottomSheet import com.maubis.scarlet.base.settings.sheet.SortingOptionsBottomSheet import com.maubis.scarlet.base.settings.sheet.sNoteItemLineCount import com.maubis.scarlet.base.settings.sheet.sUIUseGridView import com.maubis.scarlet.base.support.recycler.RecyclerItem import com.maubis.scarlet.base.support.ui.SecuredActivity import com.maubis.scarlet.base.support.ui.ThemeColorType abstract class SelectableNotesActivityBase : SecuredActivity(), INoteSelectorActivity { lateinit var recyclerView: RecyclerView lateinit var adapter: NoteAppAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(getLayoutUI()) } open fun initUI() { notifyThemeChange() setupRecyclerView() MultiAsyncTask.execute(object : MultiAsyncTask.Task<List<RecyclerItem>> { override fun run(): List<RecyclerItem> { val sorting = SortingOptionsBottomSheet.getSortingState() val notes = sort(getNotes(), sorting) .sortedBy { it.folder } .map { NoteRecyclerItem(this@SelectableNotesActivityBase, it) } if (notes.isEmpty()) { return notes } val items = emptyList<RecyclerItem>().toMutableList() var lastFolder = "" notes.forEach { val noteFolderId = it.note.folder if (lastFolder != noteFolderId) { val folder = instance.foldersDatabase().getByUUID(noteFolderId) if (folder !== null) { items.add(SelectorFolderRecyclerItem(this@SelectableNotesActivityBase, folder)) lastFolder = noteFolderId } } items.add(it) } return items } override fun handle(notes: List<RecyclerItem>) { adapter.clearItems() if (notes.isEmpty()) { adapter.addItem(EmptyRecyclerItem()) } notes.forEach { adapter.addItem(it) } } }) findViewById<View>(R.id.back_button).setOnClickListener { onBackPressed() } } abstract fun getNotes(): List<Note>; open fun getLayoutUI(): Int = R.layout.activity_select_note fun setupRecyclerView() { val isTablet = resources.getBoolean(R.bool.is_tablet) val isMarkdownEnabled = sAppPreferences.get(SettingsOptionsBottomSheet.KEY_MARKDOWN_ENABLED, true) val isMarkdownHomeEnabled = sAppPreferences.get(SettingsOptionsBottomSheet.KEY_MARKDOWN_HOME_ENABLED, true) val adapterExtra = Bundle() adapterExtra.putBoolean(SettingsOptionsBottomSheet.KEY_MARKDOWN_ENABLED, isMarkdownEnabled && isMarkdownHomeEnabled) adapterExtra.putInt(STORE_KEY_LINE_COUNT, sNoteItemLineCount) adapter = NoteAppAdapter(this, getSelectableRecyclerItemControllerList(sUIUseGridView, isTablet)) adapter.setExtra(adapterExtra) recyclerView = RecyclerViewBuilder(this) .setView(this, R.id.recycler_view) .setAdapter(adapter) .setLayoutManager(getLayoutManager(sUIUseGridView, isTablet)) .build() } override fun notifyThemeChange() { setSystemTheme() val containerLayout = findViewById<View>(R.id.container_layout) containerLayout.setBackgroundColor(getThemeColor()) val toolbarIconColor = sAppTheme.get(ThemeColorType.TOOLBAR_ICON); findViewById<ImageView>(R.id.back_button).setColorFilter(toolbarIconColor) findViewById<TextView>(R.id.toolbar_title).setTextColor(toolbarIconColor) } private fun getLayoutManager(isStaggeredView: Boolean, isTabletView: Boolean): RecyclerView.LayoutManager { if (isTabletView) { return StaggeredGridLayoutManager(2, GridLayout.VERTICAL) } return if (isStaggeredView) StaggeredGridLayoutManager(2, GridLayout.VERTICAL) else LinearLayoutManager(this) } }
gpl-3.0
28c2b0955a43d3bf6d3e8b23855e4ee2
37.11194
120
0.754455
4.495599
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/KotlinFirCompletionContributor.kt
1
6015
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.completion.* import com.intellij.openapi.components.service import com.intellij.patterns.PlatformPatterns import com.intellij.patterns.PsiJavaPatterns import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.idea.completion.context.* import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.context.FirExpressionNameReferencePositionContext import org.jetbrains.kotlin.idea.completion.context.FirPositionCompletionContextDetector import org.jetbrains.kotlin.idea.completion.context.FirTypeNameReferencePositionContext import org.jetbrains.kotlin.idea.completion.context.FirUnknownPositionContext import org.jetbrains.kotlin.idea.completion.contributors.* import org.jetbrains.kotlin.idea.completion.contributors.FirAnnotationCompletionContributor import org.jetbrains.kotlin.idea.completion.contributors.FirCallableCompletionContributor import org.jetbrains.kotlin.idea.completion.contributors.FirClassifierCompletionContributor import org.jetbrains.kotlin.idea.completion.contributors.complete import org.jetbrains.kotlin.idea.completion.weighers.Weighers import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.low.level.api.fir.util.originalKtFile import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtFile class KotlinFirCompletionContributor : CompletionContributor() { init { extend(CompletionType.BASIC, PlatformPatterns.psiElement(), KotlinFirCompletionProvider) } override fun beforeCompletion(context: CompletionInitializationContext) { val psiFile = context.file if (psiFile !is KtFile) return val identifierProviderService = service<CompletionDummyIdentifierProviderService>() correctPositionAndDummyIdentifier(identifierProviderService, context) } private fun correctPositionAndDummyIdentifier( identifierProviderService: CompletionDummyIdentifierProviderService, context: CompletionInitializationContext ) { val dummyIdentifierCorrected = identifierProviderService.correctPositionForStringTemplateEntry(context) if (dummyIdentifierCorrected) { return } context.dummyIdentifier = identifierProviderService.provideDummyIdentifier(context) } } private object KotlinFirCompletionProvider : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { @Suppress("NAME_SHADOWING") val parameters = KotlinFirCompletionParametersProvider.provide(parameters) if (shouldSuppressCompletion(parameters.ijParameters, result.prefixMatcher)) return val resultSet = createResultSet(parameters, result) val basicContext = FirBasicCompletionContext.createFromParameters(parameters, resultSet) ?: return recordOriginalFile(basicContext) val positionContext = FirPositionCompletionContextDetector.detect(basicContext) FirPositionCompletionContextDetector.analyseInContext(basicContext, positionContext) { complete(basicContext, positionContext) } } private fun KtAnalysisSession.complete( basicContext: FirBasicCompletionContext, positionContext: FirRawPositionCompletionContext, ) { val factory = FirCompletionContributorFactory(basicContext) with(Completions) { complete(factory, positionContext) } } private fun recordOriginalFile(basicCompletionContext: FirBasicCompletionContext) { val originalFile = basicCompletionContext.originalKtFile val fakeFile = basicCompletionContext.fakeKtFile fakeFile.originalKtFile = originalFile } private fun createResultSet(parameters: KotlinFirCompletionParameters, result: CompletionResultSet): CompletionResultSet { @Suppress("NAME_SHADOWING") var result = result.withRelevanceSorter(createSorter(parameters.ijParameters, result)) if (parameters is KotlinFirCompletionParameters.Corrected) { val replaced = parameters.ijParameters @Suppress("UnstableApiUsage", "DEPRECATION") val originalPrefix = CompletionData.findPrefixStatic(replaced.position, replaced.offset) result = result.withPrefixMatcher(originalPrefix) } return result } private fun createSorter(parameters: CompletionParameters, result: CompletionResultSet): CompletionSorter = CompletionSorter.defaultSorter(parameters, result.prefixMatcher) .let(Weighers::addWeighersToCompletionSorter) private val AFTER_NUMBER_LITERAL = PsiJavaPatterns.psiElement().afterLeafSkipping( PsiJavaPatterns.psiElement().withText(""), PsiJavaPatterns.psiElement().withElementType(PsiJavaPatterns.elementType().oneOf(KtTokens.FLOAT_LITERAL, KtTokens.INTEGER_LITERAL)) ) private val AFTER_INTEGER_LITERAL_AND_DOT = PsiJavaPatterns.psiElement().afterLeafSkipping( PsiJavaPatterns.psiElement().withText("."), PsiJavaPatterns.psiElement().withElementType(PsiJavaPatterns.elementType().oneOf(KtTokens.INTEGER_LITERAL)) ) private fun shouldSuppressCompletion(parameters: CompletionParameters, prefixMatcher: PrefixMatcher): Boolean { val position = parameters.position val invocationCount = parameters.invocationCount // no completion inside number literals if (AFTER_NUMBER_LITERAL.accepts(position)) return true // no completion auto-popup after integer and dot if (invocationCount == 0 && prefixMatcher.prefix.isEmpty() && AFTER_INTEGER_LITERAL_AND_DOT.accepts(position)) return true return false } }
apache-2.0
6319100d7eb6d51eeaa27c4b805145b3
46.738095
158
0.779385
5.423805
false
false
false
false
bjansen/pebble-intellij
src/main/kotlin/com/github/bjansen/intellij/pebble/psi/PebbleReferencesHelper.kt
1
5478
package com.github.bjansen.intellij.pebble.psi import com.github.bjansen.pebble.parser.PebbleLexer import com.github.bjansen.pebble.parser.PebbleParser import com.intellij.codeInsight.completion.JavaLookupElementBuilder import com.intellij.codeInsight.completion.util.ParenthesesInsertHandler import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.icons.AllIcons import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.search.searches.SuperMethodsSearch import com.intellij.psi.util.PropertyUtil import com.intellij.psi.util.PsiTreeUtil object PebbleReferencesHelper { private fun isOverride(method: PsiMethod) = SuperMethodsSearch.search(method, null, true, false).findFirst() != null fun buildPsiTypeLookups(type: PsiType?): Array<Any> { if (type is PsiClassType) { val clazz = type.resolve() ?: return emptyArray() val resolveResult = type.resolveGenerics() val lookups = arrayListOf<LookupElement>() lookups.addAll(clazz.allMethods .filter { it.hasModifierProperty(PsiModifier.PUBLIC) && !isOverride(it) && !it.isConstructor } .map { val prop = getPropertyNameAndType(it) if (prop != null) { LookupElementBuilder.create(prop.first) .withIcon(AllIcons.Nodes.Property) .withTypeText(prop.second.presentableText) } else { val handler = ParenthesesInsertHandler.getInstance(it.parameterList.parametersCount > 0) JavaLookupElementBuilder.forMethod(it, LambdaUtil.getSubstitutor(it, resolveResult)) .withInsertHandler(handler) } } ) lookups.addAll(clazz.allFields .filter { it.hasModifierProperty(PsiModifier.PUBLIC) } .map(JavaLookupElementBuilder::forField) ) return lookups.toTypedArray() } return emptyArray() } // TODO check signatures fun findMembersByName(clazz: PsiClass?, name: String, methodsOnly: Boolean = false): List<PsiElement> { if (clazz != null) { val capitalizedName = StringUtil.capitalizeWithJavaBeanConvention(name) for (prefix in listOf("get", "is", "has")) { for (method in clazz.findMethodsByName(prefix + capitalizedName, true)) { if (method.parameterList.parametersCount == 0) { return listOf(method); } } } val methods = clazz.allMethods.filter { it.name == name } if (methods.isNotEmpty()) { return methods } return if (methodsOnly) emptyList<PsiField>() else clazz.allFields.filter { it.hasModifierProperty(PsiModifier.PUBLIC) && it.name == name } } return emptyList() } private fun getPropertyNameAndType(method: PsiMethod): Pair<String, PsiType>? { val prop = PropertyUtil.getPropertyName(method) if (prop != null) { return Pair(prop, PropertyUtil.getPropertyType(method)!!) } val methodNameLength = method.name.length if (method.name.startsWith("has") && methodNameLength > "has".length && method.name[3].isUpperCase() && method.parameterList.parametersCount == 0) { return Pair(StringUtil.decapitalize(method.name.substring(3)), method.returnType!!) } return null } fun findQualifyingMember(psi: PsiElement): PsiElement? { val prevLeaf = PsiTreeUtil.prevVisibleLeaf(psi) if (prevLeaf != null && prevLeaf.node.elementType == PebbleParserDefinition.tokens[PebbleLexer.OP_MEMBER]) { val qualifier = prevLeaf.prevSibling if (qualifier != null) { val identifier = when (qualifier.node.elementType) { PebbleParserDefinition.rules[PebbleParser.RULE_function_call_expression] -> qualifier.firstChild PebbleParserDefinition.rules[PebbleParser.RULE_term] -> qualifier.firstChild else -> qualifier } fun resolveReference(): PsiElement? { if (identifier is PebbleLiteral) { return identifier } identifier.references.forEach { val resolved = it.resolve() if (resolved != null) { return resolved } } return null } val resolved = resolveReference() if (resolved is PebbleComment) { return PebbleComment.getImplicitVariable(resolved) } return resolved ?: qualifier.parent } } return null } }
mit
e0bfa15728f55b3d34d4603bb3ecc780
37.307692
116
0.553304
5.647423
false
false
false
false
GunoH/intellij-community
platform/testFramework/core/src/com/intellij/tool/HttpClient.kt
2
2967
// 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.tool import com.intellij.TestCaseLoader import org.apache.http.HttpResponse import org.apache.http.client.methods.HttpUriRequest import org.apache.http.impl.client.HttpClientBuilder import org.apache.http.impl.client.LaxRedirectStrategy import java.io.File import java.io.OutputStream import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.Semaphore import kotlin.io.path.createDirectories import kotlin.io.path.outputStream object HttpClient { private val locks = ConcurrentHashMap<String, Semaphore>() fun <Y> sendRequest(request: HttpUriRequest, processor: (HttpResponse) -> Y): Y { HttpClientBuilder.create() .setRedirectStrategy(LaxRedirectStrategy()) .build().use { client -> client.execute(request).use { response -> if (response.statusLine.statusCode != 200) { System.err.println( "Response from ${request.uri} finished with status code ${response.statusLine.statusCode}. ${response.statusLine}") } return processor(response) } } } fun download(request: HttpUriRequest, outFile: File, retries: Long = 3): Boolean = download(request, outFile.toPath(), retries) fun download(request: HttpUriRequest, outStream: OutputStream, retries: Long = 3): Boolean { val tempFile = File.createTempFile("downloaded_", ".txt") val result = download(request, tempFile, retries) try { tempFile.bufferedReader().use { reader -> outStream.bufferedWriter().use { writer -> reader.lines().forEach { writer.write(it) } } } return result } catch (_: Throwable) { return false } } /** * Downloading file from [url] to [outPath] with [retries]. * @return true - if successful, false - otherwise */ fun download(request: HttpUriRequest, outPath: Path, retries: Long = 3): Boolean { val lock = locks.getOrPut(outPath.toAbsolutePath().toString()) { Semaphore(1) } lock.acquire() var isSuccessful = false return try { if (TestCaseLoader.IS_VERBOSE_LOG_ENABLED) { println("Downloading ${request.uri} to $outPath") } withRetry(retries = retries) { sendRequest(request) { response -> require(response.statusLine.statusCode == 200) { "Failed to download ${request.uri}: $response" } outPath.parent.createDirectories() outPath.outputStream().buffered(10 * 1024 * 1024).use { stream -> response.entity?.writeTo(stream) } isSuccessful = true } } isSuccessful } finally { if (TestCaseLoader.IS_VERBOSE_LOG_ENABLED) { println("Downloading ${request.uri} ${if (isSuccessful) "is successful" else "failed"}") } lock.release() } } }
apache-2.0
2758717686e6ae994dae6223b8f25ade
31.615385
129
0.664307
4.3125
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/statistics/KotlinGradleFUSLogger.kt
1
4044
// 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.gradle.statistics import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.util.concurrency.AppExecutorUtil import org.jetbrains.kotlin.statistics.BuildSessionLogger import org.jetbrains.kotlin.statistics.BuildSessionLogger.Companion.STATISTICS_FOLDER_NAME import org.jetbrains.kotlin.statistics.fileloggers.MetricsContainer import java.io.File import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import kotlin.io.path.Path import kotlin.io.path.exists class KotlinGradleFUSLogger : StartupActivity.DumbAware, Runnable { override fun runActivity(project: Project) { AppExecutorUtil.getAppScheduledExecutorService() .scheduleWithFixedDelay(this, EXECUTION_DELAY_MIN, EXECUTION_DELAY_MIN, TimeUnit.MINUTES) } override fun run() { reportStatistics() } companion object { /** * Maximum amount of directories which were reported as gradle user dirs * These directories should be monitored for reported gradle statistics. */ private const val MAXIMUM_USER_DIRS = 10 /** * Delay between sequential checks of gradle statistics */ const val EXECUTION_DELAY_MIN = 60L /** * Property name used for persisting gradle user dirs */ private const val GRADLE_USER_DIRS_PROPERTY_NAME = "kotlin-gradle-user-dirs" private val isRunning = AtomicBoolean(false) fun reportStatistics() { if (isRunning.compareAndSet(false, true)) { try { for (gradleUserHome in gradleUserDirs) { BuildSessionLogger.listProfileFiles(File(gradleUserHome, STATISTICS_FOLDER_NAME))?.forEach { statisticFile -> var fileWasRead = true try { var previousEvent: MetricsContainer? = null fileWasRead = MetricsContainer.readFromFile(statisticFile) { metricContainer -> KotlinGradleFUSCollector.reportMetrics(metricContainer, previousEvent) previousEvent = metricContainer } } catch (e: Exception) { Logger.getInstance(KotlinGradleFUSCollector::class.java) .info("Failed to process file ${statisticFile.absolutePath}: ${e.message}", e) } finally { if (fileWasRead && !statisticFile.delete()) { Logger.getInstance(KotlinGradleFUSCollector::class.java) .warn("[FUS] Failed to delete file ${statisticFile.absolutePath}") } } } } } finally { isRunning.set(false) } } } private var gradleUserDirs: List<String> set(value) = PropertiesComponent.getInstance().setList( GRADLE_USER_DIRS_PROPERTY_NAME, value ) get() = PropertiesComponent.getInstance().getList(GRADLE_USER_DIRS_PROPERTY_NAME) ?: emptyList() fun populateGradleUserDir(path: String) { val currentState = gradleUserDirs if (path in currentState) return val result = ArrayList<String>() result.add(path) result.addAll(currentState) gradleUserDirs = result.filter { filePath -> Path(filePath).exists() }.take(MAXIMUM_USER_DIRS) } } }
apache-2.0
0b1a7a97a8ff366181829f873172d5fc
40.690722
133
0.595945
5.593361
false
false
false
false
smmribeiro/intellij-community
platform/lang-api/src/com/intellij/codeInsight/hints/InlayHintsSettings.kt
1
6660
// 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.codeInsight.hints import com.intellij.configurationStore.deserializeInto import com.intellij.configurationStore.serialize import com.intellij.lang.Language import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.SettingsCategory import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.messages.Topic import org.jdom.Element import java.util.* @State(name = "InlayHintsSettings", storages = [Storage("editor.xml")], category = SettingsCategory.CODE) class InlayHintsSettings : PersistentStateComponent<InlayHintsSettings.State> { companion object { @JvmStatic fun instance(): InlayHintsSettings { return ApplicationManager.getApplication().getService(InlayHintsSettings::class.java) } /** * Inlay hints settings changed. */ @Topic.AppLevel @JvmStatic val INLAY_SETTINGS_CHANGED: Topic<SettingsListener> = Topic(SettingsListener::class.java, Topic.BroadcastDirection.TO_DIRECT_CHILDREN) } private val listener: SettingsListener get() = ApplicationManager.getApplication().messageBus.syncPublisher(INLAY_SETTINGS_CHANGED) private var myState = State() private val lock = Any() class State { var disabledHintProviderIds: TreeSet<String> = sortedSetOf() // We can't store Map<String, Any> directly, because values deserialized as Object var settingsMapElement = Element("settingsMapElement") var lastViewedProviderKeyId: String? = null var isEnabled: Boolean = true var disabledLanguages: TreeSet<String> = sortedSetOf() } private val myCachedSettingsMap: MutableMap<String, Any> = hashMapOf() fun changeHintTypeStatus(key: SettingsKey<*>, language: Language, enable: Boolean) { synchronized(lock) { val id = key.getFullId(language) if (enable) { myState.disabledHintProviderIds.remove(id) } else { myState.disabledHintProviderIds.add(id) } } listener.settingsChanged() } fun setHintsEnabledForLanguage(language: Language, enabled: Boolean) { val settingsChanged = synchronized(lock) { val id = language.id if (enabled) { myState.disabledLanguages.remove(id) } else { myState.disabledLanguages.add(id) } } if (settingsChanged) { listener.languageStatusChanged() listener.settingsChanged() } } fun saveLastViewedProviderId(providerId: String) = synchronized(lock) { myState.lastViewedProviderKeyId = providerId } fun getLastViewedProviderId() : String? { return myState.lastViewedProviderKeyId } fun setEnabledGlobally(enabled: Boolean) { val settingsChanged = synchronized(lock) { if (myState.isEnabled != enabled) { myState.isEnabled = enabled listener.globalEnabledStatusChanged(enabled) true } else { false } } if (settingsChanged) { listener.settingsChanged() } } fun hintsEnabledGlobally() : Boolean = synchronized(lock) { return myState.isEnabled } /** * @param createSettings is a setting, that was obtained from createSettings method of provider */ fun <T: Any> findSettings(key: SettingsKey<T>, language: Language, createSettings: ()->T): T = synchronized(lock) { val fullId = key.getFullId(language) return getSettingCached(fullId, createSettings) } fun <T: Any> storeSettings(key: SettingsKey<T>, language: Language, value: T) { synchronized(lock){ val fullId = key.getFullId(language) myCachedSettingsMap[fullId] = value as Any val element = myState.settingsMapElement.clone() element.removeChild(fullId) val serialized = serialize(value) if (serialized != null) { val storeElement = Element(fullId) val wrappedSettingsElement = storeElement.addContent(serialized) myState.settingsMapElement = element.addContent(wrappedSettingsElement) element.sortAttributes(compareBy { it.name }) } else { myState.settingsMapElement = element } } listener.settingsChanged() } fun hintsEnabled(language: Language) : Boolean = synchronized(lock) { return language.id !in myState.disabledLanguages } fun hintsShouldBeShown(language: Language) : Boolean = synchronized(lock) { if (!hintsEnabledGlobally()) return false return hintsEnabled(language) } fun hintsEnabled(key: SettingsKey<*>, language: Language) : Boolean = synchronized(lock) { var lang: Language? = language while (lang != null) { if (key.getFullId(lang) in myState.disabledHintProviderIds) { return false } lang = lang.baseLanguage } return true } fun hintsShouldBeShown(key: SettingsKey<*>, language: Language): Boolean = synchronized(lock) { return hintsEnabledGlobally() && hintsEnabled(language) && hintsEnabled(key, language) } override fun getState(): State = synchronized(lock) { return myState } override fun loadState(state: State) = synchronized(lock) { val elementChanged = myState.settingsMapElement != state.settingsMapElement if (elementChanged) { myCachedSettingsMap.clear() } myState = state } // may return parameter settings object or cached object private fun <T : Any> getSettingCached(id: String, settings: ()->T): T { @Suppress("UNCHECKED_CAST") val cachedValue = myCachedSettingsMap[id] as T? if (cachedValue != null) return cachedValue return getSettingNotCached(id, settings()) } private fun <T : Any> getSettingNotCached(id: String, settings: T): T { val state = myState.settingsMapElement val settingsElement = state.getChild(id) ?: return settings val settingsElementChildren= settingsElement.children if (settingsElementChildren.isEmpty()) return settings settingsElementChildren.first().deserializeInto(settings) myCachedSettingsMap[id] = settings return settings } interface SettingsListener { /** * @param newEnabled whether inlay hints are globally switched on or off now */ fun globalEnabledStatusChanged(newEnabled: Boolean) {} /** * Called, when hints are enabled/disabled for some language */ fun languageStatusChanged() {} /** * Called when any settings in inlay hints were changed */ fun settingsChanged() {} } }
apache-2.0
975580eafa2607ec958a8dd6a619b6bf
31.019231
140
0.705706
4.720057
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/slicer/outflow/overridingPropertyResult.kt
13
237
// FLOW: OUT open class A { open val foo = 1 } open class B : A() { override val foo = <caret>2 } class C : B() { override val foo = 3 } fun test(a: A, b: B, c: C) { val x = a.foo val y = b.foo val z = c.foo }
apache-2.0
fc24e7dbe69a48acbc368a8f129893bb
11.526316
31
0.49789
2.494737
false
true
false
false
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/ui/player/FollowingView.kt
1
1812
/* * * * 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.player import android.os.Bundle import com.sinyuk.fanfou.R import com.sinyuk.fanfou.base.AbstractFragment import com.sinyuk.fanfou.di.Injectable import com.sinyuk.fanfou.domain.USERS_FOLLOWERS import kotlinx.android.synthetic.main.friends_view.* /** * Created by sinyuk on 2018/1/10. * */ class FollowingView : AbstractFragment(), Injectable { companion object { fun newInstance(uniqueId: String? = null) = FollowingView().apply { arguments = Bundle().apply { putString("uniqueId", uniqueId) } } } override fun layoutId() = R.layout.following_view override fun onLazyInitView(savedInstanceState: Bundle?) { super.onLazyInitView(savedInstanceState) navBack.setOnClickListener { pop() } postFanfouButton.setOnClickListener { } if (findChildFragment(PlayerListView::class.java) == null) { loadRootFragment(R.id.followingListContainer, PlayerListView.newInstance(USERS_FOLLOWERS, arguments!!.getString("uniqueId"))) } else { showHideFragment(findChildFragment(PlayerListView::class.java)) } } }
mit
73947f87d4bce294ef6a1017e421b5da
32.574074
137
0.693709
4.06278
false
false
false
false
ItsPriyesh/HexaTime
app/src/main/kotlin/com/priyesh/hexatime/ui/main/SettingsActivity.kt
1
3830
/* * Copyright 2015 Priyesh Patel * * 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.priyesh.hexatime.ui.main import android.content.Intent import android.content.SharedPreferences import android.graphics.drawable.ColorDrawable import android.graphics.drawable.TransitionDrawable import android.os.Bundle import android.os.Handler import android.os.Looper import android.preference.PreferenceManager import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import com.priyesh.hexatime.R import com.priyesh.hexatime.api import com.priyesh.hexatime.core.Background import com.priyesh.hexatime.core.Clock import com.priyesh.hexatime.darkenColor import kotlin.properties.Delegates public class SettingsActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener { val toolbar: Toolbar by lazy { findViewById(R.id.toolbar) as Toolbar } val clock: Clock by lazy { Clock(this) } val background: Background by lazy { Background(clock) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) setSupportActionBar(toolbar) PreferenceManager.getDefaultSharedPreferences(baseContext) .registerOnSharedPreferenceChangeListener(this) fragmentManager.beginTransaction() .add(R.id.container, SettingsFragment()) .commit() val handler = Handler(Looper.getMainLooper()) var colorOld = ContextCompat.getColor(this, R.color.primary) val updateToolbar = object : Runnable { override fun run(): Unit { clock.updateCalendar() val start = colorOld val end = background.getColor() colorOld = end updateToolbarColor(start, end) if (api(21)) updateStatusBarColor() handler.postDelayed(this, 1000) } } handler.postDelayed(updateToolbar, 1000) } private fun updateToolbarColor(start: Int, end: Int) { val transition = TransitionDrawable(arrayOf(ColorDrawable(start), ColorDrawable(end))) if (api(16)) toolbar.background = transition else toolbar.setBackgroundDrawable(transition); transition.startTransition(300) } private fun updateStatusBarColor() { val statusBarColor = darkenColor(background.getColor(), 0.8f) window.statusBarColor = statusBarColor } private fun goHome() { val home = Intent(Intent.ACTION_MAIN) home.addCategory(Intent.CATEGORY_HOME) home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(home) } override fun onSharedPreferenceChanged(prefs: SharedPreferences, key: String) { background.onPreferenceChange(prefs, key) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_settings, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.getItemId() == R.id.action_done) goHome() return super<AppCompatActivity>.onOptionsItemSelected(item) } }
apache-2.0
72793861d16dd46a118cd334b78a7b97
34.803738
105
0.710444
4.653706
false
false
false
false
OlegAndreych/work_calendar
src/main/kotlin/org/andreych/workcalendar/restservice/RestController.kt
1
2006
package org.andreych.workcalendar.restservice import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.andreych.workcalendar.service.CalendarService import org.springframework.context.annotation.DependsOn import org.springframework.core.io.ByteArrayResource import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.context.request.async.DeferredResult @RestController @DependsOn("calendarDataUpdater") class RestController(private val calendarService: CalendarService) { companion object { private val headers = HttpHeaders() init { headers.add("Cache-Control", "no-cache, no-store, must-revalidate") headers.add("Pragma", "no-cache") headers.add("Expires", "0") headers.add("Content-Encoding", "gzip") headers.add("Content-Disposition", "attachment; filename=\"calendar.ics\"") } } @GetMapping("/") fun workCalendar(): DeferredResult<ResponseEntity<ByteArrayResource>> { val deferredResult = DeferredResult<ResponseEntity<ByteArrayResource>>() CoroutineScope(Dispatchers.Default).launch { val bytes: ByteArray? = calendarService.getCalendarBytes() val responseEntity = if (bytes != null) { ResponseEntity .ok() .headers(headers) .contentType(MediaType.parseMediaType("text/calendar")) .body(ByteArrayResource(bytes)) } else { ResponseEntity .notFound() .build() } deferredResult.setResult(responseEntity) } return deferredResult } }
apache-2.0
45beb7aa6beed5461a363ff458081fcd
35.490909
87
0.665005
5.170103
false
false
false
false
sg26565/hott-transmitter-config
mz32-Downloader/src/main/kotlin/de/treichels/hott/mz32/CheckComboBox.kt
1
2241
package de.treichels.hott.mz32 import javafx.beans.property.SimpleBooleanProperty import javafx.collections.ObservableList import javafx.scene.control.ComboBox import javafx.scene.control.ListCell import javafx.scene.control.cell.CheckBoxListCell import javafx.scene.control.skin.ComboBoxListViewSkin import javafx.util.Callback import tornadofx.* /** * A combo box that displays a list of check boxes which can be selected individually. */ class CheckComboBox<T> : ComboBox<T>() { /** all items of the combo box along with a BooleanProperty that can be observed to render the check boxes. */ private val selections = mutableMapOf<T, SimpleBooleanProperty>() /** an ObservableList containing all selected items. */ val selectedItems: ObservableList<T> = mutableListOf<T>().asObservable() init { // disable standard rendering of combo box value buttonCell = ListCell<T>() // re-use default skin skin = ComboBoxListViewSkin(this).apply { isHideOnClick = false } // custom cell factory cellFactory = Callback { CheckBoxListCell<T>(Callback(::getSelection)) } // render combo box value selectedItems.onChange { updateText() } runLater { updateText() } } /** update button text on change */ private fun updateText() { buttonCell.text = selectedItems.sorted().joinToString() } /** * Manage selections * * Gets the observable state of an item from the internal map or adds it if it does not already exist. A change * listener will maintain the selectedItems list according to the state of the check box. */ private fun getSelection(item: T) = selections.getOrPut(item) { SimpleBooleanProperty(false).apply { // add a change listener to update selected values addListener { _, _, newValue -> if (newValue && !selectedItems.contains(item)) selectedItems.add(item) if (!newValue && selectedItems.contains(item)) selectedItems.remove(item) } } } /** Select (check) and item in the combo box. */ fun selectItem(item: T) { if (items.contains(item)) getSelection(item).value = true } }
lgpl-3.0
4fd30b362e1e5ab9e2bab9eb37024a7a
35.145161
115
0.676037
4.850649
false
false
false
false
sg26565/hott-transmitter-config
SaveModels/src/main/kotlin/de/treichels/hott/SaveModels.kt
1
3653
package de.treichels.hott import tornadofx.launch import tornadofx.App import tornadofx.* import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.scene.layout.VBox import javafx.scene.paint.Color import java.time.LocalDate import java.time.Period fun main(args: Array<String>) { launch<SaveModels>(args) } // Example from https://github.com/edvin/tornadofx/wiki/Type-Safe-Builders // https://edvin.gitbooks.io/tornadofx-guide/content/part1/1_Why_TornadoFX.html // https://stackoverflow.com/questions/50976849/invoke-function-when-item-in-combobox-is-selected-tornadofx class SaveModels : App(MyView::class) class MyView : View() { override val root = VBox() class Person(id: Int, name: String, birthday: LocalDate) { private var id: Int by property<Int>() fun idProperty() = getProperty(Person::id) private var name: String by property<String>() fun nameProperty() = getProperty(Person::name) private var birthday: LocalDate by property<LocalDate>() fun birthdayProperty() = getProperty(Person::birthday) val age: Int get() = Period.between(birthday, LocalDate.now()).years init { this.id = id this.name = name this.birthday = birthday } } private val texasCities = FXCollections.observableArrayList( "Austin", "Dallas", "Midland", "San Antonio", "Fort Worth" ) private val selectedCity = SimpleStringProperty("Hugo") private val persons = FXCollections.observableArrayList( Person(1, "Samantha Stuart", LocalDate.of(1981, 12, 4)), Person(2, "Tom Marks", LocalDate.of(2011, 1, 23)), Person(3, "Stuart Gilles", LocalDate.of(1989, 5, 23)), Person(4, "Nicole Williams", LocalDate.of(1998, 8, 11)) ) init { with(root) { borderpane { top = hbox { togglebutton { val stateText = selectedProperty().stringBinding { if (it == true) "ON" else "OFF" } textProperty().bind(stateText) setOnAction { println("Button 0 Pressed") } } button("Button 1") { setOnAction { println("Button 1 Pressed") } hboxConstraints { marginRight = 10.0 marginLeft = 10.0 } } button("Button 2").setOnAction { println("Button 2 Pressed") } combobox(selectedCity, texasCities) selectedCity.onChange { println("City changed to: $it") } } center = tableview(persons) { column("ID", Person::idProperty) column("Name", Person::nameProperty) column("Birthday", Person::birthdayProperty) readonlyColumn("Age", Person::age).cellFormat { text = it.toString() style { if (it < 18) { backgroundColor += c("#8b0000") textFill = Color.WHITE } } } } } } } }
lgpl-3.0
f47f5584bade9cc03a58d26cba7bc5a2
32.833333
107
0.502327
5.010974
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/note_editor/cells/viewmodel/ExtendedTextPropertyCellViewModel.kt
1
5236
package com.ivanovsky.passnotes.presentation.note_editor.cells.viewmodel import androidx.annotation.VisibleForTesting import androidx.lifecycle.MutableLiveData import com.ivanovsky.passnotes.R import com.ivanovsky.passnotes.data.entity.Property import com.ivanovsky.passnotes.domain.ResourceProvider import com.ivanovsky.passnotes.presentation.core.BaseCellViewModel import com.ivanovsky.passnotes.presentation.core.binding.OnTextChangeListener import com.ivanovsky.passnotes.presentation.core.event.Event.Companion.toEvent import com.ivanovsky.passnotes.presentation.core.event.EventProvider import com.ivanovsky.passnotes.presentation.note_editor.cells.model.ExtendedTextPropertyCellModel import com.ivanovsky.passnotes.presentation.note_editor.view.TextTransformationMethod import com.ivanovsky.passnotes.util.StringUtils.EMPTY import com.ivanovsky.passnotes.util.reset class ExtendedTextPropertyCellViewModel( override val model: ExtendedTextPropertyCellModel, private val eventProvider: EventProvider, private val resourceProvider: ResourceProvider ) : BaseCellViewModel(model), PropertyViewModel { val primaryText = MutableLiveData( if (model.isCollapsed) { model.value } else { model.name } ) val secondaryText = MutableLiveData(model.value) val isCollapsed = MutableLiveData(model.isCollapsed) val isProtected = MutableLiveData(model.isProtected) val primaryError = MutableLiveData<String?>(null) val primaryHint = MutableLiveData<String>( if (model.isCollapsed) { model.name } else { resourceProvider.getString(R.string.field_name) } ) val secondaryHint = MutableLiveData<String>(resourceProvider.getString(R.string.field_value)) val primaryTextListener = object : OnTextChangeListener { override fun onTextChanged(text: String) { primaryError.reset() } } val primaryTransformationMethod = MutableLiveData( obtainTextTransformationMethod(model.isProtected && model.isCollapsed) ) val secondaryTransformationMethod = MutableLiveData( obtainTextTransformationMethod(model.isProtected) ) init { isProtected.observeForever { isProtected -> secondaryTransformationMethod.value = obtainTextTransformationMethod(isProtected) primaryTransformationMethod.value = obtainTextTransformationMethod(isProtected && isCollapsedInternal()) } } override fun createProperty(): Property { val (name, value) = getNameAndValue() return Property( type = null, name = name, value = value, isProtected = isProtectedInternal() ) } override fun isDataValid(): Boolean { val (name, value) = getNameAndValue() return value.isEmpty() || name.isNotEmpty() } override fun displayError() { val (name, value) = getNameAndValue() if (name.isEmpty() && value.isNotEmpty()) { primaryError.value = resourceProvider.getString(R.string.empty_field_name_message) } } fun onExpandButtonClicked() { if (!isCollapsedInternal() && !isAbleToCollapse()) { primaryError.value = resourceProvider.getString(R.string.empty_field_name_message) return } val (name, value) = getNameAndValue() isCollapsed.value = isCollapsedInternal().not() if (isCollapsedInternal()) { primaryText.value = value primaryHint.value = name } else { primaryText.value = name primaryHint.value = resourceProvider.getString(R.string.field_name) secondaryText.value = value } secondaryTransformationMethod.value = obtainTextTransformationMethod(isProtectedInternal()) primaryTransformationMethod.value = obtainTextTransformationMethod(isProtectedInternal() && isCollapsedInternal()) } fun onRemoveButtonClicked() { eventProvider.send((REMOVE_EVENT to model.id).toEvent()) } @VisibleForTesting fun isAbleToCollapse(): Boolean { return isCollapsedInternal() || getPrimaryText().isNotEmpty() } @VisibleForTesting fun getNameAndValue(): Pair<String, String> { return if (isCollapsedInternal()) { Pair(getPrimaryHint(), getPrimaryText()) } else { Pair(getPrimaryText(), getSecondaryText()) } } private fun isCollapsedInternal() = isCollapsed.value ?: false private fun isProtectedInternal() = isProtected.value ?: false private fun getPrimaryText() = primaryText.value?.trim() ?: EMPTY private fun getSecondaryText() = secondaryText.value?.trim() ?: EMPTY private fun getPrimaryHint() = primaryHint.value ?: EMPTY private fun obtainTextTransformationMethod(isProtected: Boolean): TextTransformationMethod { return if (isProtected) { TextTransformationMethod.PASSWORD } else { TextTransformationMethod.PLANE_TEXT } } companion object { val REMOVE_EVENT = ExtendedTextPropertyCellModel::class.simpleName + "_removeEvent" } }
gpl-2.0
b0ccbd32159f5424d6e7180320b79298
33.913333
122
0.693659
5.093385
false
false
false
false
breadwallet/breadwallet-android
app-core/src/main/java/com/breadwallet/tools/sqlite/RatesDataSource.kt
1
9624
/** * BreadWallet * * Created by Mihail Gutan <[email protected]> on 9/25/15. * Copyright (c) 2016 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.tools.sqlite import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.util.Log import com.breadwallet.breadbox.BreadBox import com.breadwallet.legacy.presenter.entities.CurrencyEntity import com.breadwallet.tools.manager.BRReportsManager import com.breadwallet.tools.util.BRConstants import com.breadwallet.tools.util.Utils import org.kodein.di.KodeinAware import org.kodein.di.android.closestKodein import org.kodein.di.erased.instance import java.util.ArrayList import java.util.Locale class RatesDataSource private constructor(context: Context) : BRDataSourceInterface, KodeinAware { // Database fields private var database: SQLiteDatabase? = null private val dbHelper = BRSQLiteHelper.getInstance(context) private val allColumns = arrayOf( BRSQLiteHelper.CURRENCY_CODE, BRSQLiteHelper.CURRENCY_NAME, BRSQLiteHelper.CURRENCY_RATE, BRSQLiteHelper.CURRENCY_ISO ) override val kodein by closestKodein { context } private val breadBox by instance<BreadBox>() fun putCurrencies(currencyEntities: Collection<CurrencyEntity>): Boolean { if (currencyEntities.isEmpty()) { Log.e(TAG, "putCurrencies: failed: $currencyEntities") return false } return try { database = openDatabase() database!!.beginTransaction() var failed = 0 for (c in currencyEntities) { val code = c.code.toUpperCase(Locale.ROOT) val iso = c.iso.toUpperCase(Locale.ROOT) val values = ContentValues() if (Utils.isNullOrEmpty(code) || c.rate <= 0) { failed++ continue } values.put(BRSQLiteHelper.CURRENCY_CODE, code) values.put(BRSQLiteHelper.CURRENCY_NAME, c.name) values.put(BRSQLiteHelper.CURRENCY_RATE, c.rate) values.put(BRSQLiteHelper.CURRENCY_ISO, iso) database!!.insertWithOnConflict( BRSQLiteHelper.CURRENCY_TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE ) } if (failed != 0) { Log.e(TAG, "putCurrencies: failed:$failed") } database!!.setTransactionSuccessful() true } catch (ex: Exception) { Log.e(TAG, "putCurrencies: failed: ", ex) BRReportsManager.reportBug(ex) //Error in between database transaction false } finally { database!!.endTransaction() closeDatabase() } } fun deleteAllCurrencies(app: Context?, iso: String) { try { database = openDatabase() database!!.delete( BRSQLiteHelper.CURRENCY_TABLE_NAME, BRSQLiteHelper.CURRENCY_ISO + " = ?", arrayOf(iso.toUpperCase(Locale.ROOT)) ) } finally { closeDatabase() } } fun getAllCurrencies(iso: String): List<CurrencyEntity> { val currencies: MutableList<CurrencyEntity> = ArrayList() var cursor: Cursor? = null try { database = openDatabase() cursor = database!!.query( BRSQLiteHelper.CURRENCY_TABLE_NAME, allColumns, BRSQLiteHelper.CURRENCY_ISO + " = ? COLLATE NOCASE", arrayOf(iso.toUpperCase(Locale.ROOT)), null, null, "\'" + BRSQLiteHelper.CURRENCY_CODE + "\'" ) cursor.moveToFirst() val system = breadBox.getSystemUnsafe() while (!cursor.isAfterLast) { val curEntity = cursorToCurrency(cursor) val isCrypto = system?.wallets?.none { it.currency.code.equals(curEntity.code, true) } ?: true if (!isCrypto) { currencies.add(curEntity) } cursor.moveToNext() } // make sure to close the cursor } finally { cursor?.close() closeDatabase() } Log.e(TAG, "getAllCurrencies: size:" + currencies.size) return currencies } fun getAllCurrencyCodes(app: Context?, iso: String): List<String> { val ISOs: MutableList<String> = ArrayList() var cursor: Cursor? = null try { database = openDatabase() cursor = database!!.query( BRSQLiteHelper.CURRENCY_TABLE_NAME, allColumns, BRSQLiteHelper.CURRENCY_ISO + " = ? COLLATE NOCASE", arrayOf(iso.toUpperCase(Locale.ROOT)), null, null, null ) cursor.moveToFirst() while (!cursor.isAfterLast) { val curEntity = cursorToCurrency(cursor) ISOs.add(curEntity.code) cursor.moveToNext() } // make sure to close the cursor } finally { cursor?.close() closeDatabase() } return ISOs } @Synchronized fun getCurrencyByCode(iso: String, code: String): CurrencyEntity? { var cursor: Cursor? = null var result: CurrencyEntity? = null return try { database = openDatabase() cursor = database!!.query( BRSQLiteHelper.CURRENCY_TABLE_NAME, allColumns, BRSQLiteHelper.CURRENCY_CODE + " = ? AND " + BRSQLiteHelper.CURRENCY_ISO + " = ? COLLATE NOCASE", arrayOf(code.toUpperCase(Locale.ROOT), iso.toUpperCase(Locale.ROOT)), null, null, null ) cursor.moveToNext() if (!cursor.isAfterLast) { result = cursorToCurrency(cursor) } result } finally { cursor?.close() closeDatabase() } } private fun printTest() { var cursor: Cursor? = null try { database = openDatabase() val builder = StringBuilder() cursor = database!!.query( BRSQLiteHelper.CURRENCY_TABLE_NAME, allColumns, null, null, null, null, null ) builder.append("Total: ${cursor.count}") cursor.moveToFirst() while (!cursor.isAfterLast) { val ent = cursorToCurrency(cursor) builder.append("Name: ${ent.name}, code: ${ent.code}, rate: ${ent.rate}, iso: ${ent.iso}") cursor.moveToNext() } Log.e(TAG, "printTest: $builder") } finally { cursor?.close() closeDatabase() } } private fun cursorToCurrency(cursor: Cursor?): CurrencyEntity { return CurrencyEntity(cursor!!.getString(0), cursor.getString(1), cursor.getFloat(2), cursor.getString(3)) } override fun openDatabase(): SQLiteDatabase { // if (mOpenCounter.incrementAndGet() == 1) { // Opening new database if (database == null || !database!!.isOpen) database = dbHelper.writableDatabase dbHelper.setWriteAheadLoggingEnabled(BRConstants.WRITE_AHEAD_LOGGING) // } // Log.d("Database open counter: ", String.valueOf(mOpenCounter.get())); return database!! } override fun closeDatabase() { // if (mOpenCounter.decrementAndGet() == 0) { // // Closing database // database.close(); //onChanged // } // Log.d("Database open counter: " , String.valueOf(mOpenCounter.get())); } companion object { private val TAG = RatesDataSource::class.java.name private var instance: RatesDataSource? = null @JvmStatic @Synchronized fun getInstance(context: Context): RatesDataSource { if (instance == null) { synchronized(this) { if (instance == null) { instance = RatesDataSource(context) } } } return instance!! } } }
mit
95c57f3dcb8f9989e7b5358cdf7df854
35.316981
114
0.576268
4.853253
false
false
false
false
seventhroot/elysium
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/command/listchatchannels/ListChatChannelsCommand.kt
1
10130
/* * Copyright 2020 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.chat.bukkit.command.listchatchannels import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelProvider import com.rpkit.core.bukkit.util.closestChatColor import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import net.md_5.bungee.api.chat.BaseComponent import net.md_5.bungee.api.chat.ClickEvent import net.md_5.bungee.api.chat.HoverEvent import net.md_5.bungee.api.chat.TextComponent import org.bukkit.ChatColor import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player import java.util.regex.Pattern /** * List chat channels command. * Lists available chat channels. */ class ListChatChannelsCommand(private val plugin: RPKChatBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender.hasPermission("rpkit.chat.command.listchatchannels")) { if (sender is Player) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile != null) { sender.sendMessage(plugin.messages["listchatchannels-title"]) plugin.core.serviceManager.getServiceProvider(RPKChatChannelProvider::class).chatChannels.forEach { chatChannel -> val messageComponents = mutableListOf<BaseComponent>() val pattern = Pattern.compile("(\\\$channel)|(\\\$mute)|(${ChatColor.COLOR_CHAR}[0-9a-f])") val template = plugin.messages["listchatchannels-item", mapOf( Pair("color", chatChannel.color.closestChatColor().toString()) )] val matcher = pattern.matcher(template) var chatColor: ChatColor? = null var chatFormat: ChatColor? = null var index = 0 while (matcher.find()) { if (index != matcher.start()) { val textComponent = TextComponent(template.substring(index, matcher.start())) if (chatColor != null) { textComponent.color = chatColor.asBungee() } if (chatFormat != null) { textComponent.isObfuscated = chatFormat == ChatColor.MAGIC textComponent.isBold = chatFormat == ChatColor.BOLD textComponent.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH textComponent.isUnderlined = chatFormat == ChatColor.UNDERLINE textComponent.isItalic = chatFormat == ChatColor.ITALIC } messageComponents.add(textComponent) } if (matcher.group() == "\$channel") { val chatChannelComponent = TextComponent(chatChannel.name) chatChannelComponent.clickEvent = ClickEvent(ClickEvent.Action.RUN_COMMAND, "/chatchannel ${chatChannel.name}") chatChannelComponent.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, arrayOf(TextComponent("Click to talk in ${chatChannel.name}"))) if (chatColor != null) { chatChannelComponent.color = chatColor.asBungee() } if (chatFormat != null) { chatChannelComponent.isObfuscated = chatFormat == ChatColor.MAGIC chatChannelComponent.isBold = chatFormat == ChatColor.BOLD chatChannelComponent.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH chatChannelComponent.isUnderlined = chatFormat == ChatColor.UNDERLINE chatChannelComponent.isItalic = chatFormat == ChatColor.ITALIC } messageComponents.add(chatChannelComponent) } else if (matcher.group() == "\$mute") { if (chatChannel.listenerMinecraftProfiles.any { listenerMinecraftProfile -> listenerMinecraftProfile.id == minecraftProfile.id }) { val muteComponent = TextComponent("Mute") muteComponent.clickEvent = ClickEvent(ClickEvent.Action.RUN_COMMAND, "/mute ${chatChannel.name}") muteComponent.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, arrayOf(TextComponent("Click to mute ${chatChannel.name}"))) if (chatColor != null) { muteComponent.color = chatColor.asBungee() } if (chatFormat != null) { muteComponent.isObfuscated = chatFormat == ChatColor.MAGIC muteComponent.isBold = chatFormat == ChatColor.BOLD muteComponent.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH muteComponent.isUnderlined = chatFormat == ChatColor.UNDERLINE muteComponent.isItalic = chatFormat == ChatColor.ITALIC } messageComponents.add(muteComponent) } else { val unmuteComponent = TextComponent("Unmute") unmuteComponent.clickEvent = ClickEvent(ClickEvent.Action.RUN_COMMAND, "/unmute ${chatChannel.name}") unmuteComponent.hoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, arrayOf(TextComponent("Click to unmute ${chatChannel.name}"))) if (chatColor != null) { unmuteComponent.color = chatColor.asBungee() } if (chatFormat != null) { unmuteComponent.isObfuscated = chatFormat == ChatColor.MAGIC unmuteComponent.isBold = chatFormat == ChatColor.BOLD unmuteComponent.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH unmuteComponent.isUnderlined = chatFormat == ChatColor.UNDERLINE unmuteComponent.isItalic = chatFormat == ChatColor.ITALIC } messageComponents.add(unmuteComponent) } } else { val colorOrFormat = ChatColor.getByChar(matcher.group().drop(1)) if (colorOrFormat?.isColor == true) { chatColor = colorOrFormat chatFormat = null } if (colorOrFormat?.isFormat == true) { chatFormat = colorOrFormat } if (colorOrFormat == ChatColor.RESET) { chatColor = null chatFormat = null } } index = matcher.end() } val textComponent = TextComponent(template.substring(index, template.length)) if (chatColor != null) { textComponent.color = chatColor.asBungee() } if (chatFormat != null) { textComponent.isObfuscated = chatFormat == ChatColor.MAGIC textComponent.isBold = chatFormat == ChatColor.BOLD textComponent.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH textComponent.isUnderlined = chatFormat == ChatColor.UNDERLINE textComponent.isItalic = chatFormat == ChatColor.ITALIC } messageComponents.add(textComponent) sender.spigot().sendMessage(*messageComponents.toTypedArray()) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } } else { sender.sendMessage(plugin.messages["no-permission-listchatchannels"]) } return true } }
apache-2.0
23fb9aba30f612c606bc070eceef79bb
62.31875
169
0.514413
6.721964
false
false
false
false
Adven27/Exam
exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/builder/JSONSupport.kt
1
6461
package io.github.adven27.concordion.extensions.exam.db.builder import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import mu.KLogging import org.dbunit.dataset.AbstractDataSet import org.dbunit.dataset.Column import org.dbunit.dataset.DataSetException import org.dbunit.dataset.DefaultTable import org.dbunit.dataset.DefaultTableIterator import org.dbunit.dataset.DefaultTableMetaData import org.dbunit.dataset.IDataSet import org.dbunit.dataset.ITable import org.dbunit.dataset.ITableIterator import org.dbunit.dataset.ITableMetaData import org.dbunit.dataset.datatype.DataType.UNKNOWN import org.dbunit.dataset.stream.DataSetProducerAdapter import org.dbunit.dataset.stream.IDataSetConsumer import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.io.OutputStreamWriter import java.nio.charset.StandardCharsets class JSONWriter(private val dataSet: IDataSet, outputStream: OutputStream?) : IDataSetConsumer { private val out: OutputStreamWriter = OutputStreamWriter(outputStream, StandardCharsets.UTF_8) private var metaData: ITableMetaData? = null private var tableCount = 0 private var rowCount = 0 @Throws(DataSetException::class) override fun startDataSet() { try { tableCount = 0 out.write("{$NEW_LINE") } catch (e: IOException) { logger.warn("Could not start dataset.", e) } } @Throws(DataSetException::class) override fun endDataSet() { try { out.write("}") out.flush() } catch (e: IOException) { logger.warn("Could not end dataset.", e) } } @Throws(DataSetException::class) override fun startTable(metaData: ITableMetaData) { this.metaData = metaData rowCount = 0 try { out.write(DOUBLE_SPACES + "\"" + metaData.tableName + "\": [" + NEW_LINE) } catch (e: IOException) { logger.warn("Could not start table.", e) } } @Throws(DataSetException::class) override fun endTable() { try { tableCount++ if (dataSet.tableNames.size == tableCount) { out.write("$DOUBLE_SPACES]$NEW_LINE") } else { out.write("$DOUBLE_SPACES],$NEW_LINE") } } catch (e: IOException) { logger.warn("Could end table.", e) } } override fun row(values: Array<Any?>) { rowCount++ try { out.write("$FOUR_SPACES{$NEW_LINE") val sb = createSetFromValues(values) out.write(sb) if (dataSet.getTable(metaData!!.tableName).rowCount != rowCount) { out.write("$FOUR_SPACES},$NEW_LINE") } else { out.write("$FOUR_SPACES}$NEW_LINE") } } catch (expected: Exception) { logger.warn("Could not write row.", expected) } } private fun createSetFromValues(values: Array<Any?>): String { val sb = StringBuilder() for (i in values.indices) { val currentValue = values[i] if (currentValue != null) { val currentColumn = metaData!!.columns[i] sb.append(FOUR_SPACES + DOUBLE_SPACES + '"').append(metaData!!.columns[i].columnName).append("\": ") val isNumber = currentColumn.dataType.isNumber if (!isNumber) { sb.append('"') } sb.append(currentValue.toString().replace(NEW_LINE.toRegex(), "\\\\n")) if (!isNumber) { sb.append('"') } if (i != values.size - 1) { sb.append(',') } sb.append(NEW_LINE) } } return replaceExtraCommaInTheEnd(sb) } private fun replaceExtraCommaInTheEnd(sb: StringBuilder): String { val indexOfPenultimateSymbol = sb.length - 2 if (sb.length > 1 && sb[indexOfPenultimateSymbol] == ',') { sb.deleteCharAt(indexOfPenultimateSymbol) } return sb.toString() } @Synchronized fun write() { val provider = DataSetProducerAdapter(dataSet) provider.setConsumer(this) provider.produce() } companion object : KLogging() { private val NEW_LINE = System.getProperty("line.separator") private const val DOUBLE_SPACES = " " private const val FOUR_SPACES = DOUBLE_SPACES + DOUBLE_SPACES } } /** * DBUnit DataSet format for JSON based datasets. It is similar to the flat XML * layout, but has some improvements (columns are calculated by parsing the * entire dataset, not just the first row). */ class JSONDataSet : AbstractDataSet { private val tableParser = JSONITableParser(TableParser()) val mapper = jacksonObjectMapper() private var tables: List<ITable> constructor(file: File) { tables = tableParser.getTables(file) } constructor(`is`: InputStream) { tables = tableParser.getTables(`is`) } @Throws(DataSetException::class) override fun createIterator(reverse: Boolean): ITableIterator { return DefaultTableIterator(tables.toTypedArray()) } private inner class JSONITableParser(val parser: TableParser) { fun getTables(jsonFile: File): List<ITable> = getTables(FileInputStream(jsonFile)) fun getTables(jsonStream: InputStream): List<ITable> = parser.fillTable(mapper.readValue(jsonStream)) } } class TableParser { fun fillTable(dataset: Map<String, List<Map<String, Any?>>>): List<ITable> = dataset.map { (key, value) -> val table = DefaultTable(getMetaData(key, value)) for ((rowIndex, row) in value.withIndex()) { fillRow(table, row, rowIndex) } table } private fun getMetaData(tableName: String, rows: List<Map<String, Any?>>): ITableMetaData = DefaultTableMetaData(tableName, rows.flatMap { row -> row.keys }.toSet().map { Column(it, UNKNOWN) }.toTypedArray()) private fun fillRow(table: DefaultTable, row: Map<String, Any?>, rowIndex: Int) { if (row.entries.isNotEmpty()) { table.addRow() row.forEach { (col, value) -> table.setValue(rowIndex, col, value) } } } }
mit
884b59eb2323c07e145e7a12289192d4
33.550802
124
0.620337
4.307333
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/database/DbActionGeneBuilder.kt
1
38297
package org.evomaster.core.database import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType import org.evomaster.core.database.schema.Column import org.evomaster.core.database.schema.ColumnDataType import org.evomaster.core.database.schema.ForeignKey import org.evomaster.core.database.schema.Table import org.evomaster.core.parser.RegexHandler.createGeneForPostgresLike import org.evomaster.core.parser.RegexHandler.createGeneForPostgresSimilarTo import org.evomaster.core.search.gene.* import org.evomaster.core.search.gene.collection.EnumGene import org.evomaster.core.search.gene.datetime.DateGene import org.evomaster.core.search.gene.datetime.DateTimeGene import org.evomaster.core.search.gene.sql.time.SqlTimeIntervalGene import org.evomaster.core.search.gene.datetime.TimeGene import org.evomaster.core.search.gene.sql.geometric.* import org.evomaster.core.search.gene.network.CidrGene import org.evomaster.core.search.gene.network.InetGene import org.evomaster.core.search.gene.network.MacAddrGene import org.evomaster.core.search.gene.numeric.* import org.evomaster.core.search.gene.optional.ChoiceGene import org.evomaster.core.search.gene.optional.NullableGene import org.evomaster.core.search.gene.regex.DisjunctionListRxGene import org.evomaster.core.search.gene.regex.RegexGene import org.evomaster.core.search.gene.sql.* import org.evomaster.core.search.gene.sql.textsearch.SqlTextSearchQueryGene import org.evomaster.core.search.gene.sql.textsearch.SqlTextSearchVectorGene import org.evomaster.core.search.gene.string.StringGene import org.evomaster.core.utils.NumberCalculationUtil import org.slf4j.Logger import org.slf4j.LoggerFactory import java.math.BigDecimal class DbActionGeneBuilder { private fun getForeignKey(table: Table, column: Column): ForeignKey? { //TODO: what if a column is part of more than 1 FK? is that even possible? return table.foreignKeys.find { it.sourceColumns.contains(column) } } fun buildGene(id: Long, table: Table, column: Column): Gene { val fk = getForeignKey(table, column) var gene = when { //TODO handle all constraints and cases column.autoIncrement -> SqlAutoIncrementGene(column.name) fk != null -> SqlForeignKeyGene(column.name, id, fk.targetTable, column.nullable) else -> when (column.type) { // Man: TODO need to check ColumnDataType.BIT -> handleBitColumn(column) ColumnDataType.VARBIT -> handleBitVaryingColumn(column) /** * BOOLEAN(1) is assumed to be a boolean/Boolean field */ ColumnDataType.BOOLEAN, ColumnDataType.BOOL -> handleBooleanColumn(column) /** * TINYINT(3) is assumed to be representing a byte/Byte field */ // ColumnDataType.TINYINT -> // handleTinyIntColumn(column) /** * SMALLINT(5) is assumed as a short/Short field */ // ColumnDataType.INT2, ColumnDataType.SMALLINT -> // handleSmallIntColumn(column) /** * CHAR(255) is assumed to be a char/Character field. * A StringGene of length 1 is used to represent the data. * */ ColumnDataType.CHAR, ColumnDataType.CHARACTER, ColumnDataType.CHARACTER_LARGE_OBJECT -> handleCharColumn(column) /** * TINYINT(3) is assumed to be representing a byte/Byte field * INT2/SMALLINT(5) is assumed as a short/Short field * INT4/INTEGER(10) is a int/Integer field */ ColumnDataType.TINYINT, ColumnDataType.INT2, ColumnDataType.SMALLINT, ColumnDataType.INT, ColumnDataType.INT4, ColumnDataType.INTEGER, ColumnDataType.SERIAL, ColumnDataType.MEDIUMINT -> handleIntegerColumn(column) /** * BIGINT(19) is a long/Long field */ ColumnDataType.INT8, ColumnDataType.BIGINT, ColumnDataType.BIGSERIAL -> handleBigIntColumn(column) /** * DOUBLE(17) is assumed to be a double/Double field * */ ColumnDataType.DOUBLE, ColumnDataType.DOUBLE_PRECISION -> handleDoubleColumn(column) /** * VARCHAR(N) is assumed to be a String with a maximum length of N. * N could be as large as Integer.MAX_VALUE */ ColumnDataType.TINYTEXT, ColumnDataType.TEXT, ColumnDataType.LONGTEXT, ColumnDataType.VARCHAR, ColumnDataType.CHARACTER_VARYING, ColumnDataType.VARCHAR_IGNORECASE, ColumnDataType.CLOB, ColumnDataType.MEDIUMTEXT, ColumnDataType.LONGBLOB, ColumnDataType.MEDIUMBLOB, ColumnDataType.TINYBLOB -> handleTextColumn(column) //TODO normal TIME, and add tests for it. this is just a quick workaround for patio-api ColumnDataType.TIME -> buildSqlTimeGene(column) ColumnDataType.TIMETZ, ColumnDataType.TIME_WITH_TIME_ZONE -> buildSqlTimeWithTimeZoneGene(column) /** * TIMESTAMP is assumed to be a Date field */ ColumnDataType.TIMESTAMP, ColumnDataType.TIMESTAMPTZ, ColumnDataType.TIMESTAMP_WITH_TIME_ZONE -> handleTimestampColumn(column) /** * DATE is a date without time of day */ ColumnDataType.DATE -> DateGene(column.name) /** * TODO need to check with Andrea regarding fsp which is the fractional seconds precision * * see https://dev.mysql.com/doc/refman/8.0/en/date-and-time-type-syntax.html */ ColumnDataType.DATETIME -> DateTimeGene(column.name) ColumnDataType.YEAR -> handleYearColumn(column) /** * Could be any kind of binary data... so let's just use a string, * which also simplifies when needing generate the test files */ ColumnDataType.BLOB, ColumnDataType.BINARY_LARGE_OBJECT -> handleBLOBColumn(column) ColumnDataType.BINARY -> handleMySqlBinaryColumn(column) ColumnDataType.BINARY_VARYING, ColumnDataType.VARBINARY, ColumnDataType.JAVA_OBJECT -> handleMySqlVarBinaryColumn(column) ColumnDataType.BYTEA -> handlePostgresBinaryStringColumn(column) ColumnDataType.FLOAT, ColumnDataType.REAL, ColumnDataType.FLOAT4 -> handleFloatColumn(column, MIN_FLOAT4_VALUE, MAX_FLOAT4_VALUE) ColumnDataType.FLOAT8 -> handleFloatColumn(column, MIN_FLOAT8_VALUE, MAX_FLOAT8_VALUE) ColumnDataType.DEC, ColumnDataType.DECIMAL, ColumnDataType.NUMERIC -> handleDecimalColumn(column) /** * Postgres UUID column type */ ColumnDataType.UUID -> UUIDGene(column.name) /** * Postgres JSONB column type */ ColumnDataType.JSON, ColumnDataType.JSONB -> SqlJSONGene(column.name) /** * PostgreSQL XML column type */ ColumnDataType.XML -> SqlXMLGene(column.name) ColumnDataType.ENUM -> handleEnumColumn(column) ColumnDataType.MONEY -> handleMoneyColumn(column) ColumnDataType.BPCHAR -> handleTextColumn(column, isFixedLength = true) ColumnDataType.INTERVAL -> SqlTimeIntervalGene(column.name) /* * MySQL and PostgreSQL Point column data type */ ColumnDataType.POINT -> buildSqlPointGene(column) /* * PostgreSQL LINE Column data type */ ColumnDataType.LINE -> SqlLineGene(column.name) /* * PostgreSQL LSEG (line segment) column data type */ ColumnDataType.LSEG -> SqlLineSegmentGene(column.name) /* * PostgreSQL BOX column data type */ ColumnDataType.BOX -> SqlBoxGene(column.name) /* * MySQL,H2 LINESTRING and PostgreSQL PATH * column data types */ ColumnDataType.LINESTRING, ColumnDataType.PATH -> buildSqlPathGene(column) /** * MySQL and H2 MULTIPOINT * column types */ ColumnDataType.MULTIPOINT -> buildSqlMultiPointGene(column) /** * PostgreSQL and H2 MULTILINESTRING * column types */ ColumnDataType.MULTILINESTRING -> buildSqlMultiPathGene(column) /* MySQL and PostgreSQL POLYGON * column data type */ ColumnDataType.POLYGON -> buildSqlPolygonGene(column) /* MySQL and H2 MULTIPOLYGON * column data type */ ColumnDataType.MULTIPOLYGON -> buildSqlMultiPolygonGene(column) /** * H2 GEOMETRY column data type */ ColumnDataType.GEOMETRY -> handleSqlGeometry(column) /** * H2 GEOMETRYCOLLECTION and MYSQL GEOMCOLLECTION * column data types */ ColumnDataType.GEOMCOLLECTION, ColumnDataType.GEOMETRYCOLLECTION -> handleSqlGeometryCollection(column) /* * PostgreSQL CIRCLE column data type */ ColumnDataType.CIRCLE -> SqlCircleGene(column.name) ColumnDataType.CIDR -> CidrGene(column.name) ColumnDataType.INET -> InetGene(column.name) ColumnDataType.MACADDR -> MacAddrGene(column.name) ColumnDataType.MACADDR8 -> MacAddrGene(column.name, numberOfOctets = MacAddrGene.MACADDR8_SIZE) ColumnDataType.TSVECTOR -> SqlTextSearchVectorGene(column.name) ColumnDataType.TSQUERY -> SqlTextSearchQueryGene(column.name) ColumnDataType.JSONPATH -> SqlJSONPathGene(column.name) ColumnDataType.INT4RANGE -> buildSqlIntegerRangeGene(column) ColumnDataType.INT8RANGE -> buildSqlLongRangeGene(column) ColumnDataType.NUMRANGE -> buildSqlFloatRangeGene(column) ColumnDataType.DATERANGE -> buildSqlDateRangeGene(column) ColumnDataType.TSRANGE, ColumnDataType.TSTZRANGE -> buildSqlTimestampRangeGene(column) ColumnDataType.INT4MULTIRANGE -> SqlMultiRangeGene(column.name, template = buildSqlIntegerRangeGene(column)) ColumnDataType.INT8MULTIRANGE -> SqlMultiRangeGene(column.name, template = buildSqlLongRangeGene(column)) ColumnDataType.NUMMULTIRANGE -> SqlMultiRangeGene(column.name, template = buildSqlFloatRangeGene(column)) ColumnDataType.DATEMULTIRANGE -> SqlMultiRangeGene(column.name, template = buildSqlDateRangeGene(column)) ColumnDataType.TSMULTIRANGE, ColumnDataType.TSTZMULTIRANGE -> SqlMultiRangeGene(column.name, template = buildSqlTimestampRangeGene(column)) ColumnDataType.PG_LSN -> SqlLogSeqNumberGene(column.name) ColumnDataType.COMPOSITE_TYPE -> handleCompositeColumn(id, table, column) ColumnDataType.OID, ColumnDataType.REGCLASS, ColumnDataType.REGCOLLATION, ColumnDataType.REGCONFIG, ColumnDataType.REGDICTIONARY, ColumnDataType.REGNAMESPACE, ColumnDataType.REGOPER, ColumnDataType.REGOPERATOR, ColumnDataType.REGPROC, ColumnDataType.REGPROCEDURE, ColumnDataType.REGROLE, ColumnDataType.REGTYPE -> handleObjectIdentifierType(column.name) else -> throw IllegalArgumentException("Cannot handle: $column.") } } if (column.primaryKey) { gene = SqlPrimaryKeyGene(column.name, table.name, gene, id) } if (column.nullable && fk == null) { //FKs handle nullability in their own custom way gene = NullableGene(column.name, gene, true, "NULL") } if (column.dimension > 0) { gene = SqlMultidimensionalArrayGene(column.name, databaseType = column.databaseType, template = gene, numberOfDimensions = column.dimension) } return gene } private fun handleSqlGeometry(column: Column): ChoiceGene<*> { return ChoiceGene(name = column.name, listOf(buildSqlPointGene(column), buildSqlMultiPointGene(column), buildSqlPathGene(column), buildSqlMultiPathGene(column), buildSqlPolygonGene(column), buildSqlMultiPolygonGene(column))) } private fun buildSqlPointGene(column: Column) = SqlPointGene(column.name, databaseType = column.databaseType) private fun buildSqlPathGene(column: Column) = SqlPathGene(column.name, databaseType = column.databaseType) private fun buildSqlMultiPointGene(column: Column) = SqlMultiPointGene(column.name, databaseType = column.databaseType) private fun buildSqlMultiPathGene(column: Column) = SqlMultiPathGene(column.name, databaseType = column.databaseType) private fun buildSqlMultiPolygonGene(column: Column) = SqlMultiPolygonGene(column.name, databaseType = column.databaseType) private fun handleSqlGeometryCollection(column: Column) = SqlGeometryCollectionGene(column.name, databaseType = column.databaseType, template = handleSqlGeometry(column)) private fun buildSqlPolygonGene(column: Column): SqlPolygonGene { return when (column.databaseType) { /* * TODO: Uncomment this option when the [isValid()] * method is ensured after each mutation of the * children of the SqlPolygonGene. */ DatabaseType.MYSQL -> { SqlPolygonGene(column.name, minLengthOfPolygonRing = 3, onlyNonIntersectingPolygons = true, databaseType = column.databaseType) } DatabaseType.H2 -> { SqlPolygonGene(column.name, minLengthOfPolygonRing = 3, onlyNonIntersectingPolygons = false, databaseType = column.databaseType) } DatabaseType.POSTGRES -> { SqlPolygonGene(column.name, minLengthOfPolygonRing = 2, onlyNonIntersectingPolygons = false, databaseType = column.databaseType) } else -> { throw IllegalArgumentException("Must define minLengthOfPolygonRing for database ${column.databaseType}") } } } private fun buildSqlTimestampRangeGene(column: Column) = SqlRangeGene(column.name, template = buildSqlTimestampGene("bound", databaseType = column.databaseType)) private fun buildSqlDateRangeGene(column: Column) = SqlRangeGene(column.name, template = DateGene("bound")) private fun buildSqlFloatRangeGene(column: Column) = SqlRangeGene(column.name, template = FloatGene("bound")) private fun buildSqlLongRangeGene(column: Column) = SqlRangeGene(column.name, template = LongGene("bound")) private fun buildSqlIntegerRangeGene(column: Column) = SqlRangeGene(column.name, template = IntegerGene("bound")) /* https://dev.mysql.com/doc/refman/8.0/en/year.html */ private fun handleYearColumn(column: Column): Gene { // Year(2) is not supported by mysql 8.0 if (column.size == 2) return IntegerGene(column.name, 16, min = 0, max = 99) return IntegerGene(column.name, 2016, min = 1901, max = 2155) } private fun handleEnumColumn(column: Column): Gene { return EnumGene(name = column.name, data = column.enumValuesAsStrings ?: listOf()) } private fun handleBigIntColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(column.name, column.enumValuesAsStrings.map { it.toLong() }) } else { /* TODO might need to use ULong to handle unsigned long https://dev.mysql.com/doc/refman/8.0/en/integer-types.html Man: TODO need to check whether to update this with BigIntegerGene */ val min: Long? = if (column.isUnsigned) 0 else null LongGene(column.name, min = min) } } private fun handleIntegerColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(column.name, column.enumValuesAsStrings.map { it.toInt() }) } else { if ((column.type == ColumnDataType.INT4 || column.type == ColumnDataType.INT || column.type == ColumnDataType.INTEGER) && column.isUnsigned ) { LongGene(column.name, min = 0L, max = 4294967295L) } else { val min = when { column.isUnsigned -> 0 column.type == ColumnDataType.TINYINT -> Byte.MIN_VALUE.toInt() column.type == ColumnDataType.SMALLINT || column.type == ColumnDataType.INT2 -> Short.MIN_VALUE.toInt() column.type == ColumnDataType.MEDIUMINT -> -8388608 else -> Int.MIN_VALUE } val max = when (column.type) { ColumnDataType.TINYINT -> if (column.isUnsigned) 255 else Byte.MAX_VALUE.toInt() ColumnDataType.SMALLINT, ColumnDataType.INT2 -> if (column.isUnsigned) 65535 else Short.MAX_VALUE.toInt() ColumnDataType.MEDIUMINT -> if (column.isUnsigned) 16777215 else 8388607 else -> Int.MAX_VALUE } IntegerGene( column.name, min = column.lowerBound ?: min, max = column.upperBound ?: max ) } } } private fun handleCharColumn(column: Column): Gene { // TODO How to discover if it is a char or a char[] of 255 elements? return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings) } else { val minLength: Int val maxLength: Int when (column.databaseType) { DatabaseType.H2 -> { minLength = column.size maxLength = column.size } else -> { minLength = 0 maxLength = 1 } } StringGene(name = column.name, value = "f", minLength = minLength, maxLength = maxLength) } } private fun handleDoubleColumn(column: Column): Gene { // TODO How to discover if the source field is a float/Float field? return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings.map { it.toDouble() }) } else { DoubleGene(column.name) } } private fun handleMySqlBinaryColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings) } else { SqlBinaryStringGene(name = column.name, minSize = column.size, maxSize = column.size, databaseType = column.databaseType) } } private fun handleMySqlVarBinaryColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings) } else { SqlBinaryStringGene(name = column.name, minSize = 0, maxSize = column.size, databaseType = column.databaseType) } } private fun handlePostgresBinaryStringColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings) } else { SqlBinaryStringGene(name = column.name, databaseType = column.databaseType) } } private fun handleFloatColumn(column: Column, minValue: Double, maxValue: Double): Gene { /** * REAL is identical to the floating point statement float(24). * TODO How to discover if the source field is a float/Float field? */ return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings.map { it.toDouble() }) } else { DoubleGene(column.name, min = minValue, max = maxValue) } } @Deprecated("replaced by handleIntegerColumn, now all numeric types resulting in IntegerGene would by handled in handleIntegerColumn") private fun handleSmallIntColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { if (column.enumValuesAsStrings.isEmpty()) { throw IllegalArgumentException("the list of enumerated values cannot be empty") } else { EnumGene(column.name, column.enumValuesAsStrings.map { it.toInt() }) } } else { IntegerGene( column.name, min = column.lowerBound ?: Short.MIN_VALUE.toInt(), max = column.upperBound ?: Short.MAX_VALUE.toInt() ) } } @Deprecated("replaced by handleIntegerColumn, now all numeric types resulting in IntegerGene would by handled in handleIntegerColumn") private fun handleTinyIntColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { if (column.enumValuesAsStrings.isEmpty()) { throw IllegalArgumentException("the list of enumerated values cannot be empty") } else { EnumGene(column.name, column.enumValuesAsStrings.map { it.toInt() }) } } else { IntegerGene( column.name, min = column.lowerBound ?: Byte.MIN_VALUE.toInt(), max = column.upperBound ?: Byte.MAX_VALUE.toInt() ) } } private fun handleTextColumn(column: Column, isFixedLength: Boolean = false): Gene { return if (column.enumValuesAsStrings != null) { if (column.enumValuesAsStrings.isEmpty()) { throw IllegalArgumentException("the list of enumerated values cannot be empty") } else { EnumGene(name = column.name, data = column.enumValuesAsStrings) } } else { if (column.similarToPatterns != null && column.similarToPatterns.isNotEmpty()) { val columnName = column.name val similarToPatterns: List<String> = column.similarToPatterns buildSimilarToRegexGene(columnName, similarToPatterns, databaseType = column.databaseType) } else if (column.likePatterns != null && column.likePatterns.isNotEmpty()) { val columnName = column.name val likePatterns = column.likePatterns buildLikeRegexGene(columnName, likePatterns, databaseType = column.databaseType) } else { val columnMinLength = if (isFixedLength) { column.size } else { 0 } StringGene(name = column.name, minLength = columnMinLength, maxLength = column.size) } } } /** * Builds a RegexGene using a name and a list of LIKE patterns. * The resulting gene is a disjunction of the given patterns */ fun buildLikeRegexGene(geneName: String, likePatterns: List<String>, databaseType: DatabaseType): RegexGene { return when (databaseType) { DatabaseType.POSTGRES, DatabaseType.MYSQL -> buildPostgresMySQLLikeRegexGene(geneName, likePatterns) //TODO: support other database SIMILAR_TO check expressions else -> throw UnsupportedOperationException( "Must implement LIKE expressions for database %s".format( databaseType ) ) } } private fun buildPostgresMySQLLikeRegexGene(geneName: String, likePatterns: List<String>): RegexGene { val disjunctionRxGenes = likePatterns .map { createGeneForPostgresLike(it) } .map { it.disjunctions } .map { it.disjunctions } .flatten() return RegexGene(geneName, disjunctions = DisjunctionListRxGene(disjunctions = disjunctionRxGenes)) } /** * Builds a RegexGene using a name and a list of SIMILAR_TO patterns. * The resulting gene is a disjunction of the given patterns * according to the database we are using */ fun buildSimilarToRegexGene( geneName: String, similarToPatterns: List<String>, databaseType: DatabaseType ): RegexGene { return when { databaseType == DatabaseType.POSTGRES -> buildPostgresSimilarToRegexGene(geneName, similarToPatterns) //TODO: support other database SIMILAR_TO check expressions else -> throw UnsupportedOperationException( "Must implement similarTo expressions for database %s".format( databaseType ) ) } } private fun buildPostgresSimilarToRegexGene(geneName: String, similarToPatterns: List<String>): RegexGene { val disjunctionRxGenes = similarToPatterns .map { createGeneForPostgresSimilarTo(it) } .map { it.disjunctions } .map { it.disjunctions } .flatten() return RegexGene(geneName, disjunctions = DisjunctionListRxGene(disjunctions = disjunctionRxGenes)) } private fun buildSqlTimeWithTimeZoneGene(column: Column): TimeGene { return TimeGene( column.name, hour = IntegerGene("hour", 0, 0, 23), minute = IntegerGene("minute", 0, 0, 59), second = IntegerGene("second", 0, 0, 59), timeGeneFormat = TimeGene.TimeGeneFormat.TIME_WITH_MILLISECONDS ) } private fun buildSqlTimeGene(column: Column): TimeGene { return TimeGene( column.name, hour = IntegerGene("hour", 0, 0, 23), minute = IntegerGene("minute", 0, 0, 59), second = IntegerGene("second", 0, 0, 59), timeGeneFormat = TimeGene.TimeGeneFormat.ISO_LOCAL_DATE_FORMAT ) } fun buildSqlTimestampGene(name: String, databaseType: DatabaseType = DatabaseType.H2): DateTimeGene { val minYear: Int val maxYear: Int when (databaseType) { DatabaseType.MYSQL -> { minYear = 1970 maxYear = 2037 } else -> { minYear = 1900 maxYear = 2100 } } return DateTimeGene( name = name, date = DateGene( "date", year = IntegerGene("year", 2016, minYear, maxYear), month = IntegerGene("month", 3, 1, 12), day = IntegerGene("day", 12, 1, 31), onlyValidDates = true ), time = TimeGene( "time", hour = IntegerGene("hour", 0, 0, 23), minute = IntegerGene("minute", 0, 0, 59), second = IntegerGene("second", 0, 0, 59) ), dateTimeGeneFormat = DateTimeGene.DateTimeGeneFormat.DEFAULT_DATE_TIME ) } private fun handleTimestampColumn(column: Column): DateTimeGene { if (column.enumValuesAsStrings != null) { throw RuntimeException("Unsupported enum in TIMESTAMP. Please implement") } else { return buildSqlTimestampGene(column.name, databaseType = column.databaseType) } } private fun handleCLOBColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings) } else { StringGene(name = column.name, minLength = 0, maxLength = column.size) } } private fun handleBLOBColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings) } else { StringGene(name = column.name, minLength = 0, maxLength = 8) } } private fun handleRealColumn(column: Column): Gene { /** * REAL is identical to the floating point statement float(24). * TODO How to discover if the source field is a float/Float field? */ return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings.map { it.toDouble() }) } else { DoubleGene(column.name) } } private fun handleDecimalColumn(column: Column): Gene { /** * TODO: DECIMAL precision is lower than a float gene */ return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings.map { it.toFloat() }) } else { if (column.scale != null && column.scale >= 0) { /* set precision and boundary for DECIMAL https://dev.mysql.com/doc/refman/8.0/en/fixed-point-types.html for mysql, precision is [1, 65] (default 10), and scale is [0, 30] (default 0) different db might have different range, then do not validate the range for the moment */ val range = NumberCalculationUtil.boundaryDecimal(column.size, column.scale) BigDecimalGene( column.name, min = if (column.isUnsigned) BigDecimal.ZERO.setScale(column.scale) else range.first, max = range.second, precision = column.size, scale = column.scale ) } else { if (column.scale == null) { FloatGene(column.name) } else { /* TO check with CompositeTypesTest for postgres, the value of precision and scale is -1, may need to check with the authors */ log.warn("invalid scale value (${column.scale}) for decimal, and it should not be less than 0") if (column.size <= 0) { log.warn("invalid precision value (${column.size}) for decimal, and it should not be less than 1") FloatGene(column.name) } else { // for mysql, set the scale with default value 0 if it is invalid BigDecimalGene(column.name, precision = column.size, scale = 0) } } } } } private fun handleMoneyColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(name = column.name, data = column.enumValuesAsStrings.map { it.toFloat() }) } else { val MONEY_COLUMN_PRECISION = 2 val MONEY_COLUMN_SIZE = 8 val range = NumberCalculationUtil.boundaryDecimal(MONEY_COLUMN_SIZE, MONEY_COLUMN_PRECISION) BigDecimalGene( column.name, min = range.first, max = range.second, precision = MONEY_COLUMN_SIZE, scale = MONEY_COLUMN_PRECISION ) } } private fun handleBooleanColumn(column: Column): Gene { return if (column.enumValuesAsStrings != null) { checkNotEmpty(column.enumValuesAsStrings) EnumGene(column.name, column.enumValuesAsStrings.map { it.toBoolean() }) } else { BooleanGene(column.name) } } private fun handleCompositeColumn(id: Long, table: Table, column: Column): Gene { if (column.compositeType == null) { throw IllegalArgumentException("Composite column should have a composite type for column ${column.name}") } val fields = column.compositeType .map { t -> buildGene(id, table, t) } .toList() return SqlCompositeGene(column.name, fields, column.compositeTypeName) } /** * Handle Postgres Object identifier type * (https://www.postgresql.org/docs/current/datatype-oid.html) as * integers. */ private fun handleObjectIdentifierType(name: String) = IntegerGene(name) /** * handle bit for mysql * https://dev.mysql.com/doc/refman/8.0/en/bit-value-literals.html */ private fun handleBitColumn(column: Column): Gene { val gene = SqlBitStringGene(column.name, minSize = column.size, maxSize = column.size) return gene } /** * handle bit varying for postgres * https://www.postgresql.org/docs/14/datatype-bit.html */ private fun handleBitVaryingColumn(column: Column): Gene { return SqlBitStringGene(column.name, minSize = 0, maxSize = column.size) } companion object { /** * Throws an exception if the enum values is empty * (parameter is non-nullable by definition) */ private fun checkNotEmpty(enumValuesAsStrings: List<String>) { if (enumValuesAsStrings.isEmpty()) { throw IllegalArgumentException("the list of enumerated values cannot be empty") } } // the real type has a range of around 1E-37 to 1E+37 with a precision of at least 6 decimal digits val MAX_FLOAT4_VALUE: Double = "1E38".toDouble() // The double precision type has a range of around 1E-307 to 1E+308 with a precision of at least 15 digits val MAX_FLOAT8_VALUE: Double = "1E308".toDouble() // the real type has a range of around 1E-37 to 1E+37 with a precision of at least 6 decimal digits val MIN_FLOAT4_VALUE: Double = MAX_FLOAT4_VALUE.unaryMinus() // The double precision type has a range of around 1E-307 to 1E+308 with a precision of at least 15 digits val MIN_FLOAT8_VALUE: Double = MAX_FLOAT8_VALUE.unaryMinus() private val log: Logger = LoggerFactory.getLogger(DbActionGeneBuilder::class.java) } }
lgpl-3.0
5255473c64ae12ba15c06b4139a1ee6d
38.563017
201
0.565423
5.086598
false
false
false
false
Litote/kmongo
kmongo-async-shared/src/main/kotlin/org/litote/kmongo/reactivestreams/FindPublishers.kt
1
6263
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.reactivestreams import com.mongodb.CursorType import com.mongodb.ExplainVerbosity import com.mongodb.client.model.Collation import com.mongodb.reactivestreams.client.FindPublisher import org.bson.BsonValue import org.bson.Document import org.bson.conversions.Bson import org.litote.kmongo.include import org.litote.kmongo.util.KMongoUtil import org.reactivestreams.Publisher import org.reactivestreams.Subscriber import org.reactivestreams.Subscription import java.util.concurrent.TimeUnit import kotlin.reflect.KProperty /** * Sets the query filter to apply to the query. * * @param filter the filter, which may be null * @return this */ fun <T> FindPublisher<T>.filter(filter: String): FindPublisher<T> = filter(KMongoUtil.toBson(filter)) /** * Sets a document describing the fields to return for all matching documents. * * @param projection the project document * @return this */ fun <T> FindPublisher<T>.projection(projection: String): FindPublisher<T> = projection(KMongoUtil.toBson(projection)) /** * Sets a document describing the fields to return for all matching documents. * * @param projections the properties of the returned fields * @return this */ fun <T> FindPublisher<T>.projection(vararg projections: KProperty<*>): FindPublisher<T> = projection(include(*projections)) /** * Sets the sort criteria to apply to the query. * * @param sort the sort criteria * @return this */ fun <T> FindPublisher<T>.sort(sort: String): FindPublisher<T> = sort(KMongoUtil.toBson(sort)) /** * Maps a value and returns the new FindPublisher. */ @Suppress("UNCHECKED_CAST") fun <I, O> FindPublisher<I>.map(mapper: (I?) -> O?): FindPublisher<O> = object : FindPublisher<O> { override fun first(): Publisher<O> = [email protected]().map(mapper) override fun filter(filter: Bson): FindPublisher<O> = [email protected](filter).map(mapper) override fun limit(limit: Int): FindPublisher<O> = [email protected](limit).map(mapper) override fun skip(skip: Int): FindPublisher<O> = [email protected](skip).map(mapper) override fun maxTime(maxTime: Long, timeUnit: TimeUnit): FindPublisher<O> = [email protected](maxTime, timeUnit).map(mapper) override fun maxAwaitTime(maxAwaitTime: Long, timeUnit: TimeUnit): FindPublisher<O> = [email protected](maxAwaitTime, timeUnit).map(mapper) override fun projection(projection: Bson): FindPublisher<O> = [email protected](projection).map(mapper) override fun sort(sort: Bson): FindPublisher<O> = [email protected](sort).map(mapper) override fun noCursorTimeout(noCursorTimeout: Boolean): FindPublisher<O> = [email protected](noCursorTimeout).map(mapper) override fun oplogReplay(oplogReplay: Boolean): FindPublisher<O> = [email protected](oplogReplay).map(mapper) override fun partial(partial: Boolean): FindPublisher<O> = [email protected](partial).map(mapper) override fun cursorType(cursorType: CursorType): FindPublisher<O> = [email protected](cursorType).map(mapper) override fun collation(collation: Collation): FindPublisher<O> = [email protected](collation).map(mapper) override fun comment(comment: String): FindPublisher<O> = [email protected](comment).map(mapper) override fun hint(hint: Bson): FindPublisher<O> = [email protected](hint).map(mapper) override fun hintString(hint: String): FindPublisher<O> = [email protected](hint).map(mapper) override fun max(max: Bson): FindPublisher<O> = [email protected](max).map(mapper) override fun min(min: Bson): FindPublisher<O> = [email protected](min).map(mapper) override fun returnKey(returnKey: Boolean): FindPublisher<O> = [email protected](returnKey).map(mapper) override fun showRecordId(showRecordId: Boolean): FindPublisher<O> = [email protected](showRecordId).map(mapper) override fun batchSize(batchSize: Int): FindPublisher<O> = [email protected](batchSize).map(mapper) override fun allowDiskUse(allowDiskUse: Boolean?): FindPublisher<O> = [email protected](allowDiskUse).map(mapper) override fun explain(): Publisher<Document> = [email protected]() override fun explain(verbosity: ExplainVerbosity): Publisher<Document> = [email protected](verbosity) override fun <E : Any?> explain(explainResultClass: Class<E>): Publisher<E> = [email protected](explainResultClass) override fun <E : Any?> explain(explainResultClass: Class<E>, verbosity: ExplainVerbosity): Publisher<E> = [email protected](explainResultClass, verbosity) override fun subscribe(subscriber: Subscriber<in O>) { [email protected](mapper, subscriber) } override fun comment(comment: BsonValue?): FindPublisher<O> = [email protected](comment).map(mapper) override fun let(variables: Bson?): FindPublisher<O> = [email protected](variables).map(mapper) } fun <I, O> Publisher<I>.map(mapper: (I?) -> O?): Publisher<O> = Publisher<O> { subscriber -> subscribe(mapper, subscriber) } private fun <I, O> Publisher<I>.subscribe(mapper: (I?) -> O?, subscriber: Subscriber<in O>) = subscribe(object : Subscriber<I> { override fun onComplete() { subscriber.onComplete() } override fun onSubscribe(s: Subscription) { subscriber.onSubscribe(s) } override fun onNext(t: I?) { subscriber.onNext(mapper(t)) } override fun onError(t: Throwable) { subscriber.onError(t) } })
apache-2.0
04fd21fd93fdd6179ef7606435a2343d
37.195122
120
0.703976
3.868437
false
false
false
false
FrontierRobotics/i2c-api
src/test/kotlin/io/frontierrobotics/i2c/I2CBusSpecs.kt
1
3533
package io.frontierrobotics.i2c import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import io.frontierrobotics.i2c.driver.I2CDriver import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import kotlin.test.assertEquals import kotlin.test.assertFailsWith class I2CBusSpecs : Spek({ describe("an I2C Buss") { val driver = mock<I2CDriver>() val bus = I2CBus(driver, 0x1B) on("sending a command") { it("should send the command over the i2CBus") { val data = I2CData("hello") val device = I2CDevice(0x1C) bus.send(device, data) verify(driver).send(device, data) } } on("sending a command to an internal address") { it("should send the command over the i2CBus") { val data = I2CData("hello") val device = I2CDevice(0x1C, 0x01) bus.send(device, data) verify(driver).send(device, data) } } on("sending a command to a reserved address") { it("should return an error") { val data = I2CData("hello") val device = I2CDevice(0x1B) assertFailsWith<IllegalArgumentException> { bus.send(device, data) } } } on("sending a command to an out-of-bounds address") { it("should return an error") { val data = I2CData("hello") val device = I2CDevice(0x1FF) assertFailsWith<IllegalArgumentException> { bus.send(device, data) } } } on("receiving data") { it("should receive the data over the i2CBus") { val device = I2CDevice(0x1C) val expected = I2CData("123") whenever(driver.receive(device, 3)).thenReturn(expected) val actual = bus.receive(device, 3) verify(driver).receive(device, 3) assertEquals(expected, actual) } } on("receiving a command from an internal address") { it("should receive the data over the i2CBus") { val device = I2CDevice(0x1C, 0x01) val expected = I2CData("123") whenever(driver.receive(device, 3)).thenReturn(expected) val actual = bus.receive(device, 3) verify(driver).receive(device, 3) assertEquals(expected, actual) } } on("receiving a command from a reserved address") { it("should return an error") { val device = I2CDevice(0x1B) assertFailsWith<IllegalArgumentException> { bus.receive(device, 3) } } } on("receiving a command from an out-of-bounds address") { it("should return an error") { val device = I2CDevice(0x1FF) assertFailsWith<IllegalArgumentException> { bus.receive(device, 3) } } } } })
mit
5ecf47af3062ae1ddcdecba4213c6002
27.047619
72
0.507501
4.444025
false
false
false
false
holgerbrandl/kscript
src/test/kotlin/kscript/app/parser/LineParserTest.kt
1
13894
package kscript.app.parser import assertk.assertThat import assertk.assertions.containsExactlyInAnyOrder import assertk.assertions.isFailure import assertk.assertions.messageContains import kscript.app.model.* import kscript.app.parser.LineParser.parseDependency import kscript.app.parser.LineParser.parseEntry import kscript.app.parser.LineParser.parseImport import kscript.app.parser.LineParser.parseKotlinOpts import kscript.app.parser.LineParser.parseRepository import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.net.URI import java.util.stream.Stream class LineParserTest { @Test fun `Import parsing`() { assertThat( parseImport( location, 1, "import com.script.test1" ) ).containsExactlyInAnyOrder(ImportName("com.script.test1")) assertThat(parseImport(location, 1, " import com.script.test2 ")).containsExactlyInAnyOrder( ImportName("com.script.test2") ) } @ParameterizedTest @MethodSource("staticDependencies") fun `Dependency parsing - static dependencies`(list: List<String>) { val listWithQuotes = list.joinToString(", ") { "\"$it\"" } val listWithoutQuotes = list.joinToString(", ") val listWithoutQuotesStrangelyFormatted = list.joinToString(" , ") for (line in listOf( "@file:DependsOn($listWithQuotes)", "@file:DependsOn($listWithQuotes) //Comment", "@file:DependsOnMaven($listWithQuotes)", " @file:DependsOnMaven($listWithQuotes) ", "//DEPS $listWithoutQuotes", " //DEPS $listWithoutQuotesStrangelyFormatted", )) { println("Case: '$line'") var expectedAnnotations: List<ScriptAnnotation> = list.map { Dependency(it.trim()) } if (line.trimStart().startsWith("//")) { val expectedList = list.joinToString(", ") { "\"${it.trim()}\"" } expectedAnnotations = expectedAnnotations + DeprecatedItem( location, 1, "Deprecated annotation:\n$line\nshould be replaced with:\n@file:DependsOn($expectedList)" ) } assertThat( parseDependency( location, 1, line ) ).containsExactlyInAnyOrder(*expectedAnnotations.toTypedArray()) } } @ParameterizedTest @MethodSource("dynamicDependencies") fun `Dependency parsing - dynamic dependencies`(list: List<String>) { val listWithQuotes = list.joinToString(", ") { "\"$it\"" } for (line in listOf( "@file:DependsOn($listWithQuotes)", "@file:DependsOn($listWithQuotes) //Comment", "@file:DependsOnMaven($listWithQuotes)", " @file:DependsOnMaven($listWithQuotes) ", )) { println("Case: '$line'") assertThat(parseDependency(location, 1, line)).containsExactlyInAnyOrder(*list.map { Dependency(it) } .toTypedArray()) } } @ParameterizedTest @MethodSource("invalidDependencies") fun `Dependency parsing - invalid dependencies`(list: List<String>, message: String) { val listWithQuotes = list.joinToString(", ") { "\"$it\"" } val listWithoutQuotes = list.joinToString(", ") for (line in listOf( "@file:DependsOn($listWithQuotes)", "@file:DependsOn($listWithQuotes) //Comment", "@file:DependsOnMaven($listWithQuotes)", " @file:DependsOnMaven($listWithQuotes) ", "//DEPS $listWithoutQuotes", " //DEPS $listWithoutQuotes", )) { println("Case: '$line'") assertThat { parseDependency(location, 1, line) }.isFailure().messageContains(message) } } @Test fun `Dependency parsing - invalid quoting`() { assertThat { parseDependency( location, 1, "@file:DependsOn(\"com.squareup.moshi:moshi:1.5.0,com.squareup.moshi:moshi-adapters:1.5.0\") //Comment" ) }.isFailure() .messageContains("Artifact locators must be provided as separate annotation arguments and not as comma-separated list") } @ParameterizedTest @MethodSource("repositories") fun `Repository parsing`(line: String, annotations: List<ScriptAnnotation>) { println("Repository: '$line'") assertThat(parseRepository(location, 1, line)).containsExactlyInAnyOrder(*annotations.toTypedArray()) } @ParameterizedTest @MethodSource("kotlinOptions") fun `Kotlin options parsing`(line: String, kotlinOpts: List<ScriptAnnotation>) { println("KotlinOptions: '$line'") assertThat(parseKotlinOpts(location, 1, line)).containsExactlyInAnyOrder(*kotlinOpts.toTypedArray()) } @ParameterizedTest @MethodSource("entryPoint") fun `Entry point parsing`(line: String, entry: String) { println("Entry point: '$line'") var expectedAnnotations: List<ScriptAnnotation> = listOf(Entry(entry)) if (line.trimStart().startsWith("//")) { expectedAnnotations = expectedAnnotations + DeprecatedItem( location, 1, "Deprecated annotation:\n$line\nshould be replaced with:\n@file:EntryPoint(\"$entry\")" ) } assertThat(parseEntry(location, 1, line)).containsExactlyInAnyOrder(*expectedAnnotations.toTypedArray()) } companion object { @JvmStatic private val location = Location(0, ScriptSource.HTTP, ScriptType.KT, URI("http://example/test.kt"), URI("http://example/"), "test") @JvmStatic fun staticDependencies(): Stream<Arguments> = Stream.of( Arguments.of(listOf("org.javamoney:moneta:pom:1.3")), Arguments.of( listOf( " org.javamoney:moneta:pom:1.3 ", "log4j:log4j:1.2.14", "com.offbytwo:docopt:0.6.0.20150202" ) ), Arguments.of(listOf("de.mpicbg.scicomp.joblist:joblist-kotlin:1.1", "de.mpicbg.scicomp:kutils:0.7")), Arguments.of(listOf("something:dev-1.1.0-alpha3(T2):1.2.14", "de.mpicbg.scicomp:kutils:0.7")) ) @JvmStatic fun dynamicDependencies(): Stream<Arguments> = Stream.of( Arguments.of(listOf("log4j:log4j:[1.2,)", "com.offbytwo:docopt:[0.6,)")) ) @JvmStatic fun invalidDependencies(): Stream<Arguments> = Stream.of( Arguments.of(listOf("log4j:1.0"), "Invalid dependency locator: 'log4j"), Arguments.of(listOf("com.offbytwo:docopt:0.6", "log4j:1.0"), "Invalid dependency locator: 'log4j"), Arguments.of( listOf("log4j:::1.0", "com.offbytwo:docopt:0.6", "log4j:1.0"), "Invalid dependency locator: 'log4j" ), ) private const val repositoryReleasesUrl = "http://maven.imagej.net/content/repositories/releases" private const val repositorySnapshotsUrl = "http://maven.imagej.net/content/repositories/snapshots" @JvmStatic fun createDeprecatedAnnotation(line: String, expectedContent: String): DeprecatedItem { return DeprecatedItem( location, 1, "Deprecated annotation:\n$line\nshould be replaced with:\n@file:Repository($expectedContent)" ) } @JvmStatic fun repositories(): Stream<Arguments> { val lines = listOf( """@file:MavenRepository("imagej-releases", "$repositoryReleasesUrl" ) // crazy comment""", """@file:MavenRepository("imagej-releases", "$repositoryReleasesUrl", user="user", password="pass") """, """@file:MavenRepository("imagej-snapshots", "$repositorySnapshotsUrl", password="pass", user="user") """, // Whitespaces around credentials see #228 """@file:MavenRepository("spaceAroundCredentials", "$repositorySnapshotsUrl", password= "pass" , user ="user" ) """, // Different whitespaces around credentials see #228 """@file:MavenRepository("spaceAroundCredentials2", "$repositorySnapshotsUrl", password= "pass", user="user" ) """, // Different whitespaces around credentials see #228 """@file:MavenRepository("unnamedCredentials", "$repositorySnapshotsUrl", "user", "pass") """, // Named repo options """@file:MavenRepository(id= "imagej-releases", url = "$repositoryReleasesUrl", user="user", password="pass") """, """@file:Repository("$repositoryReleasesUrl")""", """@file:Repository("$repositoryReleasesUrl", user="user", password="pass")""", ) return Stream.of( Arguments.of( lines[0], listOf( Repository("imagej-releases", repositoryReleasesUrl), createDeprecatedAnnotation(lines[0], "\"$repositoryReleasesUrl\"") ) ), Arguments.of( lines[1], listOf( Repository("imagej-releases", repositoryReleasesUrl, "user", "pass"), createDeprecatedAnnotation( lines[1], "\"$repositoryReleasesUrl\", user=\"user\", password=\"pass\"" ) ) ), Arguments.of( lines[2], listOf( Repository("imagej-snapshots", repositorySnapshotsUrl, "user", "pass"), createDeprecatedAnnotation( lines[2], "\"$repositorySnapshotsUrl\", user=\"user\", password=\"pass\"" ) ) ), Arguments.of( lines[3], listOf( Repository("spaceAroundCredentials", repositorySnapshotsUrl, "user", "pass"), createDeprecatedAnnotation( lines[3], "\"$repositorySnapshotsUrl\", user=\"user\", password=\"pass\"" ) ) ), Arguments.of( lines[4], listOf( Repository("spaceAroundCredentials2", repositorySnapshotsUrl, "user", "pass"), createDeprecatedAnnotation( lines[4], "\"$repositorySnapshotsUrl\", user=\"user\", password=\"pass\"" ) ) ), Arguments.of( lines[5], listOf( Repository("unnamedCredentials", repositorySnapshotsUrl, "user", "pass"), createDeprecatedAnnotation( lines[5], "\"$repositorySnapshotsUrl\", user=\"user\", password=\"pass\"" ) ) ), Arguments.of( lines[6], listOf( Repository("imagej-releases", repositoryReleasesUrl, "user", "pass"), createDeprecatedAnnotation( lines[6], "\"$repositoryReleasesUrl\", user=\"user\", password=\"pass\"" ) ) ), Arguments.of( lines[7], listOf(Repository("", repositoryReleasesUrl, "", "")) ), Arguments.of( lines[8], listOf(Repository("", repositoryReleasesUrl, "user", "pass")) ), ) } @JvmStatic fun kotlinOptions(): Stream<Arguments> = Stream.of( Arguments.of( "//KOTLIN_OPTS -foo, 3 ,'some file.txt'", listOf( KotlinOpt("-foo"), KotlinOpt("3"), KotlinOpt("'some file.txt'"), DeprecatedItem( Location( 0, ScriptSource.HTTP, ScriptType.KT, URI.create("http://example/test.kt"), URI.create("http://example/"), "test" ), line = 1, message = "Deprecated annotation:\n//KOTLIN_OPTS -foo, 3 ,'some file.txt'\nshould be replaced with:\n@file:KotlinOptions(\"-foo\", \"3\", \"'some file.txt'\")" ) ) ), Arguments.of( """@file:KotlinOpts("--bar") // some other crazy comment""", listOf(KotlinOpt("--bar"), DeprecatedItem( Location( 0, ScriptSource.HTTP, ScriptType.KT, URI.create("http://example/test.kt"), URI.create("http://example/"), "test" ), line = 1, message = "Deprecated annotation:\n@file:KotlinOpts(\"--bar\") // some other crazy comment\nshould be replaced with:\n@file:KotlinOptions(\"--bar\")" )) ), Arguments.of( """@file:KotlinOptions("--bar") // some other crazy comment""", listOf(KotlinOpt("--bar")) ), ) @JvmStatic fun entryPoint(): Stream<Arguments> = Stream.of( Arguments.of("//ENTRY Foo", "Foo"), Arguments.of("@file:EntryPoint(\"Foo\")", "Foo"), ) } }
mit
d93b08bde8ae62c8c934723b251a9197
42.968354
183
0.538866
4.963916
false
true
false
false
yrsegal/CommandControl
src/main/java/wiresegal/cmdctrl/common/man/ManEntry.kt
1
1631
@file:Suppress("DEPRECATION") package wiresegal.cmdctrl.common.man import net.minecraft.command.ICommand import net.minecraft.command.ICommandSender import net.minecraft.util.text.ITextComponent import net.minecraft.util.text.TextComponentString import net.minecraft.util.text.translation.I18n import wiresegal.cmdctrl.common.CommandControl import java.util.* /** * @author WireSegal * Created at 5:00 PM on 12/6/16. */ class ManEntry(sender: ICommandSender, command: ICommand?, subcommand: String?) { val keys: List<String> var hasSub = false var subcom = "" init { val translationKeys = mutableListOf<String>() if (command != null) { val nameBase = command.getCommandUsage(sender) val manBase = "$nameBase.man" val subStr = (subcommand ?: "").toLowerCase(Locale.ROOT) val sub = "$nameBase.sub.$subStr.man" if (subcommand != null && I18n.canTranslate(sub)) { translationKeys.add(sub) var i = 1 while (I18n.canTranslate("$sub$i")) translationKeys.add("$sub${i++}") hasSub = true subcom = subcommand } else if (I18n.canTranslate(manBase)) { translationKeys.add(manBase) var i = 1 while (I18n.canTranslate("$manBase$i")) translationKeys.add("$manBase${i++}") } } keys = translationKeys } val asTextComponents: List<ITextComponent> get() = keys.map { TextComponentString(" | ").appendSibling(TextComponentString(CommandControl.translate(it))) } }
mit
dc0728e55e09e3fb4140f863e938deaf
32.285714
120
0.62477
4.139594
false
false
false
false
firebase/quickstart-android
database/app/src/main/java/com/google/firebase/quickstart/database/kotlin/BaseFragment.kt
1
651
package com.google.firebase.quickstart.database.kotlin import android.view.View import android.widget.ProgressBar import androidx.fragment.app.Fragment import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase open class BaseFragment : Fragment() { private var progressBar: ProgressBar? = null val uid: String get() = Firebase.auth.currentUser!!.uid fun setProgressBar(resId: Int) { progressBar = view?.findViewById(resId) } fun showProgressBar() { progressBar?.visibility = View.VISIBLE } fun hideProgressBar() { progressBar?.visibility = View.INVISIBLE } }
apache-2.0
87f9a1ff614d1bffc662a6e08f6ac646
24.076923
54
0.714286
4.458904
false
false
false
false
zlsun/kotlin-koans
src/ii_collections/_15_AllAnyAndOtherPredicates.kt
1
1115
package ii_collections fun example2(list: List<Int>) { val isZero: (Int) -> Boolean = { it == 0 } val hasZero: Boolean = list.any(isZero) val allZeros: Boolean = list.all(isZero) val numberOfZeros: Int = list.count(isZero) val firstPositiveNumber: Int? = list.firstOrNull { it > 0 } } fun Customer.isFrom(city: City): Boolean { // Return true if the customer is from the given city return this.city == city } fun Shop.checkAllCustomersAreFrom(city: City): Boolean { // Return true if all customers are from the given city return customers.all { it.isFrom(city) } } fun Shop.hasCustomerFrom(city: City): Boolean { // Return true if there is at least one customer from the given city return customers.any { it.isFrom(city) } } fun Shop.countCustomersFrom(city: City): Int { // Return the number of customers from the given city return customers.count { it.isFrom(city) } } fun Shop.findAnyCustomerFrom(city: City): Customer? { // Return a customer who lives in the given city, or null if there is none return customers.find { it.isFrom(city) } }
mit
f9cfccdf1acef420410f0a03ab01d934
27.589744
78
0.69148
3.729097
false
false
false
false
duftler/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/metrics/ZombieExecutionCheckingAgent.kt
1
4921
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.metrics import com.netflix.spectator.api.BasicTag import com.netflix.spectator.api.Registry import com.netflix.spectator.api.Tag import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.notifications.AbstractPollingNotificationAgent import com.netflix.spinnaker.orca.notifications.NotificationClusterLock import com.netflix.spinnaker.orca.pipeline.model.Execution import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.ORCHESTRATION import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.ExecutionLevel import com.netflix.spinnaker.q.metrics.MonitorableQueue import net.logstash.logback.argument.StructuredArguments.kv import org.slf4j.LoggerFactory import org.slf4j.MDC import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnBean import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression import org.springframework.stereotype.Component import rx.Scheduler import rx.schedulers.Schedulers import java.time.Clock import java.time.Duration import java.time.Instant import java.time.temporal.ChronoUnit.MINUTES import java.util.Optional /** * Monitors a queue and generates Atlas metrics. */ @Component @ConditionalOnExpression( "\${queue.zombie-check.enabled:false}") @ConditionalOnBean(MonitorableQueue::class) class ZombieExecutionCheckingAgent @Autowired constructor( private val queue: MonitorableQueue, private val registry: Registry, private val repository: ExecutionRepository, private val clock: Clock, private val conch: NotificationClusterLock, @Qualifier("scheduler") private val zombieCheckScheduler: Optional<Scheduler>, @Value("\${queue.zombie-check.interval-ms:3600000}") private val pollingIntervalMs: Long, @Value("\${queue.zombie-check.enabled:false}") private val zombieCheckEnabled: Boolean, @Value("\${queue.zombie-check.cutoff-minutes:10}") private val zombieCheckCutoffMinutes: Long, @Value("\${keiko.queue.enabled:true}") private val queueEnabled: Boolean ) : AbstractPollingNotificationAgent(conch) { private val log = LoggerFactory.getLogger(javaClass) override fun getPollingInterval() = pollingIntervalMs override fun getNotificationType() = javaClass.getSimpleName() override fun tick() { checkForZombies() } fun checkForZombies() { if (!queueEnabled) { return } if (!zombieCheckEnabled) { log.info("Not running zombie check: checkEnabled: $zombieCheckEnabled") return } try { MDC.put(AGENT_MDC_KEY, this.javaClass.simpleName) val startedAt = clock.instant() val criteria = ExecutionRepository.ExecutionCriteria().setStatuses(RUNNING) repository.retrieve(PIPELINE, criteria) .mergeWith(repository.retrieve(ORCHESTRATION, criteria)) .subscribeOn(zombieCheckScheduler.orElseGet(Schedulers::io)) .filter(this::hasBeenAroundAWhile) .filter(this::queueHasNoMessages) .doOnCompleted { log.info("Completed zombie check in ${Duration.between(startedAt, clock.instant())}") } .subscribe { log.error( "Found zombie {} {} {} {}", kv("executionType", it.type), kv("application", it.application), kv("executionName", it.name), kv("executionId", it.id) ) val tags = mutableListOf<Tag>( BasicTag("application", it.application), BasicTag("type", it.type.name) ) registry.counter("queue.zombies", tags).increment() } } finally { MDC.remove(AGENT_MDC_KEY) } } private fun hasBeenAroundAWhile(execution: Execution): Boolean = Instant.ofEpochMilli(execution.buildTime!!) .isBefore(clock.instant().minus(zombieCheckCutoffMinutes, MINUTES)) private fun queueHasNoMessages(execution: Execution): Boolean = !queue.containsMessage { message -> message is ExecutionLevel && message.executionId == execution.id } }
apache-2.0
a7df7cd818fccf3fa902317354f02538
37.445313
96
0.748019
4.358725
false
false
false
false
lena0204/Plattenspieler
app/src/main/java/com/lk/plattenspieler/fragments/LyricsAddingDialog.kt
1
1318
package com.lk.plattenspieler.fragments import android.app.* import android.content.Context import android.os.Bundle import android.widget.EditText import androidx.fragment.app.DialogFragment import com.lk.plattenspieler.R import com.lk.plattenspieler.main.MainActivityNew /** * Erstellt von Lena am 23.04.18. * Stellt einen Dialog mit Textfeld für das Hinzufügen von Liedtexten bereit */ class LyricsAddingDialog: DialogFragment(){ private lateinit var listener: OnSaveLyrics interface OnSaveLyrics{ fun onSaveLyrics(lyrics: String) } override fun onAttach(context: Context) { super.onAttach(context) listener = context as MainActivityNew } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { super.onCreateDialog(savedInstanceState) val li = activity?.layoutInflater val view = li?.inflate(R.layout.dialog_lyrics_adding, null) val et = view?.findViewById(R.id.et_lyrics_add) as EditText val builder = AlertDialog.Builder(activity?.applicationContext) builder.setTitle(R.string.dialog_title) builder.setView(view) builder.setPositiveButton(R.string.dialog_yes) { _, _ -> if(!et.text.isNullOrEmpty()){ listener.onSaveLyrics(et.text.toString()) } } builder.setNegativeButton(R.string.dialog_no) {_, _ -> dismiss() } return builder.create() } }
gpl-3.0
3575ca31d543556181d1ef7f5e1318a9
27.630435
76
0.762158
3.445026
false
false
false
false
axbaretto/beam
examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/snippets/Snippets.kt
3
16870
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UNUSED_VARIABLE") package org.apache.beam.examples.kotlin.snippets import com.google.api.services.bigquery.model.* import com.google.common.collect.ImmutableList import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.apache.beam.sdk.Pipeline import org.apache.beam.sdk.coders.AvroCoder import org.apache.beam.sdk.coders.DefaultCoder import org.apache.beam.sdk.coders.DoubleCoder import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition import org.apache.beam.sdk.io.gcp.bigquery.DynamicDestinations import org.apache.beam.sdk.io.gcp.bigquery.TableDestination import org.apache.beam.sdk.io.gcp.bigquery.WriteResult import org.apache.beam.sdk.transforms.* import org.apache.beam.sdk.transforms.join.CoGbkResult import org.apache.beam.sdk.transforms.join.CoGroupByKey import org.apache.beam.sdk.transforms.join.KeyedPCollectionTuple import org.apache.beam.sdk.values.* /** Code snippets used in webdocs. */ @Suppress("unused") object Snippets { val tableSchema: TableSchema by lazy { TableSchema().setFields( ImmutableList.of( TableFieldSchema() .setName("year") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("month") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("day") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("maxTemp") .setType("FLOAT") .setMode("NULLABLE"))) } @DefaultCoder(AvroCoder::class) internal class Quote( val source: String = "", val quote: String = "" ) @DefaultCoder(AvroCoder::class) internal class WeatherData( val year: Long = 0, val month: Long = 0, val day: Long = 0, val maxTemp: Double = 0.0 ) @JvmOverloads @SuppressFBWarnings("SE_BAD_FIELD") //Apparently findbugs doesn't like that a non-serialized object i.e. pipeline is being used inside the run{} block fun modelBigQueryIO( pipeline: Pipeline, writeProject: String = "", writeDataset: String = "", writeTable: String = "") { run { // [START BigQueryTableSpec] val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [END BigQueryTableSpec] } run { // [START BigQueryTableSpecWithoutProject] val tableSpec = "samples.weather_stations" // [END BigQueryTableSpecWithoutProject] } run { // [START BigQueryTableSpecObject] val tableSpec = TableReference() .setProjectId("clouddataflow-readonly") .setDatasetId("samples") .setTableId("weather_stations") // [END BigQueryTableSpecObject] } run { val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [START BigQueryReadTable] val maxTemperatures = pipeline.apply(BigQueryIO.readTableRows().from(tableSpec)) // Each row is of type TableRow .apply<PCollection<Double>>( MapElements.into(TypeDescriptors.doubles()) .via(SerializableFunction<TableRow, Double> { it["max_temperature"] as Double }) ) // [END BigQueryReadTable] } run { val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [START BigQueryReadFunction] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double } .from(tableSpec) .withCoder(DoubleCoder.of())) // [END BigQueryReadFunction] } run { // [START BigQueryReadQuery] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double } .fromQuery( "SELECT max_temperature FROM [clouddataflow-readonly:samples.weather_stations]") .withCoder(DoubleCoder.of())) // [END BigQueryReadQuery] } run { // [START BigQueryReadQueryStdSQL] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double } .fromQuery( "SELECT max_temperature FROM `clouddataflow-readonly.samples.weather_stations`") .usingStandardSql() .withCoder(DoubleCoder.of())) // [END BigQueryReadQueryStdSQL] } // [START BigQuerySchemaJson] val tableSchemaJson = ( "{" + " \"fields\": [" + " {" + " \"name\": \"source\"," + " \"type\": \"STRING\"," + " \"mode\": \"NULLABLE\"" + " }," + " {" + " \"name\": \"quote\"," + " \"type\": \"STRING\"," + " \"mode\": \"REQUIRED\"" + " }" + " ]" + "}") // [END BigQuerySchemaJson] run { var tableSpec = "clouddataflow-readonly:samples.weather_stations" if (writeProject.isNotEmpty() && writeDataset.isNotEmpty() && writeTable.isNotEmpty()) { tableSpec = "$writeProject:$writeDataset.$writeTable" } // [START BigQuerySchemaObject] val tableSchema = TableSchema() .setFields( ImmutableList.of( TableFieldSchema() .setName("source") .setType("STRING") .setMode("NULLABLE"), TableFieldSchema() .setName("quote") .setType("STRING") .setMode("REQUIRED"))) // [END BigQuerySchemaObject] // [START BigQueryWriteInput] /* @DefaultCoder(AvroCoder::class) class Quote( val source: String = "", val quote: String = "" ) */ val quotes = pipeline.apply( Create.of( Quote("Mahatma Gandhi", "My life is my message."), Quote("Yoda", "Do, or do not. There is no 'try'."))) // [END BigQueryWriteInput] // [START BigQueryWriteTable] quotes .apply<PCollection<TableRow>>( MapElements.into(TypeDescriptor.of(TableRow::class.java)) .via(SerializableFunction<Quote, TableRow> { TableRow().set("source", it.source).set("quote", it.quote) })) .apply<WriteResult>( BigQueryIO.writeTableRows() .to(tableSpec) .withSchema(tableSchema) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteTable] // [START BigQueryWriteFunction] quotes.apply<WriteResult>( BigQueryIO.write<Quote>() .to(tableSpec) .withSchema(tableSchema) .withFormatFunction { TableRow().set("source", it.source).set("quote", it.quote) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteFunction] // [START BigQueryWriteJsonSchema] quotes.apply<WriteResult>( BigQueryIO.write<Quote>() .to(tableSpec) .withJsonSchema(tableSchemaJson) .withFormatFunction { TableRow().set("source", it.source).set("quote", it.quote) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteJsonSchema] } run { // [START BigQueryWriteDynamicDestinations] /* @DefaultCoder(AvroCoder::class) class WeatherData( val year: Long = 0, val month: Long = 0, val day: Long = 0, val maxTemp: Double = 0.0 ) */ val weatherData = pipeline.apply( BigQueryIO.read { val record = it.record WeatherData( record.get("year") as Long, record.get("month") as Long, record.get("day") as Long, record.get("max_temperature") as Double) } .fromQuery(""" SELECT year, month, day, max_temperature FROM [clouddataflow-readonly:samples.weather_stations] WHERE year BETWEEN 2007 AND 2009 """.trimIndent()) .withCoder(AvroCoder.of(WeatherData::class.java))) // We will send the weather data into different tables for every year. weatherData.apply<WriteResult>( BigQueryIO.write<WeatherData>() .to( object : DynamicDestinations<WeatherData, Long>() { override fun getDestination(elem: ValueInSingleWindow<WeatherData>): Long? { return elem.value!!.year } override fun getTable(destination: Long?): TableDestination { return TableDestination( TableReference() .setProjectId(writeProject) .setDatasetId(writeDataset) .setTableId("${writeTable}_$destination"), "Table for year $destination") } override fun getSchema(destination: Long?): TableSchema { return tableSchema } }) .withFormatFunction { TableRow() .set("year", it.year) .set("month", it.month) .set("day", it.day) .set("maxTemp", it.maxTemp) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteDynamicDestinations] var tableSpec = "clouddataflow-readonly:samples.weather_stations" if (writeProject.isNotEmpty() && writeDataset.isNotEmpty() && writeTable.isNotEmpty()) { tableSpec = "$writeProject:$writeDataset.${writeTable}_partitioning" } // [START BigQueryTimePartitioning] weatherData.apply<WriteResult>( BigQueryIO.write<WeatherData>() .to("${tableSpec}_partitioning") .withSchema(tableSchema) .withFormatFunction { TableRow() .set("year", it.year) .set("month", it.month) .set("day", it.day) .set("maxTemp", it.maxTemp) } // NOTE: an existing table without time partitioning set up will not work .withTimePartitioning(TimePartitioning().setType("DAY")) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryTimePartitioning] } } /** Helper function to format results in coGroupByKeyTuple. */ fun formatCoGbkResults( name: String?, emails: Iterable<String>, phones: Iterable<String>): String { val emailsList = ArrayList<String>() for (elem in emails) { emailsList.add("'$elem'") } emailsList.sort() val emailsStr = "[${emailsList.joinToString(", ")}]" val phonesList = ArrayList<String>() for (elem in phones) { phonesList.add("'$elem'") } phonesList.sort() val phonesStr = "[${phonesList.joinToString(", ")}]" return "$name; $emailsStr; $phonesStr" } /** Using a CoGroupByKey transform. */ fun coGroupByKeyTuple( emailsTag: TupleTag<String>, phonesTag: TupleTag<String>, emails: PCollection<KV<String, String>>, phones: PCollection<KV<String, String>>): PCollection<String> { // [START CoGroupByKeyTuple] val results = KeyedPCollectionTuple.of(emailsTag, emails) .and(phonesTag, phones) .apply(CoGroupByKey.create()) // [END CoGroupByKeyTuple] return results.apply( ParDo.of( object : DoFn<KV<String, CoGbkResult>, String>() { @ProcessElement fun processElement(c: ProcessContext) { val e = c.element() val name = e.key val emailsIter = e.value.getAll(emailsTag) val phonesIter = e.value.getAll(phonesTag) val formattedResult = formatCoGbkResults(name, emailsIter, phonesIter) c.output(formattedResult) } })) } } /** Using a Read and Write transform to read/write from/to BigQuery. */
apache-2.0
241c2724b9025b2c50e163f4cb98ac31
44.106952
143
0.475993
5.403587
false
false
false
false