repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/properties/overrideKotlinPropertyByJavaMethod.kt | 2 | 849 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
// FILE: J.java
public class J implements K {
private String foo;
@Override
public String getFoo() {
return foo;
}
@Override
public void setFoo(String s) {
foo = s;
}
}
// FILE: K.kt
import kotlin.test.assertEquals
import kotlin.reflect.KParameter
interface K {
var foo: String
}
fun box(): String {
val p = J::foo
assertEquals("foo", p.name)
if (p.parameters.size != 1) return "Should have only 1 parameter"
if (p.parameters.single().kind != KParameter.Kind.INSTANCE) return "Should have an instance parameter"
if (J::class.members.none { it == p }) return "No foo in members"
val j = J()
p.setter.call(j, "OK")
return p.getter.call(j)
}
| apache-2.0 | 0d41c683b632e11c1e7464d4a62b734f | 19.214286 | 106 | 0.634865 | 3.508264 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/service/BlockaApiService.kt | 1 | 7326 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2022 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package service
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import model.*
import repository.Repos
import retrofit2.Call
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.*
import utils.Logger
import java.io.IOException
import java.net.UnknownHostException
object BlockaApiService {
private val http = HttpService
private val processingRepo by lazy { Repos.processing }
private val retrofit = Retrofit.Builder()
.baseUrl("https://api.blocka.net")
.addConverterFactory(MoshiConverterFactory.create(JsonSerializationService.moshi))
.client(http.getClient())
.build()
private val api = retrofit.create(BlockaRestApi::class.java)
suspend fun getAccount(id: AccountId): Account {
return runOnBgAndMapException {
api.getAccount(id).responseOrThrow().body()!!.account
}
}
suspend fun postNewAccount(): Account {
return runOnBgAndMapException {
api.postNewAccount().responseOrThrow().body()!!.account
}
}
suspend fun getDevice(id: AccountId): DevicePayload {
return runOnBgAndMapException {
api.getDevice(id).responseOrThrow().body()!!
}
}
suspend fun putDevice(request: DeviceRequest) {
return runOnBgAndMapException {
api.putDevice(request).responseOrThrow()
}
}
suspend fun getActivity(id: AccountId): List<Activity> {
return runOnBgAndMapException {
api.getActivity(id).responseOrThrow().body()!!.activity
}
}
suspend fun getCustomList(id: AccountId): List<CustomListEntry> {
return runOnBgAndMapException {
api.getCustomList(id).responseOrThrow().body()!!.customlist
}
}
suspend fun postCustomList(request: CustomListRequest) {
return runOnBgAndMapException {
api.postCustomList(request).responseOrThrow()
}
}
suspend fun deleteCustomList(request: CustomListRequest) {
return runOnBgAndMapException {
api.deleteCustomList(request).responseOrThrow()
}
}
suspend fun getStats(id: AccountId): CounterStats {
return runOnBgAndMapException {
api.getStats(id).responseOrThrow().body()!!
}
}
suspend fun getBlocklists(id: AccountId): List<Blocklist> {
return runOnBgAndMapException {
api.getBlocklists(id).responseOrThrow().body()!!.lists
}
}
suspend fun getGateways(): List<Gateway> {
return runOnBgAndMapException {
api.getGateways().responseOrThrow().body()!!.gateways
}
}
suspend fun getLeases(id: AccountId): List<Lease> {
return runOnBgAndMapException {
api.getLeases(id).responseOrThrow().body()!!.leases
}
}
suspend fun postLease(request: LeaseRequest): Lease {
return runOnBgAndMapException {
api.postLease(request).responseOrThrow().body()!!.lease
}
}
suspend fun deleteLease(request: LeaseRequest) {
return runOnBgAndMapException {
api.deleteLease(request).responseOrThrow()
}
}
suspend fun postGplayCheckout(request: GoogleCheckoutRequest): Account {
return runOnBgAndMapException {
api.postGplayCheckout(request).responseOrThrow().body()!!.account
}
}
// Will retry failed requests 3 times (with 3s delay in between)
private suspend fun <T> Call<T>.responseOrThrow(attempt: Int = 1): Response<T> {
try {
if (attempt > 1) Logger.w("Api", "Retrying request (attempt: $attempt): ${this.request().url()}")
val r = this.clone().execute()
return if (r.isSuccessful) r else when {
r.code() == 403 -> throw TooManyDevices()
r.code() in 500..599 && attempt < 3 -> {
// Retry on API server error
delay(3000)
this.responseOrThrow(attempt = attempt + 1)
}
else -> throw BlokadaException("Api response: ${r.code()}: ${r.errorBody()}")
}
} catch (ex: IOException) {
// Network connectivity problem, also retry
delay(3000)
if (attempt < 3) return this.responseOrThrow(attempt = attempt + 1)
else throw ex
}
}
private fun <T> Response<T>.resultOrThrow(): T {
if (!isSuccessful) when (code()) {
403 -> throw TooManyDevices()
else -> throw BlokadaException("Response: ${code()}: ${errorBody()}")
} else return body()!!
}
private suspend fun <T> runOnBgAndMapException(block: suspend () -> T): T {
try {
val result = withContext(Dispatchers.IO) {
block()
}
processingRepo.reportConnIssues("api", false)
processingRepo.reportConnIssues("timeout", false)
return result
} catch (ex: UnknownHostException) {
processingRepo.reportConnIssues("api", true)
throw BlokadaException("Connection problems", ex)
} catch (ex: BlokadaException) {
throw ex
} catch (ex: Exception) {
throw BlokadaException("Api request failed", ex)
}
}
}
interface BlockaRestApi {
@GET("/v2/account")
fun getAccount(@Query("account_id") id: AccountId): Call<AccountWrapper>
@POST("/v2/account")
fun postNewAccount(): Call<AccountWrapper>
@GET("/v2/device")
fun getDevice(@Query("account_id") id: AccountId): Call<DevicePayload>
@PUT("/v2/device")
fun putDevice(@Body request: DeviceRequest): Call<Void>
@GET("/v2/activity")
fun getActivity(@Query("account_id") id: AccountId): Call<ActivityWrapper>
@GET("/v2/customlist")
fun getCustomList(@Query("account_id") id: AccountId): Call<CustomListWrapper>
@POST("/v2/customlist")
fun postCustomList(@Body request: CustomListRequest): Call<Void>
@HTTP(method = "DELETE", path = "v1/customlist", hasBody = true)
fun deleteCustomList(@Body request: CustomListRequest): Call<Void>
@GET("/v2/stats")
fun getStats(@Query("account_id") id: AccountId): Call<CounterStats>
@GET("/v2/list")
fun getBlocklists(@Query("account_id") id: AccountId): Call<BlocklistWrapper>
@GET("/v2/gateway")
fun getGateways(): Call<Gateways>
@GET("/v2/lease")
fun getLeases(@Query("account_id") accountId: AccountId): Call<Leases>
@POST("/v2/lease")
fun postLease(@Body request: LeaseRequest): Call<LeaseWrapper>
@HTTP(method = "DELETE", path = "v1/lease", hasBody = true)
fun deleteLease(@Body request: LeaseRequest): Call<Void>
@POST("/v2/gplay/checkout")
fun postGplayCheckout(@Body request: GoogleCheckoutRequest): Call<AccountWrapper>
}
| mpl-2.0 | 62172275134c867efc793371ab5f833e | 30.9869 | 109 | 0.631399 | 4.601131 | false | false | false | false |
Flank/flank | flank-scripts/src/main/kotlin/flank/scripts/ops/dependencies/common/UpdateGradle.kt | 1 | 1719 | package flank.scripts.ops.dependencies
import flank.scripts.ops.dependencies.common.DependenciesResultCheck
import flank.scripts.ops.dependencies.common.GradleDependency
import flank.scripts.utils.toObject
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
internal fun File.updateGradle(gradleWrapperPropertiesPath: String = "") {
gradleDependency()
.takeIf { it.needsUpdate() }
?.let { gradleDependency -> updateGradleWrapper(gradleDependency, gradleWrapperPropertiesPath) }
}
private fun File.gradleDependency() = readText().toObject<DependenciesResultCheck>().gradle
internal fun GradleDependency.needsUpdate() = running.version < current.version || running.version < releaseCandidate.version
private fun updateGradleWrapper(gradleDependency: GradleDependency, gradleWrapperPropertiesPath: String) {
findAllGradleWrapperPropertiesFiles(gradleWrapperPropertiesPath)
.forEach {
val from = gradleDependency.running.version
val to = maxOf(gradleDependency.releaseCandidate.version, gradleDependency.current.version)
println("Update gradle wrapper $from to $to in file ${it.path}")
it.updateGradleWrapperPropertiesFile(from.toString(), to.toString())
}
}
private fun findAllGradleWrapperPropertiesFiles(gradleWrapperPropertiesPath: String) =
Files.walk(Paths.get(gradleWrapperPropertiesPath))
.filter { it.fileName.toString() == GRADLE_WRAPPER_PROPERTIES_FILE }
.map { it.toFile() }
private fun File.updateGradleWrapperPropertiesFile(from: String, to: String) = writeText(readText().replace(from, to))
private const val GRADLE_WRAPPER_PROPERTIES_FILE = "gradle-wrapper.properties"
| apache-2.0 | 65223430b5920511ba9b6dc1a244d0a8 | 45.459459 | 125 | 0.769052 | 4.645946 | false | false | false | false |
Pattonville-App-Development-Team/Android-App | app/src/main/java/org/pattonvillecs/pattonvilleapp/service/model/calendar/PinnedEventMarker.kt | 1 | 2330 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* 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 org.pattonvillecs.pattonvilleapp.service.model.calendar
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.ForeignKey
import android.arch.persistence.room.PrimaryKey
import org.pattonvillecs.pattonvilleapp.service.model.calendar.event.CalendarEvent
import org.pattonvillecs.pattonvilleapp.service.model.calendar.event.ICalendarEvent
/**
* This class is a database row that contains the UID of a calendar event. If an event has a corresponding [PinnedEventMarker], that event is considered pinned.
*
* @author Mitchell Skaggs
* @since 1.2.0
*/
@Entity(tableName = "pinned_event_markers",
foreignKeys = [(ForeignKey(entity = CalendarEvent::class,
parentColumns = ["uid"],
childColumns = ["uid"],
onDelete = ForeignKey.CASCADE,
deferred = true))])
data class PinnedEventMarker(@field:PrimaryKey
@field:ColumnInfo(name = "uid", index = true, collate = ColumnInfo.BINARY)
val uid: String) {
constructor(calendarEvent: ICalendarEvent) : this(calendarEvent.uid)
companion object {
/**
* A utility method to create a marker for an event.
*
* @receiver the [CalendarEvent] from which to take a UID
* @return a [PinnedEventMarker] using this [CalendarEvent]'s UID
*/
@JvmStatic
fun ICalendarEvent.pin(): PinnedEventMarker = PinnedEventMarker(this)
}
}
| gpl-3.0 | f1b6a8e0c2e7ed0c48724d2c91cf9273 | 40.607143 | 160 | 0.701288 | 4.595661 | false | false | false | false |
siosio/intellij-community | platform/platform-tests/testSrc/com/intellij/ide/plugins/PluginDescriptorTest.kt | 1 | 20309 | // 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:Suppress("UsePropertyAccessSyntax")
package com.intellij.ide.plugins
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.io.IoTestUtil
import com.intellij.platform.util.plugins.DataLoader
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.util.NoOpXmlInterner
import com.intellij.util.io.directoryStreamIfExists
import com.intellij.util.io.write
import com.intellij.util.lang.UrlClassLoader
import com.intellij.util.lang.ZipFilePool
import junit.framework.TestCase
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.intellij.lang.annotations.Language
import org.junit.Assume.assumeTrue
import org.junit.Rule
import org.junit.Test
import java.io.File
import java.net.URL
import java.net.URLClassLoader
import java.nio.file.Path
import java.nio.file.Paths
import java.text.SimpleDateFormat
import java.util.*
import java.util.function.Function
import java.util.function.Supplier
import kotlin.test.assertEquals
import kotlin.test.assertFalse
private fun loadDescriptors(dir: Path, buildNumber: BuildNumber, disabledPlugins: Set<PluginId> = emptySet()): DescriptorListLoadingContext {
val context = DescriptorListLoadingContext(disabledPlugins = disabledPlugins,
result = PluginLoadingResult(emptyMap(), Supplier { buildNumber }))
// constant order in tests
val paths: List<Path> = dir.directoryStreamIfExists { it.sorted() }!!
context.use {
for (file in paths) {
val descriptor = loadDescriptor(file, false, context) ?: continue
context.result.add(descriptor, false)
}
}
context.result.finishLoading()
return context
}
private fun loadAndInitDescriptors(dir: Path, buildNumber: BuildNumber, disabledPlugins: Set<PluginId> = emptySet()): PluginManagerState {
return PluginManagerCore.initializePlugins(loadDescriptors(dir, buildNumber, disabledPlugins), UrlClassLoader.build().get(), false)
}
class PluginDescriptorTest {
@Rule
@JvmField
val inMemoryFs = InMemoryFsRule()
@Test
fun descriptorLoading() {
val descriptor = loadDescriptorInTest("asp.jar")
assertThat(descriptor).isNotNull()
assertThat(descriptor.pluginId.idString).isEqualTo("com.jetbrains.plugins.asp")
assertThat(descriptor.name).isEqualTo("ASP")
}
@Test
fun testOptionalDescriptors() {
val descriptor = loadDescriptorInTest("family")
assertThat(descriptor).isNotNull()
assertThat(descriptor.pluginDependencies.size).isEqualTo(1)
}
@Test
fun testMultipleOptionalDescriptors() {
val descriptor = loadDescriptorInTest("multipleOptionalDescriptors")
assertThat(descriptor).isNotNull()
val pluginDependencies = descriptor.pluginDependencies
assertThat(pluginDependencies).hasSize(2)
assertThat(pluginDependencies.map { it.pluginId.idString }).containsExactly("dep2", "dep1")
}
@Test
fun testMalformedDescriptor() {
assertThatThrownBy { loadDescriptorInTest("malformed") }
.hasMessageContaining("Unexpected character 'o' (code 111) in prolog")
}
@Test
fun nameAsId() {
val descriptor = loadDescriptorInTest(Path.of(testDataPath, "anonymous"))
assertThat(descriptor.pluginId.idString).isEqualTo("test")
assertThat(descriptor.name).isEqualTo("test")
}
@Test
fun testCyclicOptionalDeps() {
assertThatThrownBy { loadDescriptorInTest("cyclicOptionalDeps") }
.hasMessageEndingWith(" optional descriptors form a cycle: a.xml, b.xml")
}
@Test
fun testFilteringDuplicates() {
val urls = arrayOf(
Path.of(testDataPath, "duplicate1.jar").toUri().toURL(),
Path.of(testDataPath, "duplicate2.jar").toUri().toURL()
)
assertThat(testLoadDescriptorsFromClassPath(URLClassLoader(urls, null))).hasSize(1)
}
@Test
fun testProductionPlugins() {
IoTestUtil.assumeMacOS()
assumeNotUnderTeamcity()
val descriptors = loadAndInitDescriptors(Paths.get("/Applications/Idea.app/Contents/plugins"), PluginManagerCore.getBuildNumber()).pluginSet.allPlugins
assertThat(descriptors).isNotEmpty()
assertThat(descriptors.find { it.pluginId.idString == "com.intellij.java" }).isNotNull
}
@Test
fun testProductionProductLib() {
IoTestUtil.assumeMacOS()
assumeNotUnderTeamcity()
val urls = ArrayList<URL>()
Paths.get("/Applications/Idea.app/Contents/lib").directoryStreamIfExists {
for (path in it) {
urls.add(path.toUri().toURL())
}
}
val descriptors = testLoadDescriptorsFromClassPath(URLClassLoader(urls.toTypedArray(), null))
// core and com.intellij.workspace
assertThat(descriptors).hasSize(1)
}
@Test
fun testProduction2() {
IoTestUtil.assumeMacOS()
assumeNotUnderTeamcity()
val descriptors = loadAndInitDescriptors(Paths.get("/Volumes/data/plugins"), PluginManagerCore.getBuildNumber()).pluginSet.allPlugins
assertThat(descriptors).isNotEmpty()
}
private fun assumeNotUnderTeamcity() {
assumeTrue("Must not be run under TeamCity", !UsefulTestCase.IS_UNDER_TEAMCITY)
}
@Test
fun testDuplicateDependency() {
val descriptor = loadDescriptorInTest("duplicateDependency")
assertThat(descriptor).isNotNull()
assertThat(descriptor.pluginDependencies.filter { it.isOptional }).isEmpty()
assertThat(descriptor.pluginDependencies.map { it.pluginId }).containsExactly(PluginId.getId("foo"))
}
@Test
fun testPluginNameAsId() {
val descriptor = loadDescriptorInTest("noId")
assertThat(descriptor).isNotNull()
assertThat(descriptor.pluginId.idString).isEqualTo(descriptor.name)
}
@Test
fun releaseDate() {
val pluginFile = inMemoryFs.fs.getPath("plugin/META-INF/plugin.xml")
val descriptor = readDescriptorForTest(pluginFile, false, """
<idea-plugin>
<id>bar</id>
<vendor>JetBrains</vendor>
<product-descriptor code="IJ" release-date="20190811" release-version="42" optional="true"/>
</idea-plugin>""".encodeToByteArray())
assertThat(descriptor).isNotNull()
assertThat(descriptor.vendor).isEqualTo("JetBrains")
assertThat(SimpleDateFormat("yyyyMMdd", Locale.US).format(descriptor.releaseDate)).isEqualTo("20190811")
assertThat(descriptor.isLicenseOptional).isTrue()
}
@Suppress("PluginXmlValidity")
@Test
fun `use newer plugin`() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
writeDescriptor("foo_1-0", pluginDir, """
<idea-plugin>
<id>foo</id>
<vendor>JetBrains</vendor>
<version>1.0</version>
</idea-plugin>""")
writeDescriptor("foo_2-0", pluginDir, """
<idea-plugin>
<id>foo</id>
<vendor>JetBrains</vendor>
<version>2.0</version>
</idea-plugin>""")
val pluginSet = loadAndInitDescriptors(pluginDir, PluginManagerCore.getBuildNumber()).pluginSet
val plugins = pluginSet.enabledPlugins
assertThat(plugins).hasSize(1)
val foo = plugins[0]
assertThat(foo.version).isEqualTo("2.0")
assertThat(foo.pluginId.idString).isEqualTo("foo")
assertThat(pluginSet.allPlugins.toList()).map(Function { it.id }).containsOnly(foo.pluginId)
assertThat(pluginSet.findEnabledPlugin(foo.pluginId)).isSameAs(foo)
}
@Suppress("PluginXmlValidity")
@Test
fun `use newer plugin if disabled`() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
writeDescriptor("foo_3-0", pluginDir, """
<idea-plugin>
<id>foo</id>
<vendor>JetBrains</vendor>
<version>1.0</version>
</idea-plugin>""")
writeDescriptor("foo_2-0", pluginDir, """
<idea-plugin>
<id>foo</id>
<vendor>JetBrains</vendor>
<version>2.0</version>
</idea-plugin>""")
val context = loadDescriptors(pluginDir, PluginManagerCore.getBuildNumber(), setOf(PluginId.getId("foo")))
val plugins = context.result.incompletePlugins
assertThat(plugins).hasSize(1)
val foo = plugins.values.single()
assertThat(foo.version).isEqualTo("2.0")
assertThat(foo.pluginId.idString).isEqualTo("foo")
}
@Suppress("PluginXmlValidity")
@Test
fun `prefer bundled if custom is incompatible`() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
// names are important - will be loaded in alphabetical order
writeDescriptor("foo_1-0", pluginDir, """
<idea-plugin>
<id>foo</id>
<vendor>JetBrains</vendor>
<version>2.0</version>
<idea-version until-build="2"/>
</idea-plugin>""")
writeDescriptor("foo_2-0", pluginDir, """
<idea-plugin>
<id>foo</id>
<vendor>JetBrains</vendor>
<version>2.0</version>
<idea-version until-build="4"/>
</idea-plugin>""")
val result = loadDescriptors(pluginDir, BuildNumber.fromString("4.0")!!).result
assertThat(result.hasPluginErrors).isFalse()
val plugins = result.getEnabledPlugins()
assertThat(plugins).hasSize(1)
assertThat(result.duplicateModuleMap).isNull()
assertThat(result.incompletePlugins).isEmpty()
val foo = plugins[0]
assertThat(foo.version).isEqualTo("2.0")
assertThat(foo.pluginId.idString).isEqualTo("foo")
assertThat(result.idMap).containsOnlyKeys(foo.pluginId)
assertThat(result.idMap.get(foo.pluginId)).isSameAs(foo)
}
@Suppress("PluginXmlValidity")
@Test
fun `select compatible plugin if both versions provided`() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
writeDescriptor("foo_1-0", pluginDir, """
<idea-plugin>
<id>foo</id>
<vendor>JetBrains</vendor>
<version>1.0</version>
<idea-version since-build="1.*" until-build="2.*"/>
</idea-plugin>""")
writeDescriptor("foo_2-0", pluginDir, """
<idea-plugin>
<id>foo</id>
<vendor>JetBrains</vendor>
<version>2.0</version>
<idea-version since-build="2.0" until-build="4.*"/>
</idea-plugin>""")
val pluginSet = loadAndInitDescriptors(pluginDir, BuildNumber.fromString("3.12")!!).pluginSet
val plugins = pluginSet.enabledPlugins
assertThat(plugins).hasSize(1)
val foo = plugins[0]
assertThat(foo.version).isEqualTo("2.0")
assertThat(foo.pluginId.idString).isEqualTo("foo")
assertThat(pluginSet.allPlugins.toList()).map(Function { it.id }).containsOnly(foo.pluginId)
assertThat(pluginSet.findEnabledPlugin(foo.pluginId)).isSameAs(foo)
}
@Suppress("PluginXmlValidity")
@Test
fun `use first plugin if both versions the same`() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
PluginBuilder().noDepends().id("foo").version("1.0").build(pluginDir.resolve("foo_1-0"))
PluginBuilder().noDepends().id("foo").version("1.0").build(pluginDir.resolve("foo_another"))
val pluginSet = loadAndInitDescriptors(pluginDir, PluginManagerCore.getBuildNumber()).pluginSet
val plugins = pluginSet.enabledPlugins
assertThat(plugins).hasSize(1)
val foo = plugins[0]
assertThat(foo.version).isEqualTo("1.0")
assertThat(foo.pluginId.idString).isEqualTo("foo")
assertThat(pluginSet.allPlugins.toList()).map(Function { it.id }).containsOnly(foo.pluginId)
assertThat(pluginSet.findEnabledPlugin(foo.pluginId)).isSameAs(foo)
}
@Suppress("PluginXmlValidity")
@Test
fun classLoader() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
PluginBuilder().noDepends().id("foo").depends("bar").build(pluginDir.resolve("foo"))
PluginBuilder().noDepends().id("bar").build(pluginDir.resolve("bar"))
checkClassLoader(pluginDir)
}
@Suppress("PluginXmlValidity")
@Test
fun `classLoader - optional dependency`() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
writeDescriptor("foo", pluginDir, """
<idea-plugin>
<id>foo</id>
<depends optional="true" config-file="stream-debugger.xml">bar</depends>
<vendor>JetBrains</vendor>
</idea-plugin>
""")
pluginDir.resolve("foo/META-INF/stream-debugger.xml").write("""
<idea-plugin>
<actions>
</actions>
</idea-plugin>
""")
writeDescriptor("bar", pluginDir, """
<idea-plugin>
<id>bar</id>
<vendor>JetBrains</vendor>
</idea-plugin>
""")
checkClassLoader(pluginDir)
}
private fun checkClassLoader(pluginDir: Path) {
val list = loadAndInitDescriptors(pluginDir, PluginManagerCore.getBuildNumber()).pluginSet.enabledPlugins
assertThat(list).hasSize(2)
val bar = list[0]
assertThat(bar.pluginId.idString).isEqualTo("bar")
val foo = list[1]
assertThat(foo.pluginDependencies.map { it.pluginId }).containsExactly(bar.pluginId)
assertThat(foo.pluginId.idString).isEqualTo("foo")
val fooClassLoader = foo.pluginClassLoader as PluginClassLoader
assertThat(fooClassLoader._getParents()).containsExactly(bar)
}
@Test
fun componentConfig() {
val pluginFile = inMemoryFs.fs.getPath("/plugin/META-INF/plugin.xml")
pluginFile.write("<idea-plugin>\n <id>bar</id>\n <project-components>\n <component>\n <implementation-class>com.intellij.ide.favoritesTreeView.FavoritesManager</implementation-class>\n <option name=\"workspace\" value=\"true\"/>\n </component>\n\n \n </project-components>\n</idea-plugin>")
val descriptor = loadDescriptorInTest(pluginFile.parent.parent)
assertThat(descriptor).isNotNull
assertThat(descriptor.projectContainerDescriptor.components!![0].options).isEqualTo(Collections.singletonMap("workspace", "true"))
}
@Test
fun testPluginIdAsName() {
val descriptor = loadDescriptorInTest("noName")
assertThat(descriptor).isNotNull()
assertThat(descriptor.name).isEqualTo(descriptor.pluginId.idString)
}
@Test
fun testUrlTolerance() {
class SingleUrlEnumeration(private val myUrl: URL) : Enumeration<URL> {
private var hasMoreElements = true
override fun hasMoreElements(): Boolean {
return hasMoreElements
}
override fun nextElement(): URL {
if (!hasMoreElements) throw NoSuchElementException()
hasMoreElements = false
return myUrl
}
}
class TestLoader(prefix: String, suffix: String) : UrlClassLoader(build(), false) {
private val url = URL(prefix + File(testDataPath).toURI().toURL().toString() + suffix + "META-INF/plugin.xml")
override fun getResource(name: String) = null
override fun getResources(name: String) = SingleUrlEnumeration(url)
}
val loader1 = TestLoader("", "/spaces%20spaces/")
TestCase.assertEquals(1, testLoadDescriptorsFromClassPath(loader1).size)
val loader2 = TestLoader("", "/spaces spaces/")
TestCase.assertEquals(1, testLoadDescriptorsFromClassPath(loader2).size)
val loader3 = TestLoader("jar:", "/jar%20spaces.jar!/")
TestCase.assertEquals(1, testLoadDescriptorsFromClassPath(loader3).size)
val loader4 = TestLoader("jar:", "/jar spaces.jar!/")
assertThat(testLoadDescriptorsFromClassPath(loader4)).hasSize(1)
}
@Test
fun testEqualityById() {
val fs = inMemoryFs.fs
val tempFile = fs.getPath("/", PluginManagerCore.PLUGIN_XML_PATH)
tempFile.write("""
<idea-plugin>
<id>ID</id>
<name>A</name>
</idea-plugin>""")
val impl1 = loadDescriptorInTest(fs.getPath("/"))
tempFile.write("""
<idea-plugin>
<id>ID</id>
<name>B</name>
</idea-plugin>""")
val impl2 = loadDescriptorInTest(fs.getPath("/"))
TestCase.assertEquals(impl1, impl2)
TestCase.assertEquals(impl1.hashCode(), impl2.hashCode())
TestCase.assertNotSame(impl1.name, impl2.name)
}
@Test
fun testLoadDisabledPlugin() {
val descriptor = loadDescriptorInTest("disabled", setOf(PluginId.getId("com.intellij.disabled")))
assertFalse(descriptor.isEnabled)
assertEquals("This is a disabled plugin", descriptor.description)
assertThat(descriptor.pluginDependencies.map { it.pluginId.idString }).containsExactly("com.intellij.modules.lang")
}
@Test
fun testLoadPluginWithDisabledDependency() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
PluginBuilder().noDepends().id("foo").depends("bar").build(pluginDir.resolve("foo"))
PluginBuilder().noDepends().id("bar").build(pluginDir.resolve("bar"))
val pluginSet = loadAndInitDescriptors(pluginDir, PluginManagerCore.getBuildNumber(), setOf(PluginId.getId("bar"))).pluginSet
assertThat(pluginSet.enabledPlugins).isEmpty()
}
@Test
fun testLoadPluginWithDisabledTransitiveDependency() {
val pluginDir = inMemoryFs.fs.getPath("/plugins")
PluginBuilder()
.noDepends()
.id("org.jetbrains.plugins.gradle.maven")
.implementationDetail()
.depends("org.jetbrains.plugins.gradle")
.build(pluginDir.resolve("intellij.gradle.java.maven"))
PluginBuilder()
.noDepends()
.id("org.jetbrains.plugins.gradle")
.depends("com.intellij.gradle")
.implementationDetail()
.build(pluginDir.resolve("intellij.gradle.java"))
PluginBuilder()
.noDepends()
.id("com.intellij.gradle")
.build(pluginDir.resolve("intellij.gradle"))
val result = loadAndInitDescriptors(pluginDir, PluginManagerCore.getBuildNumber(), setOf(PluginId.getId("com.intellij.gradle"))).pluginSet
assertThat(result.enabledPlugins).isEmpty()
}
}
private fun writeDescriptor(id: String, pluginDir: Path, @Language("xml") data: String) {
pluginDir.resolve("$id/META-INF/plugin.xml").write(data.trimIndent())
}
private val testDataPath: String
get() = "${PlatformTestUtil.getPlatformTestDataPath()}plugins/pluginDescriptor"
private fun loadDescriptorInTest(dirName: String, disabledPlugins: Set<PluginId> = emptySet()): IdeaPluginDescriptorImpl {
return loadDescriptorInTest(Path.of(testDataPath, dirName), disabledPlugins)
}
fun readDescriptorForTest(path: Path, isBundled: Boolean, input: ByteArray, id: PluginId? = null): IdeaPluginDescriptorImpl {
val pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER
val dataLoader = object : DataLoader {
override val pool: ZipFilePool?
get() = null
override fun load(path: String) = throw UnsupportedOperationException()
override fun toString() = throw UnsupportedOperationException()
}
val raw = readModuleDescriptor(
input = input,
readContext = object : ReadModuleContext {
override val interner = NoOpXmlInterner
override val isMissingIncludeIgnored: Boolean
get() = false
},
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = path.toString()
)
if (id != null) {
raw.id = id.idString
}
val result = IdeaPluginDescriptorImpl(raw = raw, path = path, isBundled = isBundled, id = id)
result.readExternal(
raw = raw,
isSub = false,
context = DescriptorListLoadingContext(disabledPlugins = Collections.emptySet()),
pathResolver = pathResolver,
dataLoader = dataLoader
)
return result
}
fun createFromDescriptor(path: Path,
isBundled: Boolean,
data: ByteArray,
context: DescriptorListLoadingContext,
pathResolver: PathResolver,
dataLoader: DataLoader): IdeaPluginDescriptorImpl {
val raw = readModuleDescriptor(input = data,
readContext = context,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = null,
readInto = null,
locationSource = path.toString())
val result = IdeaPluginDescriptorImpl(raw = raw, path = path, isBundled = isBundled, id = null)
result.readExternal(raw = raw,
pathResolver = pathResolver,
context = context,
isSub = false,
dataLoader = dataLoader)
return result
} | apache-2.0 | fe044fd1849e47ab967646b103bf0ea5 | 35.726944 | 316 | 0.697622 | 4.548488 | false | true | false | false |
siosio/intellij-community | plugins/git-features-trainer/src/git4idea/ift/lesson/GitAnnotateLesson.kt | 1 | 14552 | // 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 git4idea.ift.lesson
import com.intellij.diff.impl.DiffWindowBase
import com.intellij.diff.tools.util.DiffSplitter
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorBundle
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.vcs.actions.ActiveAnnotationGutter
import com.intellij.openapi.vcs.actions.AnnotateToggleAction
import com.intellij.openapi.vcs.changes.VcsEditorTabFilesManager
import com.intellij.openapi.vcs.changes.ui.ChangeListViewerDialog
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.UIUtil
import git4idea.ift.GitLessonsBundle
import git4idea.ift.GitLessonsUtil.checkoutBranch
import training.dsl.*
import training.dsl.LessonUtil.adjustPopupPosition
import training.dsl.LessonUtil.restorePopupPosition
import training.learn.LearnBundle
import java.awt.Component
import java.awt.Point
import java.awt.Rectangle
import java.util.concurrent.CompletableFuture
import javax.swing.JEditorPane
class GitAnnotateLesson : GitLesson("Git.Annotate", GitLessonsBundle.message("git.annotate.lesson.name")) {
override val existedFile = "git/martian_cat.yml"
private val branchName = "main"
private val propertyName = "ears_number"
private val editedPropertyName = "ear_number"
private val firstStateText = "ears_number: 4"
private val secondStateText = "ear_number: 4"
private val thirdStateText = "ear_number: 2"
private val partOfTargetCommitMessage = "Edit ear number of martian cat"
private var backupDiffLocation: Point? = null
private var backupRevisionsLocation: Point? = null
override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true)
override val lessonContent: LessonContext.() -> Unit = {
checkoutBranch(branchName)
val annotateActionName = ActionsBundle.message("action.Annotate.text").dropMnemonic()
task {
text(GitLessonsBundle.message("git.annotate.introduction", strong(annotateActionName)))
triggerByPartOfComponent l@{ ui: EditorComponentImpl ->
val startOffset = ui.editor.document.charsSequence.indexOf(firstStateText)
if (startOffset == -1) return@l null
val endOffset = startOffset + firstStateText.length
val startPoint = ui.editor.offsetToXY(startOffset)
val endPoint = ui.editor.offsetToXY(endOffset)
Rectangle(startPoint.x - 3, startPoint.y, endPoint.x - startPoint.x + 6, ui.editor.lineHeight)
}
proceedLink()
}
val annotateMenuItemText = ActionsBundle.message("action.Annotate.with.Blame.text").dropMnemonic()
if (isAnnotateShortcutSet()) {
task("Annotate") {
text(GitLessonsBundle.message("git.annotate.invoke.shortcut.1", action(it)))
trigger(it)
}
}
else {
task {
highlightGutterComponent(null, firstStateText, highlightRight = true)
}
task {
text(GitLessonsBundle.message("git.annotate.open.context.menu"))
text(GitLessonsBundle.message("git.annotate.click.gutter.balloon"), LearningBalloonConfig(Balloon.Position.atRight, 0))
highlightAnnotateMenuItem()
}
task("Annotate") {
val addShortcutText = LearnBundle.message("shortcut.balloon.add.shortcut")
text(GitLessonsBundle.message("git.annotate.choose.annotate", strong(annotateMenuItemText)))
text(GitLessonsBundle.message("git.annotate.add.shortcut.tip", strong(annotateActionName), action(it), strong(addShortcutText)))
trigger(it)
restoreByUi()
}
}
task {
highlightAnnotation(null, firstStateText, highlightRight = true)
}
val showDiffText = ActionsBundle.message("action.Diff.ShowDiff.text")
lateinit var openFirstDiffTaskId: TaskContext.TaskId
task {
openFirstDiffTaskId = taskId
text(GitLessonsBundle.message("git.annotate.feature.explanation", strong(annotateActionName), strong("Johnny Catsville")))
text(GitLessonsBundle.message("git.annotate.click.annotation.tooltip"), LearningBalloonConfig(Balloon.Position.above, 0))
highlightShowDiffMenuItem()
}
var firstDiffSplitter: DiffSplitter? = null
task {
text(GitLessonsBundle.message("git.annotate.choose.show.diff", strong(showDiffText)))
trigger("com.intellij.openapi.vcs.actions.ShowDiffFromAnnotation")
restoreByUi(delayMillis = defaultRestoreDelay)
}
task {
triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: EditorComponentImpl ->
if (ui.editor.document.charsSequence.contains(secondStateText)) {
firstDiffSplitter = UIUtil.getParentOfType(DiffSplitter::class.java, ui)
true
}
else false
}
}
prepareRuntimeTask l@{
if (backupDiffLocation == null) {
backupDiffLocation = adjustPopupPosition(DiffWindowBase.DEFAULT_DIALOG_GROUP_KEY)
}
}
if (isAnnotateShortcutSet()) {
task("Annotate") {
text(GitLessonsBundle.message("git.annotate.go.deeper", code(propertyName)) + " "
+ GitLessonsBundle.message("git.annotate.invoke.shortcut.2", action(it)))
triggerOnAnnotationsShown(firstDiffSplitter, secondStateText)
restoreIfDiffClosed(openFirstDiffTaskId, firstDiffSplitter)
}
} else {
task {
highlightGutterComponent(firstDiffSplitter, secondStateText, highlightRight = false)
}
task {
text(GitLessonsBundle.message("git.annotate.go.deeper", code(propertyName)) + " "
+ GitLessonsBundle.message("git.annotate.invoke.manually", strong(annotateMenuItemText)))
text(GitLessonsBundle.message("git.annotate.click.gutter.balloon"), LearningBalloonConfig(Balloon.Position.atLeft, 0))
val annotateItemFuture = highlightAnnotateMenuItem()
triggerOnAnnotationsShown(firstDiffSplitter, secondStateText)
restoreIfDiffClosed(openFirstDiffTaskId, firstDiffSplitter)
restartTaskIfMenuClosed(annotateItemFuture)
}
}
var secondDiffSplitter: DiffSplitter? = null
lateinit var openSecondDiffTaskId: TaskContext.TaskId
task {
openSecondDiffTaskId = taskId
text(GitLessonsBundle.message("git.annotate.show.diff", strong(showDiffText)))
highlightAnnotation(firstDiffSplitter, secondStateText, highlightRight = false)
val showDiffItemFuture = highlightShowDiffMenuItem()
triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: EditorComponentImpl ->
if (ui.editor.document.charsSequence.contains(thirdStateText)) {
secondDiffSplitter = UIUtil.getParentOfType(DiffSplitter::class.java, ui)
true
}
else false
}
restoreIfDiffClosed(openFirstDiffTaskId, firstDiffSplitter)
restartTaskIfMenuClosed(showDiffItemFuture)
}
if (isAnnotateShortcutSet()) {
task("Annotate") {
text(GitLessonsBundle.message("git.annotate.found.needed.commit", code(editedPropertyName)) + " "
+ GitLessonsBundle.message("git.annotate.invoke.shortcut.3", action(it)))
triggerOnAnnotationsShown(secondDiffSplitter, secondStateText)
restoreIfDiffClosed(openSecondDiffTaskId, secondDiffSplitter)
}
} else {
task {
text(GitLessonsBundle.message("git.annotate.found.needed.commit", code(editedPropertyName)) + " "
+ GitLessonsBundle.message("git.annotate.invoke.manually", strong(annotateMenuItemText)))
highlightGutterComponent(secondDiffSplitter, secondStateText, highlightRight = true)
val annotateItemFuture = highlightAnnotateMenuItem()
triggerOnAnnotationsShown(secondDiffSplitter, secondStateText)
restoreIfDiffClosed(openSecondDiffTaskId, secondDiffSplitter)
restartTaskIfMenuClosed(annotateItemFuture)
}
}
task {
text(GitLessonsBundle.message("git.annotate.click.annotation"))
highlightAnnotation(secondDiffSplitter, secondStateText, highlightRight = true)
triggerByUiComponentAndHighlight(highlightInside = false) { ui: JEditorPane ->
ui.text?.contains(partOfTargetCommitMessage) == true
}
restoreIfDiffClosed(openSecondDiffTaskId, secondDiffSplitter)
}
task("EditorEscape") {
before {
if (backupRevisionsLocation == null) {
backupRevisionsLocation = adjustPopupPosition(ChangeListViewerDialog.DIMENSION_SERVICE_KEY)
}
}
text(GitLessonsBundle.message("git.annotate.close.all.windows", code(editedPropertyName),
if (VcsEditorTabFilesManager.getInstance().shouldOpenInNewWindow) 0 else 1, action(it)))
stateCheck {
previous.ui?.isShowing != true && firstDiffSplitter?.isShowing != true && secondDiffSplitter?.isShowing != true
}
}
if (isAnnotateShortcutSet()) {
task("Annotate") {
text(GitLessonsBundle.message("git.annotate.close.annotations") + " "
+ GitLessonsBundle.message("git.annotate.close.by.shortcut", action(it)))
stateCheck { !isAnnotationsShown(editor) }
}
} else {
task("Annotate") {
val closeAnnotationsText = EditorBundle.message("close.editor.annotations.action.name")
text(GitLessonsBundle.message("git.annotate.close.annotations") + " "
+ GitLessonsBundle.message("git.annotate.invoke.manually.2", strong(closeAnnotationsText)))
triggerByPartOfComponent { ui: EditorGutterComponentEx ->
Rectangle(ui.x + ui.annotationsAreaOffset, ui.y, ui.annotationsAreaWidth, ui.height)
}
val closeAnnotationsItemFuture = CompletableFuture<ActionMenuItem>()
triggerByUiComponentAndHighlight(highlightInside = false) { ui: ActionMenuItem ->
(ui.text?.contains(closeAnnotationsText) == true).also {
if (it) closeAnnotationsItemFuture.complete(ui)
}
}
stateCheck { !isAnnotationsShown(editor) }
restartTaskIfMenuClosed(closeAnnotationsItemFuture)
}
}
}
override fun onLessonEnd(project: Project, lessonPassed: Boolean) {
restorePopupPosition(project, DiffWindowBase.DEFAULT_DIALOG_GROUP_KEY, backupDiffLocation)
backupDiffLocation = null
restorePopupPosition(project, ChangeListViewerDialog.DIMENSION_SERVICE_KEY, backupRevisionsLocation)
backupRevisionsLocation = null
}
private fun TaskContext.highlightGutterComponent(splitter: DiffSplitter?, partOfEditorText: String, highlightRight: Boolean) {
triggerByPartOfComponent l@{ ui: EditorGutterComponentEx ->
if (splitter != null && !isInsideSplitter(splitter, ui)) return@l null
val editor = findEditorForGutter(ui) ?: return@l null
if (editor.document.charsSequence.contains(partOfEditorText)) {
if (highlightRight) {
Rectangle(ui.x, ui.y, ui.width - 5, ui.height)
}
else Rectangle(ui.x + 5, ui.y, ui.width, ui.height)
}
else null
}
}
private fun TaskContext.highlightAnnotation(splitter: DiffSplitter?, partOfLineText: String, highlightRight: Boolean) {
triggerByPartOfComponent l@{ ui: EditorGutterComponentEx ->
if (splitter != null && !isInsideSplitter(splitter, ui)) return@l null
val editor = findEditorForGutter(ui) ?: return@l null
val offset = editor.document.charsSequence.indexOf(partOfLineText)
if (offset == -1) return@l null
val y = editor.offsetToXY(offset).y
if (highlightRight) {
Rectangle(ui.x + ui.annotationsAreaOffset, y, ui.annotationsAreaWidth, editor.lineHeight)
}
else Rectangle(ui.x + ui.width - ui.annotationsAreaOffset - ui.annotationsAreaWidth, y, ui.annotationsAreaWidth, editor.lineHeight)
}
}
private fun TaskContext.highlightAnnotateMenuItem() = highlightMenuItem { it.anAction is AnnotateToggleAction }
private fun TaskContext.highlightShowDiffMenuItem(): CompletableFuture<ActionMenuItem> {
val showDiffText = ActionsBundle.message("action.Diff.ShowDiff.text")
return highlightMenuItem { it.text?.contains(showDiffText) == true }
}
private fun TaskContext.highlightMenuItem(predicate: (ActionMenuItem) -> Boolean): CompletableFuture<ActionMenuItem> {
val future = CompletableFuture<ActionMenuItem>()
triggerByUiComponentAndHighlight(highlightInside = false) { ui: ActionMenuItem ->
predicate(ui).also {
if (it) future.complete(ui)
}
}
return future
}
private fun TaskContext.triggerOnAnnotationsShown(splitter: DiffSplitter?, partOfEditorText: String) {
triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: EditorComponentImpl ->
ui.editor.document.charsSequence.contains(partOfEditorText)
&& UIUtil.getParentOfType(DiffSplitter::class.java, ui) == splitter
&& isAnnotationsShown(ui.editor)
}
}
private fun TaskContext.restoreIfDiffClosed(restoreId: TaskContext.TaskId, diff: DiffSplitter?) {
restoreState(restoreId) { diff?.isShowing != true }
}
private fun TaskContext.restartTaskIfMenuClosed(menuItemFuture: CompletableFuture<ActionMenuItem>) {
restoreState(taskId, delayMillis = defaultRestoreDelay) {
val item = menuItemFuture.getNow(null)
item != null && !item.isShowing
}
}
private fun isInsideSplitter(splitter: DiffSplitter, component: Component): Boolean {
return UIUtil.getParentOfType(DiffSplitter::class.java, component) == splitter
}
private fun isAnnotationsShown(editor: Editor): Boolean {
val annotations = editor.gutter.textAnnotations
return annotations.filterIsInstance<ActiveAnnotationGutter>().isNotEmpty()
}
private fun isAnnotateShortcutSet(): Boolean {
return KeymapManager.getInstance().activeKeymap.getShortcuts("Annotate").isNotEmpty()
}
private fun findEditorForGutter(component: EditorGutterComponentEx): Editor? {
val scrollPane = UIUtil.getParentOfType(JBScrollPane::class.java, component) ?: return null
return UIUtil.findComponentOfType(scrollPane, EditorComponentImpl::class.java)?.editor
}
}
| apache-2.0 | 5868587d6874990b354d8fa00ce7cdcc | 43.775385 | 158 | 0.729865 | 4.944614 | false | false | false | false |
siosio/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/impl/SdkLookupTest.kt | 1 | 23675 | // 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.java.codeInsight.daemon.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.ProgressIndicatorBase
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.projectRoots.SimpleJavaSdkType
import com.intellij.openapi.projectRoots.impl.UnknownSdkFixAction
import com.intellij.openapi.roots.ui.configuration.*
import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownloadTask
import com.intellij.openapi.roots.ui.configuration.projectRoot.SdkDownloadTracker
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.ExtensionTestUtil
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.setSystemPropertyForTest
import com.intellij.util.WaitFor
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.ui.UIUtil
import org.junit.Assert
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicReference
import kotlin.concurrent.thread
class SdkLookupTest : LightPlatformTestCase() {
override fun setUp() {
super.setUp()
setSystemPropertyForTest("intellij.progress.task.ignoreHeadless", "true")
}
val log = Collections.synchronizedList(mutableListOf<String>())
val sdkType get() = SimpleJavaSdkType.getInstance()!!
interface SdkLookupBuilderEx : SdkLookupBuilder {
fun onDownloadingSdkDetectedEx(d: SdkLookupDownloadDecision): SdkLookupBuilderEx
fun onSdkFixResolved(d: SdkLookupDecision): SdkLookupBuilderEx
fun lookupBlocking()
}
private val lookup: SdkLookupBuilderEx
get() {
var ourFixDecision = SdkLookupDecision.CONTINUE
var ourSdkDownloadDecision = SdkLookupDownloadDecision.WAIT
var onSdkResolvedHook : (Sdk?) -> Unit = {}
val base = SdkLookup.newLookupBuilder()
.withProject(project)
.withProgressIndicator(ProgressIndicatorBase())
.withSdkType(sdkType)
.onSdkNameResolved { log += "sdk-name: ${it?.name}" }
.onSdkResolved { onSdkResolvedHook(it); log += "sdk: ${it?.name}" }
.onDownloadingSdkDetected { log += "sdk-downloading: ${it.name}"; ourSdkDownloadDecision }
.onSdkFixResolved { log += "fix: ${it.javaClass.simpleName}"; ourFixDecision }
return object : SdkLookupBuilder by base, SdkLookupBuilderEx {
override fun lookupBlocking() = base.lookupBlocking()
override fun onDownloadingSdkDetectedEx(d: SdkLookupDownloadDecision) = apply {
ourSdkDownloadDecision = d
}
override fun onSdkFixResolved(d: SdkLookupDecision) = apply {
ourFixDecision = d
}
override fun onDownloadingSdkDetected(handler: (Sdk) -> SdkLookupDownloadDecision): SdkLookupBuilder = error("Must not call in test")
override fun onSdkFixResolved(handler: (UnknownSdkFixAction) -> SdkLookupDecision): SdkLookupBuilder = error("Must not call in test")
override fun onSdkNameResolved(handler: (Sdk?) -> Unit): SdkLookupBuilder = error("Must not call in test")
override fun onSdkResolved(handler: (Sdk?) -> Unit): SdkLookupBuilder = apply {
onSdkResolvedHook = handler
}
}
}
fun SdkLookupBuilder.lookupBlocking(): Unit = service<SdkLookup>().lookupBlocking(this as SdkLookupParameters)
private fun assertLog(vararg messages: String) {
fun List<String>.format() = joinToString("") { "\n $it" }
Assert.assertEquals("actual log: " + log.format(), messages.toList().format(), log.format())
}
private fun assertLogContains(vararg messages: String) {
fun List<String>.format() = joinToString("") { "\n $it" }
Assert.assertEquals("actual log: " + log.format(), messages.toList().format(), log.format())
}
fun `test no sdk found`() {
runInThreadAndPumpMessages {
lookup.lookupBlocking()
}
assertLog(
"sdk-name: null",
"sdk: null",
)
}
fun `test find existing by name`() {
val sdk = newSdk("temp-1")
runInThreadAndPumpMessages {
lookup.withSdkName(sdk.name).lookupBlocking()
}
assertLog(
"sdk-name: temp-1",
"sdk: temp-1",
)
}
fun `test find sdk from alternatives`() {
val sdk1 = newUnregisteredSdk("temp-3")
val sdk2 = newUnregisteredSdk("temp-2")
runInThreadAndPumpMessages {
lookup
.testSuggestedSdksFirst(sequenceOf(null, sdk1, sdk2))
.lookupBlocking()
}
assertLog(
"sdk-name: temp-3",
"sdk: temp-3",
)
}
fun `test find sdk from alternatives and filter`() {
val sdk1 = newUnregisteredSdk("temp-3", "1.2.3")
val sdk2 = newUnregisteredSdk("temp-2", "2.3.4")
runInThreadAndPumpMessages {
lookup
.testSuggestedSdksFirst(sequenceOf(null, sdk1, sdk2))
.withVersionFilter { it == "2.3.4" }
.lookupBlocking()
}
assertLog(
"sdk-name: temp-2",
"sdk: temp-2",
)
}
fun `test find downloading sdk`() {
val taskLatch = CountDownLatch(1)
val downloadStarted = CountDownLatch(1)
Disposer.register(testRootDisposable, Disposable { taskLatch.countDown() })
val eternalTask = object: SdkDownloadTask {
val home = createTempDir("planned-home").toPath().systemIndependentPath
override fun getPlannedHomeDir() = home
override fun getSuggestedSdkName() = "suggested name"
override fun getPlannedVersion() = "planned version"
override fun doDownload(indicator: ProgressIndicator) {
downloadStarted.countDown()
taskLatch.await()
log += "download-completed"
}
}
val sdk = newSdk("temp-5")
threadEx {
SdkDownloadTracker.getInstance().downloadSdk(eternalTask, listOf(sdk), ProgressIndicatorBase())
}
runInThreadAndPumpMessages {
downloadStarted.await()
}
//download should be running now
threadEx {
object: WaitFor(1000) {
//this event should come from the lookup
override fun condition() = log.any { it.startsWith("sdk-name:") }
}
log += "thread-ex"
taskLatch.countDown()
}
runInThreadAndPumpMessages {
//right now it hangs doing async VFS refresh in downloader thread if running from a modal progress.
//ProgressManager.getInstance().run(object : Task.Modal(project, "temp", true) {
// override fun run(indicator: ProgressIndicator) {
lookup
.withSdkName("temp-5")
.lookupBlocking()
//}
//})
}
assertLog(
"sdk-name: temp-5",
"sdk-downloading: temp-5",
"thread-ex",
"download-completed",
"sdk: temp-5",
)
}
fun `test find downloading sdk stop`() {
val taskLatch = CountDownLatch(1)
val downloadStarted = CountDownLatch(1)
Disposer.register(testRootDisposable, Disposable { taskLatch.countDown() })
val eternalTask = object : SdkDownloadTask {
val home = createTempDir("planned-home").toPath().systemIndependentPath
override fun getPlannedHomeDir() = home
override fun getSuggestedSdkName() = "suggested name"
override fun getPlannedVersion() = "planned version"
override fun doDownload(indicator: ProgressIndicator) {
downloadStarted.countDown()
log += "download-started"
taskLatch.await()
log += "download-completed"
}
}
val sdk = newSdk("temp-5")
val download = threadEx {
SdkDownloadTracker.getInstance().downloadSdk(eternalTask, listOf(sdk), ProgressIndicatorBase())
}
runInThreadAndPumpMessages {
downloadStarted.await()
}
//download should be running now
val downloadThread = threadEx {
object : WaitFor(1000) {
//this event should come from the lookup
override fun condition() = log.any { it.startsWith("sdk-downloading:") }
}
log += "thread-ex"
taskLatch.countDown()
download.join()
}
runInThreadAndPumpMessages {
lookup
.onDownloadingSdkDetectedEx(SdkLookupDownloadDecision.STOP)
.onSdkResolved {
downloadThread.join()
}
.withSdkName("temp-5")
.lookupBlocking()
downloadThread.join()
}
assertLog(
"download-started",
"sdk-name: temp-5",
"sdk-downloading: temp-5",
"thread-ex",
"download-completed",
"sdk: null",
)
}
fun `test find downloading sdk async`() {
val taskLatch = CountDownLatch(1)
val downloadStarted = CountDownLatch(1)
Disposer.register(testRootDisposable, Disposable { taskLatch.countDown() })
val eternalTask = object: SdkDownloadTask {
val home = createTempDir("planned-home").toPath().systemIndependentPath
override fun getPlannedHomeDir() = home
override fun getSuggestedSdkName() = "suggested name"
override fun getPlannedVersion() = "planned version"
override fun doDownload(indicator: ProgressIndicator) {
downloadStarted.countDown()
taskLatch.await()
log += "download-completed"
}
}
val sdk = newSdk("temp-5")
threadEx {
SdkDownloadTracker.getInstance().downloadSdk(eternalTask, listOf(sdk), ProgressIndicatorBase())
}
runInThreadAndPumpMessages {
downloadStarted.await()
}
//download should be running now
threadEx {
object: WaitFor(1000) {
//this event should come from the lookup
override fun condition() = log.any { it.startsWith("sdk-name:") }
}
log += "thread-ex"
taskLatch.countDown()
}
val lookupLatch = CountDownLatch(1)
lookup
.withSdkName("temp-5")
.onSdkResolved { lookupLatch.countDown() }
.executeLookup()
runInThreadAndPumpMessages {
lookupLatch.await()
}
assertLog(
"sdk-name: temp-5",
"sdk-downloading: temp-5",
"thread-ex",
"download-completed",
"sdk: temp-5",
)
}
fun `test local fix`() {
val auto = object: UnknownSdkResolver {
override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType
override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup {
override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null
override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? {
if (sdk.sdkName != "xqwr") return null
return object : UnknownSdkLocalSdkFix {
val home = createTempDir("our home for ${sdk.sdkName}")
override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}"}
override fun getExistingSdkHome() = home.toString()
override fun getVersionString() = "1.2.3"
override fun getSuggestedSdkName() = sdk.sdkName!!
}
}
}
}
ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable)
runInThreadAndPumpMessages {
lookup
.withSdkName("xqwr")
.lookupBlocking()
}
assertLog(
"fix: UnknownMissingSdkFixLocal",
"configure: xqwr",
"sdk-name: xqwr",
"sdk: xqwr",
)
removeSdk("xqwr")
}
private fun removeSdk(name: String) {
val sdk = ProjectJdkTable.getInstance().findJdk(name) ?: error("SDK '$name' doesn't exist")
SdkTestCase.removeSdk(sdk)
}
fun `test local fix with SDK prototype`() {
val prototypeSdk = newSdk("prototype")
val auto = object : UnknownSdkResolver {
override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType
override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup {
override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null
override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkLocalSdkFix {
val home = createTempDir("our home for ${sdk.sdkName}")
override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}" }
override fun getExistingSdkHome() = home.toString()
override fun getVersionString() = "1.2.3"
override fun getSuggestedSdkName() = sdk.sdkName!!
override fun getRegisteredSdkPrototype() = prototypeSdk
}
}
}
ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable)
runInThreadAndPumpMessages {
lookup
.lookupBlocking()
}
assertLog(
"sdk-name: prototype",
"sdk: prototype",
)
}
fun `test local fix with unregistered SDK prototype`() {
val prototypeSdk = newUnregisteredSdk("prototype")
val auto = object : UnknownSdkResolver {
override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType
override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup {
override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null
override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkLocalSdkFix {
val home = createTempDir("our home for ${sdk.sdkName}")
override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}" }
override fun getExistingSdkHome() = home.toString()
override fun getVersionString() = "1.2.3"
override fun getSuggestedSdkName() = "suggested-name"
override fun getRegisteredSdkPrototype() = prototypeSdk
}
}
}
ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable)
runInThreadAndPumpMessages {
lookup
.lookupBlocking()
}
assertLog(
"fix: UnknownMissingSdkFixLocal",
"configure: suggested-name",
"sdk-name: suggested-name",
"sdk: suggested-name",
)
removeSdk("suggested-name")
}
fun `test local fix with stop`() {
val prototypeSdk = newUnregisteredSdk("prototype")
val auto = object : UnknownSdkResolver {
override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType
override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup {
override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null
override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkLocalSdkFix {
val home = createTempDir("our home for ${sdk.sdkName}")
override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}" }
override fun getExistingSdkHome() = home.toString()
override fun getVersionString() = "1.2.3"
override fun getSuggestedSdkName() = "suggested-name"
override fun getRegisteredSdkPrototype() = prototypeSdk
}
}
}
ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable)
runInThreadAndPumpMessages {
lookup
.onSdkFixResolved(SdkLookupDecision.STOP)
.lookupBlocking()
}
assertLog(
"fix: UnknownMissingSdkFixLocal",
"sdk-name: null",
"sdk: null",
)
}
fun `test local fix should not clash with SDK name`() {
val prototypeSdk = newSdk("prototype")
val auto = object : UnknownSdkResolver {
override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType
override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup {
override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? = null
override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkLocalSdkFix {
val home = createTempDir("our home for ${sdk.sdkName}")
override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}" }
override fun getExistingSdkHome() = home.toString()
override fun getVersionString() = "1.2.3"
override fun getSuggestedSdkName() = prototypeSdk.name
}
}
}
ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable)
runInThreadAndPumpMessages {
lookup
.lookupBlocking()
}
assertLog(
"fix: UnknownMissingSdkFixLocal",
"configure: prototype (2)",
"sdk-name: prototype (2)",
"sdk: prototype (2)",
)
}
fun `test download fix`() {
val auto = object: UnknownSdkResolver {
override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType
override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup {
override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? = null
override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? {
if (sdk.sdkName != "xqwr") return null
return object : UnknownSdkDownloadableSdkFix {
override fun getDownloadDescription(): String = "download description"
override fun createTask(indicator: ProgressIndicator) = object: SdkDownloadTask {
override fun getSuggestedSdkName() = sdk.sdkName!!
override fun getPlannedHomeDir() = home.toString()
override fun getPlannedVersion() = versionString
override fun doDownload(indicator: ProgressIndicator) { log += "download: ${sdk.sdkName}" }
}
val home = createTempDir("our home for ${sdk.sdkName}")
override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}"}
override fun getVersionString() = "1.2.3"
}
}
}
}
ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable)
runInThreadAndPumpMessages {
lookup
.withSdkName("xqwr")
.lookupBlocking()
}
assertLog(
"fix: UnknownMissingSdkFixDownload",
"sdk-name: xqwr",
"download: xqwr",
"configure: xqwr",
"sdk: xqwr",
)
removeSdk("xqwr")
}
fun `test download fix stop`() {
val auto = object: UnknownSdkResolver {
override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType
override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup {
override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? = null
override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkDownloadableSdkFix? {
if (sdk.sdkName != "xqwr") return null
return object : UnknownSdkDownloadableSdkFix {
override fun getDownloadDescription(): String = "download description"
override fun createTask(indicator: ProgressIndicator) = object: SdkDownloadTask {
override fun getSuggestedSdkName() = sdk.sdkName!!
override fun getPlannedHomeDir() = home.toString()
override fun getPlannedVersion() = versionString
override fun doDownload(indicator: ProgressIndicator) { log += "download: ${sdk.sdkName}" }
}
val home = createTempDir("our home for ${sdk.sdkName}")
override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}"}
override fun getVersionString() = "1.2.3"
}
}
}
}
ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable)
runInThreadAndPumpMessages {
lookup
.onSdkFixResolved(SdkLookupDecision.STOP)
.withSdkName("xqwr")
.lookupBlocking()
}
assertLog(
"fix: UnknownMissingSdkFixDownload",
"sdk-name: null",
"sdk: null",
)
}
fun `test download fix should not clash SDK name`() {
val prototypeSdk = newSdk("prototype")
val auto = object: UnknownSdkResolver {
override fun supportsResolution(sdkTypeId: SdkTypeId) = sdkTypeId == sdkType
override fun createResolver(project: Project?, indicator: ProgressIndicator) = object : UnknownSdkResolver.UnknownSdkLookup {
override fun proposeLocalFix(sdk: UnknownSdk, indicator: ProgressIndicator): UnknownSdkLocalSdkFix? = null
override fun proposeDownload(sdk: UnknownSdk, indicator: ProgressIndicator) = object : UnknownSdkDownloadableSdkFix {
override fun getDownloadDescription(): String = "download description"
override fun createTask(indicator: ProgressIndicator) = object: SdkDownloadTask {
override fun getSuggestedSdkName() = prototypeSdk.name
override fun getPlannedHomeDir() = home.toString()
override fun getPlannedVersion() = versionString
override fun doDownload(indicator: ProgressIndicator) { log += "download: ${sdk.sdkName}" }
}
val home = createTempDir("our home for ${sdk.sdkName}")
override fun configureSdk(sdk: Sdk) { log += "configure: ${sdk.name}"}
override fun getVersionString() = "1.2.3"
}
}
}
ExtensionTestUtil.maskExtensions(UnknownSdkResolver.EP_NAME, listOf(auto), testRootDisposable)
runInThreadAndPumpMessages {
lookup
.lookupBlocking()
}
assertLog(
"fix: UnknownMissingSdkFixDownload",
"sdk-name: prototype (2)",
"download: null",
"configure: prototype (2)",
"sdk: prototype (2)",
)
removeSdk("prototype (2)")
}
private fun newSdk(sdkName: String, version: String = "1.2.3"): Sdk {
return WriteAction.compute<Sdk, Throwable> {
val sdk = newUnregisteredSdk(sdkName, version)
ProjectJdkTable.getInstance().addJdk(sdk, testRootDisposable)
sdk
}
}
private fun newUnregisteredSdk(sdkName: String,
version: String = "1.2.3"): Sdk {
val sdk = ProjectJdkTable.getInstance().createSdk(sdkName, sdkType)
sdk.sdkModificator.also { it.versionString = version }.commitChanges()
if (sdk is Disposable) {
Disposer.register(testRootDisposable, sdk)
}
return sdk
}
private fun <R> runInThreadAndPumpMessages(action: () -> R) : R {
val result = AtomicReference<Result<R>>(null)
val th = threadEx { result.set(runCatching { action() }) }
while (th.isAlive) {
ProgressManager.checkCanceled()
UIUtil.dispatchAllInvocationEvents()
th.join(100)
}
return result.get()?.getOrThrow() ?: error("No result was set")
}
private fun threadEx(task: () -> Unit): Thread {
val thread = thread(block = task)
Disposer.register(testRootDisposable, Disposable { thread.interrupt(); thread.join(500) })
return thread
}
}
| apache-2.0 | 479a27ee2b7fa437fd4d170499418754 | 36.51981 | 142 | 0.672439 | 5.043673 | false | true | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateStrategy.kt | 1 | 4777 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.openapi.updateSettings.UpdateStrategyCustomization
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.containers.MultiMap
import com.intellij.util.graph.InboundSemiGraph
import com.intellij.util.graph.impl.ShortestPathFinder
import org.jetbrains.annotations.ApiStatus
class UpdateStrategy @JvmOverloads constructor(
private val currentBuild: BuildNumber,
private val product: Product? = null,
private val settings: UpdateSettings = UpdateSettings.getInstance(),
private val customization: UpdateStrategyCustomization = UpdateStrategyCustomization.getInstance(),
) {
@Deprecated("Please use `UpdateStrategy(BuildNumber, Product, UpdateSettings)` instead")
@ApiStatus.ScheduledForRemoval(inVersion = "2022.2")
@Suppress("DEPRECATION")
constructor(
currentBuild: BuildNumber,
updates: UpdatesInfo,
settings: UpdateSettings = UpdateSettings.getInstance(),
) : this(
currentBuild,
updates.product,
settings,
)
fun checkForUpdates(): PlatformUpdates {
if (product == null || product.channels.isEmpty()) {
return PlatformUpdates.Empty
}
val selectedChannel = settings.selectedChannelStatus
val ignoredBuilds = settings.ignoredBuildNumbers.toSet()
return product.channels
.asSequence()
.filter { ch -> ch.status >= selectedChannel } // filters out inapplicable channels
.sortedBy { ch -> ch.status } // reorders channels (EAPs first)
.flatMap { ch -> ch.builds.asSequence().map { build -> build to ch } } // maps into a sequence of <build, channel> pairs
.filter { p -> isApplicable(p.first, ignoredBuilds) } // filters out inapplicable builds
.maxWithOrNull(Comparator { p1, p2 -> compareBuilds(p1.first.number, p2.first.number) }) // a build with the max number, preferring the same baseline
?.let { (newBuild, channel) ->
PlatformUpdates.Loaded(
newBuild,
channel,
patches(newBuild, product, currentBuild),
)
} ?: PlatformUpdates.Empty
}
private fun isApplicable(candidate: BuildInfo, ignoredBuilds: Set<String>): Boolean =
customization.isNewerVersion(candidate.number, currentBuild) &&
candidate.number.asStringWithoutProductCode() !in ignoredBuilds &&
candidate.target?.inRange(currentBuild) ?: true
private fun compareBuilds(n1: BuildNumber, n2: BuildNumber): Int {
val preferSameMajorVersion = customization.haveSameMajorVersion(currentBuild, n1).compareTo(customization.haveSameMajorVersion(currentBuild, n2))
return if (preferSameMajorVersion != 0) preferSameMajorVersion else n1.compareTo(n2)
}
private fun patches(newBuild: BuildInfo, product: Product, from: BuildNumber): UpdateChain? {
val single = newBuild.patches.find { it.isAvailable && it.fromBuild.compareTo(from) == 0 }
if (single != null) {
return UpdateChain(listOf(from, newBuild.number), single.size)
}
val upgrades = MultiMap<BuildNumber, BuildNumber>()
val sizes = mutableMapOf<Pair<BuildNumber, BuildNumber>, Int>()
val number = Regex("\\d+")
product.channels.forEach { channel ->
channel.builds.forEach { build ->
val toBuild = build.number.withoutProductCode()
build.patches.forEach { patch ->
if (patch.isAvailable) {
val fromBuild = patch.fromBuild.withoutProductCode()
upgrades.putValue(toBuild, fromBuild)
if (patch.size != null) {
val maxSize = number.findAll(patch.size).map { it.value.toIntOrNull() }.filterNotNull().maxOrNull()
if (maxSize != null) sizes += (fromBuild to toBuild) to maxSize
}
}
}
}
}
val graph = object : InboundSemiGraph<BuildNumber> {
override fun getNodes() = upgrades.keySet() + upgrades.values()
override fun getIn(n: BuildNumber) = upgrades[n].iterator()
}
val path = ShortestPathFinder(graph).findPath(from.withoutProductCode(), newBuild.number.withoutProductCode())
if (path == null || path.size <= 2) return null
var total = 0
for (i in 1 until path.size) {
val size = sizes[path[i - 1] to path[i]]
if (size == null) {
total = -1
break
}
total += size
}
return UpdateChain(path, if (total > 0) total.toString() else null)
}
}
| apache-2.0 | 64451d613da81ea869f76b29661b4c2b | 42.825688 | 163 | 0.657316 | 4.844828 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/postProcessing/postProcessings.kt | 6 | 2182 | // 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.nj2k.postProcessing
import com.intellij.openapi.editor.RangeMarker
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.j2k.JKMultipleFilesPostProcessingTarget
import org.jetbrains.kotlin.j2k.JKPieceOfCodePostProcessingTarget
import org.jetbrains.kotlin.j2k.JKPostProcessingTarget
import org.jetbrains.kotlin.j2k.elements
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.psi.KtFile
interface GeneralPostProcessing {
val options: PostProcessingOptions
get() = PostProcessingOptions.DEFAULT
fun runProcessing(target: JKPostProcessingTarget, converterContext: NewJ2kConverterContext)
}
data class PostProcessingOptions(
val disablePostprocessingFormatting: Boolean = true
) {
companion object {
val DEFAULT = PostProcessingOptions()
}
}
abstract class FileBasedPostProcessing : GeneralPostProcessing {
final override fun runProcessing(target: JKPostProcessingTarget, converterContext: NewJ2kConverterContext) = when (target) {
is JKPieceOfCodePostProcessingTarget ->
runProcessing(target.file, listOf(target.file), target.rangeMarker, converterContext)
is JKMultipleFilesPostProcessingTarget ->
target.files.forEach { file ->
runProcessing(file, target.files, rangeMarker = null, converterContext = converterContext)
}
}
abstract fun runProcessing(file: KtFile, allFiles: List<KtFile>, rangeMarker: RangeMarker?, converterContext: NewJ2kConverterContext)
}
abstract class ElementsBasedPostProcessing : GeneralPostProcessing {
final override fun runProcessing(target: JKPostProcessingTarget, converterContext: NewJ2kConverterContext) {
runProcessing(target.elements(), converterContext)
}
abstract fun runProcessing(elements: List<PsiElement>, converterContext: NewJ2kConverterContext)
}
data class NamedPostProcessingGroup(
val description: String,
val processings: List<GeneralPostProcessing>
)
| apache-2.0 | fc1adcab51a73e6e5a9a1e6039c5a623 | 38.672727 | 158 | 0.784143 | 5.098131 | false | false | false | false |
Kiskae/DiscordKt | implementation/src/main/kotlin/net/serverpeon/discord/internal/data/model/ChannelNode.kt | 1 | 15747 | package net.serverpeon.discord.internal.data.model
import net.serverpeon.discord.interaction.Editable
import net.serverpeon.discord.interaction.PermissionException
import net.serverpeon.discord.internal.data.EventInput
import net.serverpeon.discord.internal.jsonmodels.ChannelModel
import net.serverpeon.discord.internal.jsonmodels.MessageModel
import net.serverpeon.discord.internal.rest.WrappedId
import net.serverpeon.discord.internal.rest.retro.Channels.*
import net.serverpeon.discord.internal.rx
import net.serverpeon.discord.internal.rxObservable
import net.serverpeon.discord.internal.toFuture
import net.serverpeon.discord.internal.ws.data.inbound.Channels
import net.serverpeon.discord.internal.ws.data.inbound.Misc
import net.serverpeon.discord.message.Message
import net.serverpeon.discord.model.*
import rx.Completable
import rx.Observable
import java.time.Duration
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.regex.Pattern
abstract class ChannelNode<T : ChannelNode<T>> private constructor(val root: DiscordNode,
override val id: DiscordId<Channel>
) : Channel, Channel.Text, EventInput<T> {
override fun delete(): CompletableFuture<Void> {
return root.api.Channels.deleteChannel(WrappedId(id)).toFuture()
}
override fun messageHistory(limit: Int, before: DiscordId<PostedMessage>?): Observable<PostedMessage> {
checkPermission(PermissionSet.Permission.READ_MESSAGE_HISTORY)
return Observable.concat<List<MessageModel>>(Observable.create { sub ->
//TODO: some sort of rate limiting mechanism
var currentLimit = limit
var lastMessage: DiscordId<PostedMessage>? = before
sub.setProducer {
if (currentLimit > 0) {
//Produce the next call.
val requestLimit = Math.min(currentLimit, 100)
currentLimit -= requestLimit
val obs = root.api.Channels.getMessages(WrappedId(id),
limit = requestLimit,
before = lastMessage?.let { WrappedId(it) }
).rxObservable().publish().apply {
// Set lastMessage to last message of list
sub.add(subscribe { lastMessage = it.last().id })
}.refCount()
sub.onNext(obs)
} else {
sub.onCompleted()
}
}
}).flatMapIterable {
it
}.map { Builder.message(it, root) }
}
override fun sendMessage(message: Message, textToSpeech: Boolean?): CompletableFuture<PostedMessage> {
checkPermission(PermissionSet.Permission.SEND_MESSAGES)
if (textToSpeech == true) {
checkPermission(PermissionSet.Permission.SEND_TTS_MESSAGES)
}
val mentions = message.mentions.map { it.id }.toList().toBlocking().first()
return root.api.Channels.sendMessage(WrappedId(id), SendMessageRequest(
message.encodedContent,
mentions = if (mentions.isNotEmpty()) mentions else null,
tts = textToSpeech
)).toFuture().thenApply { Builder.message(it, root) }
}
abstract fun checkPermission(perm: PermissionSet.Permission)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as ChannelNode<*>
return id == other.id
}
override fun hashCode(): Int {
return id.hashCode()
}
/**
* Public channel objects start here
*/
class Public internal constructor(root: DiscordNode,
id: DiscordId<Channel>,
override val guild: GuildNode,
override var topic: String,
override val type: Channel.Type,
override var name: String,
internal var overrides: LinkedHashMap<DiscordId<*>, OverrideData>,
internal var position: Int
) : ChannelNode<Public>(root, id), Channel.Public {
private val changeId = AtomicInteger(0)
override fun handler(): EventInput.Handler<Public> {
return PublicChannelUpdater
}
override fun checkPermission(perm: PermissionSet.Permission) {
guild.selfAsMember.checkPermission(this, perm)
}
override val voiceStates: Observable<VoiceState> = Observable.empty() //TODO: implement voice state
override val memberOverrides: Observable<Channel.ResolvedPermission<Guild.Member>>
get() = filterAndMapOverrides(shouldBeMember = true) { id ->
val user = guild.memberMap[id]!!
val perms = permissionsFor(user)
Channel.ResolvedPermission(user, perms)
}
override val roleOverrides: Observable<Channel.ResolvedPermission<Role>>
get() = filterAndMapOverrides(shouldBeMember = false) { id ->
val role = guild.roleMap[id]!!
val perms = permissionsFor(role)
Channel.ResolvedPermission(role, perms)
}
override fun permissionsFor(role: Role): PermissionSet {
val overrides = overrides[role.id]
return overrides?.let {
role.permissions.without(it.deny).with(it.allow)
} ?: role.permissions
}
override fun permissionsFor(member: Guild.Member): PermissionSet {
return resolveMemberPerms(member, true)
}
override fun createInvite(expiredAfter: Duration,
maxUses: Int,
temporaryMembership: Boolean,
humanReadableId: Boolean
): CompletableFuture<Invite.Details> {
checkPermission(PermissionSet.Permission.CREATE_INSTANT_INVITE)
return root.api.Channels.createInvite(WrappedId(id), InviteSpec(
max_age = expiredAfter.seconds.toInt(),
max_uses = maxUses,
temporary = temporaryMembership,
xkcdpass = humanReadableId
)).toFuture().thenApply {
Builder.invite(it, root)
}
}
override fun getActiveInvites(): Observable<Invite.Details> {
checkPermission(PermissionSet.Permission.MANAGE_CHANNEL)
return root.api.Channels.getChannelInvites(WrappedId(id)).rxObservable().flatMapIterable {
it
}.map {
Builder.invite(it, root)
}
}
override val isPrivate: Boolean
get() = false
private fun resolveMemberPerms(member: Guild.Member, applyOwnOverride: Boolean): PermissionSet {
return if (member.id == guild.ownerId) {
PermissionSet.ALL
} else {
member.roles.map {
permissionsFor(it)
}.reduce(PermissionSet.ZERO, { p1, p2 ->
p1.with(p2) // Fold all roles together
}).let {
if (applyOwnOverride) {
it.map { rolePerms ->
val overrides = overrides[member.id]
overrides?.let {
rolePerms.without(it.deny).with(it.allow)
} ?: rolePerms
}
} else {
it
}
}.toBlocking().first() //Everything SHOULD be available, so this won't cause problems (famous last words)
}
}
override fun setOverride(allow: PermissionSet, deny: PermissionSet, member: Guild.Member): CompletableFuture<PermissionSet> {
return if (allow.empty() && deny.empty()) {
val current = overrides[member.id]
if (current != null) {
//Go through deletion
root.api.Channels.deletePermissionsUser(WrappedId(id), WrappedId(member.id)).toFuture()
.thenApply {
resolveMemberPerms(member, false)
}
} else {
//No override, return current
CompletableFuture.completedFuture(permissionsFor(member))
}
} else {
root.api.Channels.changePermissionsUser(WrappedId(id), WrappedId(member.id), EditPermissionRequest(
allow = allow,
deny = deny,
id = member.id,
type = "member"
)).toFuture().thenApply {
resolveMemberPerms(member, false).without(deny).with(allow)
}
}
}
override fun setOverride(allow: PermissionSet, deny: PermissionSet, role: Role): CompletableFuture<PermissionSet> {
return if (allow.empty() && deny.empty()) {
val current = overrides[role.id]
if (current != null) {
root.api.Channels.deletePermissionsRole(WrappedId(id), WrappedId(role.id)).toFuture()
.thenApply { role.permissions }
} else {
CompletableFuture.completedFuture(role.permissions)
}
} else {
root.api.Channels.changePermissionsRole(WrappedId(id), WrappedId(role.id), EditPermissionRequest(
allow = allow,
deny = deny,
id = role.id,
type = "role"
)).toFuture().thenApply { role.permissions.without(deny).with(allow) }
}
}
override fun indicateTyping(): Completable {
return root.api.Channels.postActivity(WrappedId(id)).rx()
}
override fun edit(): Channel.Public.Edit {
guild.selfAsMember.checkPermission(this, PermissionSet.Permission.MANAGE_CHANNEL)
return Transaction(topic, name)
}
private fun <T : DiscordId.Identifiable<T>, G : T> filterAndMapOverrides(
shouldBeMember: Boolean,
objectLookup: (DiscordId<T>) -> Channel.ResolvedPermission<G>
): Observable<Channel.ResolvedPermission<G>> {
return Observable.defer {
Observable.from(overrides.entries)
}.filter {
it.value.isMember == shouldBeMember
}.map {
@Suppress("UNCHECKED_CAST")
objectLookup(it.key as DiscordId<T>)
}
}
override fun toString(): String {
return "PublicChannel(guild='${guild.name}', name='$name')"
}
inner class Transaction(override var topic: String, override var name: String) : Channel.Public.Edit {
private var completed = AtomicBoolean(false)
private val changeIdAtInit = changeId.get()
override fun commit(): CompletableFuture<Channel.Public> {
if (changeId.compareAndSet(changeIdAtInit, changeIdAtInit + 1)) {
throw Editable.ResourceChangedException(this@Public)
} else if (completed.getAndSet(true)) {
throw IllegalStateException("Don't call complete() twice")
} else {
return root.api.Channels.editChannel(WrappedId(id), EditChannelRequest(
name = name,
position = position,
topic = topic
)).toFuture().thenApply {
Builder.channel(it, guild)
}
}
}
}
}
data class OverrideData(val allow: PermissionSet, val deny: PermissionSet, val isMember: Boolean)
private object PublicChannelUpdater : EventInput.Handler<Public> {
override fun voiceStateUpdate(target: Public, e: Misc.VoiceStateUpdate) {
// Pass through to member
target.guild.memberMap[e.update.user_id]?.handle(e)
}
override fun typingStart(target: Public, e: Misc.TypingStart) {
// Ignored, not something we need to represent
}
override fun channelUpdate(target: Public, e: Channels.Update) {
e.channel.let {
target.name = it.name
target.topic = it.topic ?: ""
target.overrides = translateOverrides(it.permission_overwrites)
target.position = it.position
}
}
}
/**
* Private channel objects start here
*/
class Private internal constructor(root: DiscordNode,
id: DiscordId<Channel>,
override val recipient: UserNode
) : ChannelNode<Private>(root, id), Channel.Private {
override fun handler(): EventInput.Handler<Private> {
return PrivateChannelUpdater
}
override fun checkPermission(perm: PermissionSet.Permission) {
if (perm == PermissionSet.Permission.MANAGE_MESSAGES) {
throw PermissionException(PermissionSet.Permission.MANAGE_MESSAGES)
}
}
override fun indicateTyping(): Completable {
return root.api.Channels.postActivity(WrappedId(id)).rx()
}
override fun sendMessage(message: Message, textToSpeech: Boolean?): CompletableFuture<PostedMessage> {
val mentions = message.mentions.toList().toBlocking().first()
return root.api.Channels.sendMessage(WrappedId(id), SendMessageRequest(
content = message.encodedContent,
mentions = if (mentions.isEmpty()) null else mentions.map { it.id },
tts = textToSpeech
)).toFuture().thenApply {
error("Message not yet translatable")
}
}
override fun toString(): String {
return "PrivateChannel(recipient=$recipient)"
}
override val type: Channel.Type
get() = Channel.Type.PRIVATE
override val isPrivate: Boolean
get() = true
}
private object PrivateChannelUpdater : EventInput.Handler<Private> {
override fun typingStart(target: Private, e: Misc.TypingStart) {
// Ignored
}
}
companion object {
private val CHANNEL_NAME_REQUIREMENTS = Pattern.compile("^[A-Za-z0-9\\-]{2,100}$")
internal fun translateOverrides(
permission_overwrites: List<ChannelModel.PermissionOverwrites>
): LinkedHashMap<DiscordId<*>, OverrideData> {
val pairs = permission_overwrites.map {
DiscordId<Role>(it.id) to OverrideData(it.allow, it.deny, it.type == "member")
}.toTypedArray()
return linkedMapOf(*pairs)
}
fun sanitizeChannelName(name: String): String {
val nameWithDashes = name.replace(' ', '-')
check(CHANNEL_NAME_REQUIREMENTS.asPredicate().test(nameWithDashes)) {
"Channel name contains invalid characters: $name"
}
return nameWithDashes.toLowerCase()
}
}
} | mit | e3b9824d92c0d511183049f29bc08b51 | 40.994667 | 133 | 0.565314 | 5.361593 | false | false | false | false |
hotpodata/redchain | mobile/src/main/java/com/hotpodata/redchain/adapter/SideBarAdapter.kt | 1 | 8533 | package com.hotpodata.redchain.adapter
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hotpodata.redchain.R
import com.hotpodata.redchain.adapter.viewholder.*
import com.hotpodata.redchain.data.Chain
/**
* Created by jdrotos on 11/7/15.
*/
class SideBarAdapter(ctx: Context, rows: List<Any>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val ROW_TYPE_HEADER = 0
private val ROW_TYPE_ONE_LINE = 1
private val ROW_TYPE_TWO_LINE = 2
private val ROW_TYPE_DIV = 3
private val ROW_TYPE_DIV_INSET = 4
private val ROW_TYPE_SIDE_BAR_HEADING = 5
private val ROW_TYPE_CHAIN = 6
private val ROW_TYPE_NEW_CHAIN = 7
private var mRows: List<Any>
private var mColor: Int
private var mContext: Context
init {
mRows = rows
mColor = ctx.resources.getColor(R.color.primary)
mContext = ctx
notifyDataSetChanged()
}
public fun setRows(rows: List<Any>) {
mRows = rows
notifyDataSetChanged()
}
public fun setAccentColor(color: Int) {
mColor = color;
if (itemCount > 0 && getItemViewType(0) == ROW_TYPE_HEADER) {
notifyItemChanged(0)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder? {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
ROW_TYPE_HEADER -> {
val v = inflater.inflate(R.layout.row_sidebar_section_header, parent, false)
SideBarSectionHeaderViewHolder(v)
}
ROW_TYPE_ONE_LINE, ROW_TYPE_NEW_CHAIN -> {
val v = inflater.inflate(R.layout.row_text_one_line, parent, false)
RowTextOneLineViewHolder(v)
}
ROW_TYPE_TWO_LINE -> {
val v = inflater.inflate(R.layout.row_text_two_line, parent, false)
RowTextTwoLineViewHolder(v)
}
ROW_TYPE_DIV, ROW_TYPE_DIV_INSET -> {
val v = inflater.inflate(R.layout.row_div, parent, false)
RowDivViewHolder(v)
}
ROW_TYPE_SIDE_BAR_HEADING -> {
val v = inflater.inflate(R.layout.row_sidebar_header, parent, false)
SideBarHeaderViewHolder(v)
}
ROW_TYPE_CHAIN -> {
val v = inflater.inflate(R.layout.row_chain_two_line, parent, false)
RowChainViewHolder(v)
}
else -> null
}
}
@Suppress("DEPRECATION")
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val type = getItemViewType(position)
val objData = mRows[position]
when (type) {
ROW_TYPE_SIDE_BAR_HEADING -> {
val vh = holder as SideBarHeaderViewHolder
val data = objData as SideBarHeading
vh.mTitleTv.text = data.title
vh.mSubTitleTv.text = data.subtitle
vh.mContainer.setBackgroundColor(mColor)
}
ROW_TYPE_HEADER -> {
val vh = holder as SideBarSectionHeaderViewHolder
val data = objData as String
vh.mTitleTv.text = data
}
ROW_TYPE_ONE_LINE, ROW_TYPE_NEW_CHAIN -> {
val vh = holder as RowTextOneLineViewHolder
val data = objData as SettingsRow
vh.mTextOne.text = data.title
vh.itemView.setOnClickListener(data.onClickListener)
if (data.iconResId != -1) {
vh.mIcon.setImageResource(data.iconResId)
vh.mIcon.visibility = View.VISIBLE
} else {
vh.mIcon.setImageDrawable(null)
vh.mIcon.visibility = View.GONE
}
}
ROW_TYPE_TWO_LINE -> {
val vh = holder as RowTextTwoLineViewHolder
val data = objData as SettingsRow
vh.mTextOne.text = data.title
vh.mTextTwo.text = data.subTitle
vh.itemView.setOnClickListener(data.onClickListener)
if (data.iconResId != -1) {
vh.mIcon.setImageResource(data.iconResId)
vh.mIcon.visibility = View.VISIBLE
} else {
vh.mIcon.setImageDrawable(null)
vh.mIcon.visibility = View.GONE
}
}
ROW_TYPE_DIV_INSET, ROW_TYPE_DIV -> {
val vh = holder as RowDivViewHolder
val data = objData as Div
if (data.isInset) {
vh.mSpacer.visibility = View.VISIBLE
} else {
vh.mSpacer.visibility = View.GONE
}
}
ROW_TYPE_CHAIN -> {
val vh = holder as RowChainViewHolder
val data = objData as RowChain
vh.itemView.setOnClickListener(data.onClickListener)
vh.mTextOne.text = data.chain.title
vh.mIcon.setCircleBgColor(data.chain.color)
if (data.isSelected) {
vh.mTextOne.setTypeface(null, Typeface.BOLD)
vh.mTextOne.setTextColor(mColor)
vh.mTextTwo.setTypeface(null, Typeface.BOLD)
vh.mTextTwo.setTextColor(mColor)
} else {
vh.mTextOne.setTypeface(null, Typeface.NORMAL)
vh.mTextOne.setTextColor(mContext.resources.getColor(R.color.settings_row_title_color))
vh.mTextTwo.setTypeface(null, Typeface.NORMAL)
vh.mTextTwo.setTextColor(mContext.resources.getColor(R.color.settings_row_subtitle_color))
}
if (data.chain.chainContainsToday()) {
vh.mIcon.setImageResource(R.drawable.ic_action_checkmark)
vh.mIcon.setColorFilter(Color.WHITE)
} else {
vh.mIcon.setImageDrawable(null)
}
vh.mTextTwo.text = mContext.resources.getString(R.string.day_num, if (data.chain.chainContainsToday()) data.chain.chainLength else data.chain.chainLength + 1)
vh.mTextTwo.visibility = View.VISIBLE
}
}
}
override fun getItemCount(): Int {
return mRows.size
}
override fun getItemViewType(position: Int): Int {
val data = mRows[position]
return when (data) {
is String -> ROW_TYPE_HEADER
is RowCreateChain -> ROW_TYPE_NEW_CHAIN
is SettingsRow -> if (TextUtils.isEmpty(data.subTitle)) {
ROW_TYPE_ONE_LINE
} else {
ROW_TYPE_TWO_LINE
}
is Div -> if (data.isInset) {
ROW_TYPE_DIV_INSET
} else {
ROW_TYPE_DIV
}
is SideBarHeading -> ROW_TYPE_SIDE_BAR_HEADING
is RowChain -> ROW_TYPE_CHAIN
else -> super.getItemViewType(position)
}
}
open class SettingsRow {
var title: String? = null
private set
var subTitle: String? = null
private set
var onClickListener: View.OnClickListener? = null
private set
var iconResId = -1
private set
constructor(title: String, subTitle: String, onClickListener: View.OnClickListener) {
this.title = title
this.subTitle = subTitle
this.onClickListener = onClickListener
}
constructor(title: String, subTitle: String, onClickListener: View.OnClickListener, iconResId: Int) {
this.title = title
this.subTitle = subTitle
this.onClickListener = onClickListener
this.iconResId = iconResId
}
}
class Div(val isInset: Boolean)
class SideBarHeading(val title: String, val subtitle: String?)
class RowChain(val chain: Chain, val isSelected: Boolean, var onClickListener: View.OnClickListener?)
class RowCreateChain(title: String, subTitle: String, onClickListener: View.OnClickListener, iconResId: Int) : SettingsRow(title, subTitle, onClickListener, iconResId)
} | apache-2.0 | d59ea3c72e730251707219168322872f | 37.269058 | 174 | 0.568968 | 4.722191 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinInvalidUClass.kt | 4 | 1508 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.light.LightPsiClassBuilder
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.uast.*
/**
* implementation of [UClass] for invalid code, when it is impossible to create a [KtLightClass]
*/
@ApiStatus.Internal
class KotlinInvalidUClass(
override val psi: PsiClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
constructor(name: String, context: PsiElement, givenParent: UElement?) : this(LightPsiClassBuilder(context, name), givenParent)
override fun getContainingFile(): PsiFile? = uastParent?.getContainingUFile()?.sourcePsi
override val sourcePsi: PsiElement? get() = null
override val uastAnchor: UIdentifier? get() = null
override val javaPsi: PsiClass get() = psi
override fun getFields(): Array<UField> = emptyArray()
override fun getInitializers(): Array<UClassInitializer> = emptyArray()
override fun getInnerClasses(): Array<UClass> = emptyArray()
override fun getMethods(): Array<UMethod> = emptyArray()
override fun getSuperClass(): UClass? = null
override fun getOriginalElement(): PsiElement? = null
}
| apache-2.0 | e3edbe12d5c92a7907c84f0ab79a5a52 | 34.069767 | 158 | 0.759284 | 4.583587 | false | false | false | false |
tginsberg/advent-2016-kotlin | src/main/kotlin/com/ginsberg/advent2016/Day08.kt | 1 | 1922 | /*
* Copyright (c) 2016 by Todd Ginsberg
*/
package com.ginsberg.advent2016
/**
* Advent of Code - Day 8: December 8, 2016
*
* From http://adventofcode.com/2016/day/8
*
*/
class Day08(input: List<String>, val height: Int = 6, val width: Int = 50) {
private val digits = Regex("""^\D*(\d+)\D*(\d+)\D*$""")
private val screen = Array(height) { Array(width, { false }) }
init {
input.forEach { interpretCommand(it) }
}
/**
* How many pixels should be lit?
*/
fun solvePart1(): Int =
screen.fold(0) { carry, next -> carry + next.count { it } }
/**
* What code is the screen trying to display?
*/
fun solvePart2(): String =
screen.map { it.map { if (it) "#" else " " }.joinToString("") }.joinToString("\n")
// This is all side-effects, ew.
fun interpretCommand(command: String) {
val (a, b) = getTheDigits(command)
when {
command.startsWith("rect") -> {
(0 until b).forEach { x ->
(0 until a).forEach { y ->
screen[x][y] = true
}
}
}
command.startsWith("rotate row") ->
screen[a] = rotate(screen[a], b)
command.startsWith("rotate column") -> {
val rotated = rotate(colToRow(a), b)
(0 until height).forEach { screen[it][a] = rotated[it] }
}
}
}
private fun colToRow(col: Int): Array<Boolean> =
(0 until height).map { screen[it][col] }.toTypedArray()
private fun rotate(row: Array<Boolean>, by: Int): Array<Boolean> =
(row.takeLast(by) + row.dropLast(by)).toTypedArray()
fun getTheDigits(line: String): Pair<Int, Int> =
digits.matchEntire(line)?.destructured?.let {
Pair(it.component1().toInt(), it.component2().toInt())
} ?: Pair(0, 0)
}
| mit | f8d4a10ff1db6f86dd817b95c369c8af | 28.569231 | 90 | 0.522373 | 3.776031 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixFactoryForTypeMismatchError.kt | 1 | 20904 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.isKFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.intentions.reflectToRegularFunctionType
import org.jetbrains.kotlin.idea.util.approximateWithResolvableType
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isNull
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.*
import org.jetbrains.kotlin.resolve.constants.IntegerValueTypeConstant
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.types.CommonSupertypes
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE
import org.jetbrains.kotlin.types.isDefinitelyNotNullType
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
//TODO: should use change signature to deal with cases of multiple overridden descriptors
class QuickFixFactoryForTypeMismatchError : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val actions = LinkedList<IntentionAction>()
val file = diagnostic.psiFile as KtFile
val context = file.analyzeWithContent()
val diagnosticElement = diagnostic.psiElement
if (diagnosticElement !is KtExpression) {
// INCOMPATIBLE_TYPES may be reported not only on expressions, but also on types.
// We ignore such cases here.
if (diagnostic.factory != Errors.INCOMPATIBLE_TYPES) {
LOG.error("Unexpected element: " + diagnosticElement.text)
}
return emptyList()
}
val expectedType: KotlinType
val expressionType: KotlinType?
when (diagnostic.factory) {
Errors.TYPE_MISMATCH -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.TYPE_MISMATCH_WARNING -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH_WARNING.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.NULL_FOR_NONNULL_TYPE -> {
val diagnosticWithParameters = Errors.NULL_FOR_NONNULL_TYPE.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = expectedType.makeNullable()
}
Errors.TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH -> {
val diagnosticWithParameters = Errors.TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.CONSTANT_EXPECTED_TYPE_MISMATCH -> {
val diagnosticWithParameters = Errors.CONSTANT_EXPECTED_TYPE_MISMATCH.cast(diagnostic)
expectedType = diagnosticWithParameters.b
expressionType = context.getType(diagnosticElement)
}
Errors.SIGNED_CONSTANT_CONVERTED_TO_UNSIGNED -> {
val constantValue = context[BindingContext.COMPILE_TIME_VALUE, diagnosticElement]
if (constantValue is IntegerValueTypeConstant) {
// Here we have unsigned type (despite really constant is signed)
expectedType = constantValue.getType(NO_EXPECTED_TYPE)
val signedConstantValue = with(IntegerValueTypeConstant) {
constantValue.convertToSignedConstant(diagnosticElement.findModuleDescriptor())
}
// And here we have signed type
expressionType = signedConstantValue.getType(NO_EXPECTED_TYPE)
} else return emptyList()
}
ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS -> {
val diagnosticWithParameters = ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.INCOMPATIBLE_TYPES -> {
val diagnosticWithParameters = Errors.INCOMPATIBLE_TYPES.cast(diagnostic)
expectedType = diagnosticWithParameters.b
expressionType = diagnosticWithParameters.a
}
else -> {
LOG.error("Unexpected diagnostic: " + DefaultErrorMessages.render(diagnostic))
return emptyList()
}
}
if (expressionType == null) {
LOG.error("No type inferred: " + diagnosticElement.text)
return emptyList()
}
if (diagnosticElement is KtStringTemplateExpression &&
expectedType.isChar() &&
ConvertStringToCharLiteralFix.isApplicable(diagnosticElement)
) {
actions.add(ConvertStringToCharLiteralFix(diagnosticElement))
}
if (expressionType.isSignedOrUnsignedNumberType() && expectedType.isSignedOrUnsignedNumberType()) {
var wrongPrimitiveLiteralFix: WrongPrimitiveLiteralFix? = null
if (diagnosticElement is KtConstantExpression && !KotlinBuiltIns.isChar(expectedType)) {
wrongPrimitiveLiteralFix = WrongPrimitiveLiteralFix(diagnosticElement, expectedType)
actions.add(wrongPrimitiveLiteralFix)
}
actions.add(NumberConversionFix(diagnosticElement, expressionType, expectedType, wrongPrimitiveLiteralFix))
actions.add(RoundNumberFix(diagnosticElement, expectedType, wrongPrimitiveLiteralFix))
}
if (KotlinBuiltIns.isCharSequenceOrNullableCharSequence(expectedType) || KotlinBuiltIns.isStringOrNullableString(expectedType)) {
actions.add(AddToStringFix(diagnosticElement, false))
if (expectedType.isMarkedNullable && expressionType.isMarkedNullable) {
actions.add(AddToStringFix(diagnosticElement, true))
}
}
val convertKClassToClassFix = ConvertKClassToClassFix.create(file, expectedType, expressionType, diagnosticElement)
if (convertKClassToClassFix != null) {
actions.add(convertKClassToClassFix)
}
if (expectedType.isInterface()) {
val expressionTypeDeclaration = expressionType.constructor.declarationDescriptor?.let {
descriptorToDeclaration(it)
} as? KtClassOrObject
if (expressionTypeDeclaration != null && expectedType != TypeUtils.makeNotNullable(expressionType)) {
actions.add(LetImplementInterfaceFix(expressionTypeDeclaration, expectedType, expressionType))
}
}
actions.addAll(WrapWithCollectionLiteralCallFix.create(expectedType, expressionType, diagnosticElement))
ConvertCollectionFix.getConversionTypeOrNull(expressionType, expectedType)?.let {
actions.add(ConvertCollectionFix(diagnosticElement, it))
}
fun KtExpression.getTopMostQualifiedForSelectorIfAny(): KtExpression {
var qualifiedOrThis = this
do {
val element = qualifiedOrThis
qualifiedOrThis = element.getQualifiedExpressionForSelectorOrThis()
} while (qualifiedOrThis !== element)
return qualifiedOrThis
}
// We don't want to cast a cast or type-asserted expression.
if (diagnostic.factory != Errors.SIGNED_CONSTANT_CONVERTED_TO_UNSIGNED &&
diagnosticElement !is KtBinaryExpressionWithTypeRHS &&
diagnosticElement.parent !is KtBinaryExpressionWithTypeRHS
) {
actions.add(CastExpressionFix(diagnosticElement.getTopMostQualifiedForSelectorIfAny(), expectedType))
}
if (!expectedType.isMarkedNullable && TypeUtils.isNullableType(expressionType)) {
val nullableExpected = expectedType.makeNullable()
if (expressionType.isSubtypeOf(nullableExpected)) {
val targetExpression = diagnosticElement.getTopMostQualifiedForSelectorIfAny()
// With implicit receivers (e.g., inside a scope function),
// NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS is reported on the callee, so we need
// to explicitly check for nullable implicit receiver
val checkCalleeExpression =
diagnostic.factory == ErrorsJvm.NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS &&
targetExpression.parent?.safeAs<KtCallExpression>()?.calleeExpression == targetExpression
getAddExclExclCallFix(targetExpression, checkCalleeExpression)?.let { actions.add(it) }
if (expectedType.isBoolean()) {
actions.add(AddEqEqTrueFix(targetExpression))
}
}
}
fun <D : KtCallableDeclaration> addChangeTypeFix(
callable: D,
expressionType: KotlinType,
createFix: (D, KotlinType) -> KotlinQuickFixAction<KtCallableDeclaration>
) {
val scope = callable.getResolutionScope(context, callable.getResolutionFacade())
val typeToInsert = expressionType.approximateWithResolvableType(scope, false)
if (typeToInsert.isKFunctionType) {
actions.add(createFix(callable, typeToInsert.reflectToRegularFunctionType()))
}
actions.add(createFix(callable, typeToInsert))
}
// Suggest replacing the parameter type `T` with its expected definitely non-nullable subtype `T & Any`.
// Types that contain DNN types as arguments (like `(Mutable)Collection<T & Any>`) are currently not supported.
// The "Change parameter type" action is generated only if the `DefinitelyNonNullableTypes` language feature is enabled:
// if it is disabled, the `T & Any` intersection type is resolved as just `T`, so the fix would not have any effect.
if (
diagnosticElement is KtReferenceExpression &&
expectedType.isDefinitelyNotNullType &&
diagnosticElement.module?.languageVersionSettings?.supportsFeature(LanguageFeature.DefinitelyNonNullableTypes) == true
) {
val descriptor = context[BindingContext.REFERENCE_TARGET, diagnosticElement]?.safeAs<CallableDescriptor>()
when (val declaration = safeGetDeclaration(descriptor)) {
is KtParameter -> {
// Check the parent parameter list to avoid creating actions for loop iterators
if (declaration.parent is KtParameterList) {
actions.add(ChangeParameterTypeFix(declaration, expectedType))
}
}
is KtProperty -> {
addChangeTypeFix(declaration, expectedType, ::ChangeVariableTypeFix)
}
}
}
// Property initializer type mismatch property type:
val property = PsiTreeUtil.getParentOfType(diagnosticElement, KtProperty::class.java)
if (property != null) {
val getter = property.getter
val initializer = property.initializer
if (QuickFixBranchUtil.canEvaluateTo(initializer, diagnosticElement)
|| getter != null && QuickFixBranchUtil.canFunctionOrGetterReturnExpression(getter, diagnosticElement)
) {
val returnType = property.returnType(expressionType, context)
addChangeTypeFix(property, returnType, ::ChangeVariableTypeFix)
}
}
val expressionParent = diagnosticElement.parent
// Mismatch in returned expression:
val function = if (expressionParent is KtReturnExpression)
expressionParent.getTargetFunction(context)
else
PsiTreeUtil.getParentOfType(diagnosticElement, KtFunction::class.java, true)
if (function is KtFunction && QuickFixBranchUtil.canFunctionOrGetterReturnExpression(function, diagnosticElement)) {
val returnType = function.returnType(expressionType, context)
addChangeTypeFix(function, returnType, ChangeCallableReturnTypeFix::ForEnclosing)
}
// Fixing overloaded operators:
if (diagnosticElement is KtOperationExpression) {
val resolvedCall = diagnosticElement.getResolvedCall(context)
if (resolvedCall != null) {
val declaration = getFunctionDeclaration(resolvedCall)
if (declaration != null) {
actions.add(ChangeCallableReturnTypeFix.ForCalled(declaration, expectedType))
}
}
}
// Change function return type when TYPE_MISMATCH is reported on call expression:
if (diagnosticElement is KtCallExpression) {
val resolvedCall = diagnosticElement.getResolvedCall(context)
if (resolvedCall != null) {
val declaration = getFunctionDeclaration(resolvedCall)
if (declaration != null) {
actions.add(ChangeCallableReturnTypeFix.ForCalled(declaration, expectedType))
}
}
}
// KT-10063: arrayOf() bounding single array element
val annotationEntry = PsiTreeUtil.getParentOfType(diagnosticElement, KtAnnotationEntry::class.java)
if (annotationEntry != null) {
if (KotlinBuiltIns.isArray(expectedType) && expressionType.isSubtypeOf(expectedType.arguments[0].type)
|| KotlinBuiltIns.isPrimitiveArray(expectedType)
) {
actions.add(AddArrayOfTypeFix(diagnosticElement, expectedType))
actions.add(WrapWithArrayLiteralFix(diagnosticElement))
}
}
diagnosticElement.getStrictParentOfType<KtParameter>()?.let {
if (it.defaultValue == diagnosticElement) {
actions.add(ChangeParameterTypeFix(it, expressionType))
}
}
val resolvedCall = diagnosticElement.getParentResolvedCall(context, true)
if (resolvedCall != null) {
// to fix 'type mismatch' on 'if' branches
// todo: the same with 'when'
val parentIf = QuickFixBranchUtil.getParentIfForBranch(diagnosticElement)
val argumentExpression = parentIf ?: diagnosticElement
val valueArgument = resolvedCall.call.getValueArgumentForExpression(argumentExpression)
if (valueArgument != null) {
val correspondingParameterDescriptor = resolvedCall.getParameterForArgument(valueArgument)
val correspondingParameter = safeGetDeclaration(correspondingParameterDescriptor) as? KtParameter
val expressionFromArgument = valueArgument.getArgumentExpression()
val valueArgumentType = when (diagnostic.factory) {
Errors.NULL_FOR_NONNULL_TYPE, Errors.SIGNED_CONSTANT_CONVERTED_TO_UNSIGNED -> expressionType
else -> expressionFromArgument?.let { context.getType(it) }
}
if (valueArgumentType != null) {
if (correspondingParameter != null) {
val callable = PsiTreeUtil.getParentOfType(correspondingParameter, KtCallableDeclaration::class.java, true)
val scope = callable?.getResolutionScope(context, callable.getResolutionFacade())
val typeToInsert = valueArgumentType.approximateWithResolvableType(scope, true)
actions.add(ChangeParameterTypeFix(correspondingParameter, typeToInsert))
}
val parameterVarargType = correspondingParameterDescriptor?.varargElementType
if ((parameterVarargType != null || resolvedCall.resultingDescriptor.fqNameSafe == FqName("kotlin.collections.mapOf"))
&& KotlinBuiltIns.isArray(valueArgumentType)
&& expressionType.arguments.isNotEmpty()
&& expressionType.arguments[0].type.constructor == expectedType.constructor
) {
actions.add(ChangeToUseSpreadOperatorFix(diagnosticElement))
}
}
}
}
return actions
}
private fun KtCallableDeclaration.returnType(candidateType: KotlinType, context: BindingContext): KotlinType {
val (initializers, functionOrGetter) = when (this) {
is KtNamedFunction -> listOfNotNull(this.initializer) to this
is KtProperty -> listOfNotNull(this.initializer, this.getter?.initializer) to this.getter
else -> return candidateType
}
val returnedExpressions = if (functionOrGetter != null) {
val descriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, functionOrGetter]
functionOrGetter
.collectDescendantsOfType<KtReturnExpression> { it.getTargetFunctionDescriptor(context) == descriptor }
.mapNotNull { it.returnedExpression }
.plus(initializers)
} else {
initializers
}.map { KtPsiUtil.safeDeparenthesize(it) }
returnedExpressions.singleOrNull()?.let {
if (it.isNull() || this.typeReference == null) return candidateType
}
val returnTypes = returnedExpressions.map { it.getActualType(this, context) ?: candidateType }.distinct()
return returnTypes.singleOrNull() ?: CommonSupertypes.commonSupertype(returnTypes)
}
private fun KtExpression.getActualType(declaration: KtCallableDeclaration, context: BindingContext): KotlinType? {
if (declaration.typeReference == null) return getType(context)
val property = KtPsiFactory(declaration).createDeclarationByPattern<KtProperty>("val x = $0", this)
val newContext = property.analyzeAsReplacement(this, context)
return property.initializer?.getType(newContext)
}
companion object {
private val LOG = Logger.getInstance(QuickFixFactoryForTypeMismatchError::class.java)
private fun getFunctionDeclaration(resolvedCall: ResolvedCall<*>): KtFunction? {
val result = safeGetDeclaration(resolvedCall.resultingDescriptor)
if (result is KtFunction) {
return result
}
return null
}
private fun safeGetDeclaration(descriptor: CallableDescriptor?): PsiElement? {
//do not create fix if descriptor has more than one overridden declaration
return if (descriptor == null || descriptor.overriddenDescriptors.size > 1) null else descriptorToDeclaration(descriptor)
}
}
}
| apache-2.0 | d0a6312e5614f084aa690d5befc7bde1 | 52.462916 | 158 | 0.676426 | 5.935264 | false | false | false | false |
siosio/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarExtraSlotPane.kt | 1 | 5389 | // 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.execution.runToolbar
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedActionToolbarComponent
import com.intellij.openapi.project.Project
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.swing.MigLayout
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingUtilities
import kotlin.math.absoluteValue
class RunToolbarExtraSlotPane(val project: Project, val cancel: () -> Unit) {
private val manager = RunToolbarSlotManager.getInstance(project)
val slotPane = JPanel(VerticalLayout(JBUI.scale(2))).apply {
isOpaque = false
}
private val components = mutableListOf<SlotComponent>()
private val managerListener = object : SlotListener {
override fun slotAdded() {
addSingleSlot()
}
override fun slotRemoved(index: Int) {
if(index >= 0 && index < components.size) {
removeSingleComponent(components[index])
}
else {
rebuild()
}
}
override fun rebuildPopup() {
rebuild()
}
}
private val pane = object : JPanel(VerticalLayout(JBUI.scale(2))) {
override fun addNotify() {
manager.addListener(managerListener)
if (manager.slotsCount() == 0) {
manager.addNewSlot()
} else {
build()
}
super.addNotify()
SwingUtilities.invokeLater {
pack()
}
}
override fun removeNotify() {
manager.removeListener(managerListener)
super.removeNotify()
}
}.apply {
border = JBUI.Borders.empty(3)
add(slotPane)
add(JPanel(MigLayout("ins 0, novisualpadding", "[min!]push[min!]")).apply {
isOpaque = false
border = JBUI.Borders.empty(2, 1, 0, 5)
this.add(JLabel(AllIcons.Toolbar.AddSlot).apply {
this.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
manager.addNewSlot()
}
})
})
this.add(JLabel(AllIcons.General.GearPlain))
})
}
internal fun getView(): JComponent = pane
private fun rebuild() {
build()
if(manager.slotsCount() > 0) {
pack()
}
}
private fun cancelPopup() {
SwingUtilities.invokeLater{
cancel()
}
}
private fun build() {
val count = manager.slotsCount()
if(count == 0) {
slotPane.removeAll()
components.clear()
cancelPopup()
return
} else {
val diff = count - components.size
repeat(diff.absoluteValue) { if(diff > 0) addNewSlot() else removeComponent(components[it])}
}
}
private fun addSingleSlot() {
addNewSlot()
pack()
}
private fun addNewSlot() {
val slot = createComponent()
slot.minus.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
getData(slot)?.let {
manager.removeSlot(it.id)
}
}
})
slotPane.add(slot.view)
components.add(slot)
}
private fun pack() {
slotPane.revalidate()
pane.revalidate()
slotPane.repaint()
pane.repaint()
UIUtil.getWindow(pane)?.let {
if (it.isShowing) {
it.pack()
}
}
}
private fun removeSingleComponent(component: SlotComponent) {
removeComponent(component)
if (components.isNotEmpty()) {
pack()
}
}
private fun removeComponent(component: SlotComponent) {
slotPane.remove(component.view)
components.remove(component)
if (components.isEmpty()) {
cancelPopup()
}
}
private fun getData(component: SlotComponent): SlotDate? {
val index = components.indexOf(component)
if(index < 0) return null
return manager.getData(index)
}
private fun createComponent(): SlotComponent {
val group = DefaultActionGroup()
val bar = FixWidthSegmentedActionToolbarComponent(ActionPlaces.RUN_TOOLBAR, group)
val component = SlotComponent(bar, JLabel(AllIcons.Toolbar.RemoveSlot))
bar.targetComponent = bar
DataManager.registerDataProvider(bar, DataProvider {
key ->
if(RunToolbarData.RUN_TOOLBAR_DATA_KEY.`is`(key)) {
getData(component)
}
else
null
})
val runToolbarActionsGroup = ActionManager.getInstance().getAction(
"RunToolbarActionsGroup") as DefaultActionGroup
val dataContext = DataManager.getInstance().getDataContext(bar)
val event = AnActionEvent.createFromDataContext("RunToolbarActionsGroup", null, dataContext)
for (action in runToolbarActionsGroup.getChildren(event)) {
if (action is ActionGroup && !action.isPopup) {
group.addAll(*action.getChildren(event))
}
else {
group.addAction(action)
}
}
return component
}
internal data class SlotComponent(val bar: SegmentedActionToolbarComponent, val minus: JComponent) {
val view = JPanel(MigLayout("ins 0, gapx 2, novisualpadding")).apply {
add(minus)
add(bar)
}
}
} | apache-2.0 | 96e641a165bf216aeaf8ed7dc829105b | 25.421569 | 158 | 0.666172 | 4.413595 | false | false | false | false |
rustamgaifullin/MP | app/src/main/kotlin/io/rg/mp/ui/expense/ExpenseServiceModule.kt | 1 | 1724 | package io.rg.mp.ui.expense
import com.google.api.services.drive.Drive
import com.google.api.services.sheets.v4.Sheets
import dagger.Module
import dagger.Provides
import io.rg.mp.drive.BalanceService
import io.rg.mp.drive.CategoryService
import io.rg.mp.drive.LocaleService
import io.rg.mp.drive.SpreadsheetService
import io.rg.mp.drive.TransactionService
import io.rg.mp.persistence.dao.CategoryDao
import io.rg.mp.persistence.dao.SpreadsheetDao
import io.rg.mp.ui.FragmentScope
import io.rg.mp.ui.ReloadViewAuthenticator
@Module
class ExpenseServiceModule {
@Provides
@FragmentScope
fun categoryService(sheets: Sheets) = CategoryService(sheets)
@Provides
@FragmentScope
fun spreadsheetService(drive: Drive) = SpreadsheetService(drive)
@Provides
@FragmentScope
fun localeService(sheets: Sheets) = LocaleService(sheets)
@Provides
@FragmentScope
fun transactionService(sheets: Sheets) = TransactionService(sheets)
@Provides
@FragmentScope
fun balanceService(sheets: Sheets) = BalanceService(sheets)
@Provides
@FragmentScope
fun expenseViewModel(
categoryService: CategoryService,
localeService: LocaleService,
transactionService: TransactionService,
balanceService: BalanceService,
categoryDao: CategoryDao,
spreadsheetDao: SpreadsheetDao) : ExpenseViewModel {
return ExpenseViewModel(categoryService,
localeService,
transactionService,
balanceService,
categoryDao,
spreadsheetDao)
}
@Provides
@FragmentScope
fun reloadViewAuthenticator() = ReloadViewAuthenticator()
}
| mit | 64d809384ad790a30bb096cfaf5d5a1a | 28.220339 | 71 | 0.717517 | 4.489583 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/test/kotlin/database/partition/FullTableScanPartitionTest.kt | 1 | 10586 | package database.partition
import com.onyx.persistence.query.from
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.query.AttributeUpdate
import com.onyx.persistence.query.Query
import com.onyx.persistence.query.QueryCriteria
import com.onyx.persistence.query.QueryCriteriaOperator
import database.base.DatabaseBaseTest
import entities.partition.FullTablePartitionEntity
import org.junit.Before
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
import org.junit.runners.Parameterized
import java.util.*
import kotlin.reflect.KClass
import kotlin.test.assertEquals
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(Parameterized::class)
class FullTableScanPartitionTest(override var factoryClass: KClass<*>) : DatabaseBaseTest(factoryClass) {
@Before
fun removeData() {
manager.from(FullTablePartitionEntity::class).delete()
}
@Test
fun aTestSavePartitionEntityWithIndex() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
}
@Test
fun bTestQueryPartitionEntityWithIndex() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L))
query.partition = 2L
val results = manager.executeQuery<Any>(query)
assertEquals(1, results.size, "Expected 1 result(s)")
}
@Test
fun bTestQueryPartitionEntityWithIndexNoDefinedPartitionInQuery() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L))
val results = manager.executeQuery<Any>(query)
assertEquals(2, results.size, "Expected 2 result(s)")
}
@Test
fun cTestQueryFindQueryPartitionEntityWithIndex() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L).and("partitionId", QueryCriteriaOperator.EQUAL, 2L))
val results = manager.executeQuery<Any>(query)
assertEquals(1, results.size, "Expected 1 result(s)")
}
@Test
fun dTestDeleteQueryPartitionEntity() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L).and("partitionId", QueryCriteriaOperator.EQUAL, 2L))
val results = manager.executeDelete(query)
assertEquals(1, results, "Expected 1 result(s)")
}
@Test
fun bTestDeleteQueryPartitionEntityWithIndex() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L))
query.partition = 2L
val results = manager.executeDelete(query)
assertEquals(1, results, "Expected 1 result(s)")
}
@Test
fun bTestDeleteQueryPartitionEntityWithIndexNoDefinedPartitionInQuery() {
val entity = FullTablePartitionEntity()
entity.id = 1L
entity.partitionId = 3L
entity.indexVal = 5L
manager.saveEntity<IManagedEntity>(entity)
val entity2 = FullTablePartitionEntity()
entity2.id = 2L
entity2.partitionId = 2L
entity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(entity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L))
val results = manager.executeDelete(query)
assertEquals(2, results, "Expected 2 result(s)")
}
@Test
fun dTestUpdateQueryPartitionEntity() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L).and("partitionId", QueryCriteriaOperator.EQUAL, 2L))
query.updates = Arrays.asList(AttributeUpdate("indexVal", 6L))
val results = manager.executeUpdate(query)
assertEquals(1, results, "Expected 1 result(s)")
}
@Test
fun bTestUpdateQueryPartitionEntityWithIndex() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L))
query.updates = Arrays.asList(AttributeUpdate("indexVal", 6L))
query.partition = 2L
val results = manager.executeUpdate(query)
assertEquals(1, results, "Expected 1 result(s)")
}
@Test
fun bTestUpdateQueryPartitionEntityWithIndexNoDefinedPartitionInQuery() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L))
query.updates = Arrays.asList(AttributeUpdate("indexVal", 6L))
val results = manager.executeUpdate(query)
assertEquals(2, results, "Expected 2 result(s)")
}
@Test
fun bTestUpdatePartitionField() {
val fullTablePartitionEntity = FullTablePartitionEntity()
fullTablePartitionEntity.id = 1L
fullTablePartitionEntity.partitionId = 3L
fullTablePartitionEntity.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity)
val fullTablePartitionEntity2 = FullTablePartitionEntity()
fullTablePartitionEntity2.id = 2L
fullTablePartitionEntity2.partitionId = 2L
fullTablePartitionEntity2.indexVal = 5L
manager.saveEntity<IManagedEntity>(fullTablePartitionEntity2)
val query = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 5L))
query.updates = Arrays.asList(AttributeUpdate("partitionId", 5L), AttributeUpdate("indexVal", 6L))
val results = manager.executeUpdate(query)
assertEquals(2, results, "Expected 2 result(s)")
val query2 = Query(FullTablePartitionEntity::class.java, QueryCriteria("indexVal", QueryCriteriaOperator.EQUAL, 6L))
query2.partition = 5L
val result = manager.executeQuery<Any>(query2)
assertEquals(2, result.size, "Expected 2 result(s)")
}
}
| agpl-3.0 | 70e8e884e9442e1727015f679d7f17a7 | 37.776557 | 175 | 0.734461 | 5.756389 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/outputValues/outputValuesWithExpression.kt | 9 | 574 | // WITH_STDLIB
// SUGGESTED_NAMES: triple, intIntIntTriple, intIntTriple, intTriple, getT
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_TYPES: kotlin.Int
// PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var b: kotlin.Int defined in foo
// PARAM_DESCRIPTOR: var c: kotlin.Int defined in foo
// SIBLING:
fun foo(a: Int): Int {
var b: Int = 1
var c: Int = 2
val t = <selection>if (a > 0) {
b += a
c -= b
b
}
else {
a
}</selection>
println(b + c)
return t
} | apache-2.0 | f3426efecffa8418f1a66ac4052d1da6 | 22 | 74 | 0.602787 | 3.317919 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/usagesSearch/utils.kt | 2 | 14286 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.search.usagesSearch
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.util.MethodSignatureUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.lazyPub
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.project.getNullableModuleInfo
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.hasJavaResolutionFacade
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.compiler.IDELanguageSettingsProvider
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.project.findAnalyzerServices
import org.jetbrains.kotlin.idea.references.unwrappedTargets
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport
import org.jetbrains.kotlin.idea.search.ReceiverTypeSearcherInfo
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.util.FuzzyType
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.fuzzyExtensionReceiverType
import org.jetbrains.kotlin.idea.util.toFuzzyType
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.descriptorUtil.isTypeRefinementEnabled
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.getSingleAbstractMethodOrNull
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.isValidOperator
@Deprecated(
"This method is obsolete and will be removed",
ReplaceWith(
"resolveToDescriptorIfAny(BodyResolveMode.FULL)",
"org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny",
"org.jetbrains.kotlin.resolve.lazy.BodyResolveMode"
)
)
@get:JvmName("getDescriptor")
val KtDeclaration.descriptorCompat: DeclarationDescriptor?
get() = if (this is KtParameter) this.descriptorCompat else this.resolveToDescriptorIfAny(BodyResolveMode.FULL)
@Deprecated(
"This method is obsolete and will be removed",
ReplaceWith(
"resolveToParameterDescriptorIfAny(BodyResolveMode.FULL)",
"org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny",
"org.jetbrains.kotlin.resolve.lazy.BodyResolveMode"
)
)
@get:JvmName("getDescriptor")
val KtParameter.descriptorCompat: ValueParameterDescriptor?
get() = this.resolveToParameterDescriptorIfAny(BodyResolveMode.FULL)
class KotlinConstructorCallLazyDescriptorHandle(ktElement: KtDeclaration) :
KotlinSearchUsagesSupport.ConstructorCallHandle {
private val descriptor: ConstructorDescriptor? by lazyPub { ktElement.constructor }
override fun referencedTo(element: KtElement): Boolean =
element.getConstructorCallDescriptor().let {
it != null && descriptor != null && it == descriptor
}
}
class JavaConstructorCallLazyDescriptorHandle(psiMethod: PsiMethod) :
KotlinSearchUsagesSupport.ConstructorCallHandle {
private val descriptor: ConstructorDescriptor? by lazyPub { psiMethod.getJavaMethodDescriptor() as? ConstructorDescriptor }
override fun referencedTo(element: KtElement): Boolean =
element.getConstructorCallDescriptor().let {
it != null && descriptor != null && it == descriptor
}
}
fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String? =
declaration.descriptor?.let { DescriptorRenderer.COMPACT.render(it) }
fun isSamInterface(psiClass: PsiClass): Boolean {
val classDescriptor = psiClass.getJavaMemberDescriptor() as? JavaClassDescriptor
return classDescriptor != null && getSingleAbstractMethodOrNull(classDescriptor) != null
}
fun hasType(element: KtExpression): Boolean =
element.analyze(BodyResolveMode.PARTIAL).getType(element) != null
val KtDeclaration.constructor: ConstructorDescriptor?
get() {
val context = this.analyze()
return when (this) {
is KtClassOrObject -> context[BindingContext.CLASS, this]?.unsubstitutedPrimaryConstructor
is KtFunction -> context[BindingContext.CONSTRUCTOR, this]
else -> null
}
}
val KtParameter.propertyDescriptor: PropertyDescriptor?
get() = this.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? PropertyDescriptor
fun PsiReference.checkUsageVsOriginalDescriptor(
targetDescriptor: DeclarationDescriptor,
declarationToDescriptor: (KtDeclaration) -> DeclarationDescriptor? = { it.descriptor },
checker: (usageDescriptor: DeclarationDescriptor, targetDescriptor: DeclarationDescriptor) -> Boolean
): Boolean {
return unwrappedTargets
.filterIsInstance<KtDeclaration>()
.any {
val usageDescriptor = declarationToDescriptor(it)
usageDescriptor != null && checker(usageDescriptor, targetDescriptor)
}
}
fun PsiReference.isConstructorUsage(ktClassOrObject: KtClassOrObject): Boolean = with(element) {
fun checkJavaUsage(): Boolean {
val call = getNonStrictParentOfType<PsiConstructorCall>()
return call == parent && call?.resolveConstructor()?.containingClass?.navigationElement == ktClassOrObject
}
fun checkKotlinUsage(): Boolean {
if (this !is KtElement) return false
val descriptor = getConstructorCallDescriptor() as? ConstructorDescriptor ?: return false
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor.containingDeclaration)
return declaration == ktClassOrObject || (declaration is KtConstructor<*> && declaration.getContainingClassOrObject() == ktClassOrObject)
}
checkJavaUsage() || checkKotlinUsage()
}
private fun KtElement.getConstructorCallDescriptor(): DeclarationDescriptor? {
val bindingContext = this.analyze()
val constructorCalleeExpression = getNonStrictParentOfType<KtConstructorCalleeExpression>()
if (constructorCalleeExpression != null) {
return bindingContext.get(BindingContext.REFERENCE_TARGET, constructorCalleeExpression.constructorReferenceExpression)
}
val callExpression = getNonStrictParentOfType<KtCallElement>()
if (callExpression != null) {
val callee = callExpression.calleeExpression
if (callee is KtReferenceExpression) {
return bindingContext.get(BindingContext.REFERENCE_TARGET, callee)
}
}
return null
}
// Check if reference resolves to extension function whose receiver is the same as declaration's parent (or its superclass)
// Used in extension search
fun PsiReference.isExtensionOfDeclarationClassUsage(declaration: KtNamedDeclaration): Boolean {
val descriptor = declaration.descriptor ?: return false
return checkUsageVsOriginalDescriptor(descriptor) { usageDescriptor, targetDescriptor ->
when (usageDescriptor) {
targetDescriptor -> false
!is FunctionDescriptor -> false
else -> {
val receiverDescriptor =
usageDescriptor.extensionReceiverParameter?.type?.constructor?.declarationDescriptor
val containingDescriptor = targetDescriptor.containingDeclaration
containingDescriptor == receiverDescriptor
|| (containingDescriptor is ClassDescriptor
&& receiverDescriptor is ClassDescriptor
&& DescriptorUtils.isSubclass(containingDescriptor, receiverDescriptor))
}
}
}
}
// Check if reference resolves to the declaration with the same parent
// Used in overload search
fun PsiReference.isUsageInContainingDeclaration(declaration: KtNamedDeclaration): Boolean {
val descriptor = declaration.descriptor ?: return false
return checkUsageVsOriginalDescriptor(descriptor) { usageDescriptor, targetDescriptor ->
usageDescriptor != targetDescriptor
&& usageDescriptor.containingDeclaration == targetDescriptor.containingDeclaration
}
}
fun PsiReference.isCallableOverrideUsage(declaration: KtNamedDeclaration): Boolean {
val toDescriptor: (KtDeclaration) -> CallableDescriptor? = { sourceDeclaration ->
if (sourceDeclaration is KtParameter) {
// we don't treat parameters in overriding method as "override" here (overriding parameters usages are searched optionally and via searching of overriding methods first)
if (sourceDeclaration.hasValOrVar()) sourceDeclaration.propertyDescriptor else null
} else {
sourceDeclaration.descriptor as? CallableDescriptor
}
}
val targetDescriptor = toDescriptor(declaration) ?: return false
return unwrappedTargets.any {
when (it) {
is KtDeclaration -> {
val usageDescriptor = toDescriptor(it)
usageDescriptor != null && OverridingUtil.overrides(
usageDescriptor,
targetDescriptor,
usageDescriptor.module.isTypeRefinementEnabled(),
false // don't distinguish between expect and non-expect callable descriptors, KT-38298, KT-38589
)
}
is PsiMethod -> {
declaration.toLightMethods().any { superMethod -> MethodSignatureUtil.isSuperMethod(superMethod, it) }
}
else -> false
}
}
}
fun <T : PsiNamedElement> List<T>.filterDataClassComponentsIfDisabled(kotlinOptions: KotlinReferencesSearchOptions): List<T> {
if (kotlinOptions.searchForComponentConventions) return this
fun PsiNamedElement.isComponentElement(): Boolean {
if (this !is PsiMethod) return false
val dataClassParent = ((parent as? KtLightClass)?.kotlinOrigin as? KtClass)?.isData() == true
if (!dataClassParent) return false
if (!Name.isValidIdentifier(name)) return false
val nameIdentifier = Name.identifier(name)
if (!DataClassDescriptorResolver.isComponentLike(nameIdentifier)) return false
return true
}
return filter { !it.isComponentElement() }
}
fun KtFile.forceResolveReferences(elements: List<KtElement>) {
getResolutionFacade().analyze(elements, BodyResolveMode.PARTIAL)
}
private fun PsiElement.resolveTargetToDescriptor(isDestructionDeclarationSearch: Boolean): FunctionDescriptor? {
if (isDestructionDeclarationSearch && this is KtParameter) {
return dataClassComponentFunction()
}
return when {
this is KtDeclaration -> resolveToDescriptorIfAny(BodyResolveMode.FULL)
this is PsiMember && hasJavaResolutionFacade() ->
this.getJavaOrKotlinMemberDescriptor()
else -> null
} as? FunctionDescriptor
}
private fun containsTypeOrDerivedInside(declaration: KtDeclaration, typeToSearch: FuzzyType): Boolean {
fun KotlinType.containsTypeOrDerivedInside(type: FuzzyType): Boolean {
return type.checkIsSuperTypeOf(this) != null || arguments.any { !it.isStarProjection && it.type.containsTypeOrDerivedInside(type) }
}
val descriptor = declaration.resolveToDescriptorIfAny() as? CallableDescriptor
val type = descriptor?.returnType
return type != null && type.containsTypeOrDerivedInside(typeToSearch)
}
private fun FuzzyType.toPsiClass(project: Project): PsiClass? {
val classDescriptor = type.constructor.declarationDescriptor ?: return null
val classDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, classDescriptor)
return when (classDeclaration) {
is PsiClass -> classDeclaration
is KtClassOrObject -> classDeclaration.toLightClass()
else -> null
}
}
private fun PsiElement.extractReceiverType(isDestructionDeclarationSearch: Boolean): FuzzyType? {
val descriptor = resolveTargetToDescriptor(isDestructionDeclarationSearch)?.takeIf { it.isValidOperator() } ?: return null
return if (descriptor.isExtension) {
descriptor.fuzzyExtensionReceiverType()!!
} else {
val classDescriptor = descriptor.containingDeclaration as? ClassDescriptor ?: return null
classDescriptor.defaultType.toFuzzyType(classDescriptor.typeConstructor.parameters)
}
}
fun PsiElement.getReceiverTypeSearcherInfo(isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo? {
val receiverType = runReadAction { extractReceiverType(isDestructionDeclarationSearch) } ?: return null
val psiClass = runReadAction { receiverType.toPsiClass(project) }
return ReceiverTypeSearcherInfo(psiClass) {
containsTypeOrDerivedInside(it, receiverType)
}
}
fun KtFile.getDefaultImports(): List<ImportPath> {
val moduleInfo = getNullableModuleInfo() ?: return emptyList()
return TargetPlatformDetector.getPlatform(this).findAnalyzerServices(project).getDefaultImports(
IDELanguageSettingsProvider.getLanguageVersionSettings(moduleInfo, project),
includeLowPriorityImports = true
)
}
fun PsiFile.scriptDefinitionExists(): Boolean = findScriptDefinition() != null | apache-2.0 | 1ab14c576a53f937a4cc70a187fefd90 | 44.069401 | 181 | 0.755985 | 5.63106 | false | false | false | false |
mcilloni/kt-uplink | src/main/kotlin/UplinkError.kt | 1 | 3598 | /*
* uplink, a simple daemon to implement a simple chat protocol
* Copyright (C) Marco Cilloni <[email protected]> 2016
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Exhibit B is not attached this software is compatible with the
* licenses expressed under Section 1.12 of the MPL v2.
*
*/
package com.github.mcilloni.uplink
import io.grpc.Status
import io.grpc.StatusException
import io.grpc.StatusRuntimeException
import java.util.concurrent.ExecutionException
internal inline fun <T> rpc(body: () -> T) = try {
body()
} catch (e: ExecutionException) {
throw normExc(e.cause ?: throw e)
} catch (e: StatusRuntimeException) {
throw if (e.status.code == Status.Code.UNAVAILABLE) UnavailableException() else normExc(e)
}
internal fun normExc(e: Throwable) : Throwable {
val msg = e.message ?: throw e
return when {
msg.contains("EAUTHFAIL") -> AuthFailException(e)
msg.contains("ESERVERFAULT") -> ServerFaultException(e)
msg.contains("ERESERVEDUSER") -> ReservedUserException(e)
msg.contains("EALREADYFRIENDS") -> AlreadyFriendsException(e)
msg.contains("ENOREQUEST") -> NoFriendshipRequestException(e)
msg.contains("ENOTMEMBER") -> NotMemberException(e)
else -> e
}
}
open class UplinkException internal constructor(msg: String, t : Throwable = Throwable()) : Exception(msg, t)
class UnknownErrcodeException internal constructor(errcode: Int, t : Throwable = Throwable()) : UplinkException("unknown errcode $errcode", t)
class AlreadyInvitedException internal constructor(t : Throwable = Throwable()) : UplinkException("user already invited to the given conversation", t)
class AlreadyFriendsException internal constructor(t : Throwable = Throwable()) : UplinkException("already friend with the given user", t)
class EmptyConvException internal constructor(t : Throwable = Throwable()) : UplinkException("empty conversation", t)
class NameAlreadyTakenException internal constructor(t : Throwable = Throwable()) : UplinkException("username already taken", t)
class NoConvException internal constructor(t : Throwable = Throwable()) : UplinkException("no such conversation", t)
class NoFriendshipRequestException internal constructor(t : Throwable = Throwable()) : UplinkException("no friendship request from this user", t)
class NoUserException internal constructor(t : Throwable = Throwable()) : UplinkException("no such user", t)
class NotInvitedException internal constructor(t : Throwable = Throwable()) : UplinkException("user not invited to the given conversation", t)
class NotMemberException internal constructor(t : Throwable = Throwable()) : UplinkException("user not member of the given conversation", t)
class SelfInviteException internal constructor(t : Throwable = Throwable()) : UplinkException("self invite is not allowed", t)
class ServerFaultException internal constructor(t : Throwable = Throwable()) : UplinkException("server error", t)
class BrokeProtoException internal constructor(t : Throwable = Throwable()) : UplinkException("protocol broken, please report", t)
class AuthFailException internal constructor(t : Throwable = Throwable()) : UplinkException("login data rejected", t)
class ReservedUserException internal constructor(t : Throwable = Throwable()) : UplinkException("trying to access data of a reserved user", t)
class UnavailableException internal constructor() : Exception("Uplink is unavailable") | mpl-2.0 | 2154f3d06c1b86786160e74d8ed4c6aa | 61.051724 | 150 | 0.757365 | 4.431034 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/v3/util/VertxUtil.kt | 1 | 7942 | package xyz.nulldev.ts.api.v3.util
import io.vertx.core.Handler
import io.vertx.core.buffer.Buffer
import io.vertx.core.http.HttpClientRequest
import io.vertx.core.http.HttpClientResponse
import io.vertx.core.http.HttpServerResponse
import io.vertx.core.http.RequestOptions
import io.vertx.core.streams.ReadStream
import io.vertx.core.streams.WriteStream
import io.vertx.kotlin.core.http.requestOptionsOf
import java.net.URL
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
fun HttpServerResponse.tryEnd() {
if (!closed() && !ended())
end()
}
suspend fun ReadStream<*>.awaitEnd() = suspendCoroutine<Unit> { cont ->
endHandler {
cont.resume(Unit)
}
exceptionHandler {
cont.resumeWithException(it)
}
}
suspend fun ReadStream<*>.resumeAndAwaitEnd() = suspendCoroutine<Unit> { cont ->
endHandler {
cont.resume(Unit)
}
exceptionHandler {
cont.resumeWithException(it)
}
try {
resume()
} catch (t: Throwable) {
cont.resumeWithException(t)
}
}
suspend fun HttpClientResponse.awaitBody() = suspendCoroutine<Buffer?> { cont ->
var resumed = false
bodyHandler {
if (!resumed) {
resumed = true
cont.resume(it)
}
}
exceptionHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(it)
}
}
endHandler {
if (!resumed) {
resumed = true
cont.resume(null)
}
}
}
fun <T> WriteStream<T>.watched(block: (T) -> Unit) = object : WriteStream<T> {
override fun setWriteQueueMaxSize(maxSize: Int): WriteStream<T> {
[email protected](maxSize)
return this
}
override fun writeQueueFull(): Boolean {
return [email protected]()
}
override fun write(data: T): WriteStream<T> {
block(data)
[email protected](data)
return this
}
override fun end() {
[email protected]()
}
override fun drainHandler(handler: Handler<Void>?): WriteStream<T> {
[email protected](handler)
return this
}
override fun exceptionHandler(handler: Handler<Throwable>?): WriteStream<T> {
[email protected](handler)
return this
}
}
fun <T> combineWriteStreams(a: WriteStream<T>, b: WriteStream<T>) = object : WriteStream<T> {
override fun setWriteQueueMaxSize(maxSize: Int): WriteStream<T> {
a.setWriteQueueMaxSize(maxSize)
b.setWriteQueueMaxSize(maxSize)
return this
}
override fun writeQueueFull(): Boolean {
return a.writeQueueFull() || b.writeQueueFull()
}
override fun write(data: T): WriteStream<T> {
a.write(data)
b.write(data)
return this
}
override fun end() {
a.end()
b.end()
}
override fun drainHandler(handler: Handler<Void>?): WriteStream<T> {
a.drainHandler(handler)
b.drainHandler(handler)
return this
}
override fun exceptionHandler(handler: Handler<Throwable>?): WriteStream<T> {
a.exceptionHandler(handler)
b.exceptionHandler(handler)
return this
}
}
suspend fun HttpClientRequest.awaitResponse() = suspendCoroutine<HttpClientResponse> { cont ->
var resumed = false
handler {
pause()
if (!resumed) {
resumed = true
cont.resume(it)
}
}
exceptionHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(it)
}
}
endHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(IllegalStateException("Stream ended with no response!"))
}
}
end()
}
suspend fun <T> ReadStream<T>.awaitSingle() = suspendCoroutine<T> { cont ->
var resumed = false
handler {
pause()
if (!resumed) {
resumed = true
cont.resume(it)
}
}
exceptionHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(it)
}
}
endHandler {
pause()
if (!resumed) {
resumed = true
cont.resumeWithException(IllegalStateException("Stream ended with no response!"))
}
}
}
fun URL.asRequestOptions(): RequestOptions {
val isSSL = this.protocol.equals("https", false)
return requestOptionsOf(
host = host,
port = if (port != -1) port else if (isSSL) 443 else 80,
ssl = isSSL,
uri = toURI().toString()
)
}
/**
* Reads a specific number of bytes from the input stream
*
* @returns The remaining ReadStream (paused) along with the read ByteArray. If there are less data in the stream than the
* request amount of bytes, the returned byte array will be smaller
*/
suspend fun ReadStream<Buffer>.readBytes(bytes: Int): Pair<ReadStream<Buffer>, ByteArray> = suspendCoroutine { cont ->
require(bytes >= 0)
var remainingBuffer: Buffer? = null
var remainingHandler: Handler<Buffer>? = null
var remainingExceptionHandler: Handler<Throwable>? = null
var remainingEndHandler: Handler<Void>? = null
val remaining = object : ReadStream<Buffer> {
var paused = false
override fun fetch(amount: Long): ReadStream<Buffer> {
if (amount > 0) {
if (remainingBuffer != null) remainingHandler?.handle(remainingBuffer)
remainingBuffer = null
[email protected](amount - 1)
}
return this
}
override fun pause(): ReadStream<Buffer> {
paused = true
[email protected]()
return this
}
override fun resume(): ReadStream<Buffer> {
paused = false
if (remainingBuffer != null) remainingHandler?.handle(remainingBuffer)
remainingBuffer = null
// Handlers could have paused stream again while handling remaining buffer
if (!paused) [email protected]()
return this
}
override fun handler(handler: Handler<Buffer>?): ReadStream<Buffer> {
if (handler != null) remainingHandler = handler
return this
}
override fun exceptionHandler(handler: Handler<Throwable>?): ReadStream<Buffer> {
if (handler != null) remainingExceptionHandler = handler
return this
}
override fun endHandler(endHandler: Handler<Void>?): ReadStream<Buffer> {
if (endHandler != null) remainingEndHandler = endHandler
return this
}
}
val read = Buffer.buffer(bytes)
var allRead = false
handler {
if (allRead) {
remainingHandler?.handle(it)
} else {
val newLength = read.length() + it.length()
if (newLength >= bytes) {
val toRead = bytes - read.length()
read.appendBuffer(it, 0, toRead)
if (newLength > bytes) remainingBuffer = it.slice(toRead, it.length())
pause()
allRead = true
cont.resume(remaining to read.bytes)
} else {
read.appendBuffer(it, 0, it.length())
}
}
}
exceptionHandler {
if (!allRead) {
cont.resumeWithException(it)
allRead = true
} else {
remainingExceptionHandler?.handle(it)
}
}
endHandler {
if (!allRead) {
cont.resume(EmptyReadStream<Buffer>() to read.bytes)
allRead = true
} else {
remainingEndHandler?.handle(it)
}
}
}
| apache-2.0 | c31dcc69aa86baa00ce3dd7010cb38e0 | 25.211221 | 122 | 0.585873 | 4.612079 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/fragments/discovery/VectorSettingsDiscoveryFragment.kt | 2 | 7643 | /*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.fragments.discovery
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.airbnb.mvrx.MvRx
import com.airbnb.mvrx.args
import com.airbnb.mvrx.fragmentViewModel
import com.airbnb.mvrx.withState
import com.google.android.material.snackbar.Snackbar
import im.vector.R
import im.vector.activity.MXCActionBarActivity
import im.vector.activity.ReviewTermsActivity
import im.vector.activity.util.TERMS_REQUEST_CODE
import im.vector.extensions.withArgs
import im.vector.fragments.VectorBaseMvRxFragment
import kotlinx.android.synthetic.main.fragment_simple_epoxy.*
import org.matrix.androidsdk.features.terms.TermsManager
import org.matrix.androidsdk.rest.model.pid.ThreePid
class VectorSettingsDiscoveryFragment : VectorBaseMvRxFragment(), SettingsDiscoveryController.InteractionListener {
override fun getLayoutResId() = R.layout.fragment_simple_epoxy
private val viewModel by fragmentViewModel(DiscoverySettingsViewModel::class)
private lateinit var controller: SettingsDiscoveryController
lateinit var sharedViewModel: DiscoverySharedViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
sharedViewModel = ViewModelProviders.of(requireActivity()).get(DiscoverySharedViewModel::class.java)
controller = SettingsDiscoveryController(requireContext(), this).also {
epoxyRecyclerView.setController(it)
}
sharedViewModel.navigateEvent.observe(this, Observer {
if (it.peekContent().first == DiscoverySharedViewModel.NEW_IDENTITY_SERVER_SET_REQUEST) {
viewModel.changeIdentityServer(it.peekContent().second)
}
})
viewModel.errorLiveEvent.observe(this, Observer {
it.getContentIfNotHandled()?.let { throwable ->
Snackbar.make(coordinatorLayout, throwable.toString(), Snackbar.LENGTH_LONG).show()
}
})
}
override fun invalidate() = withState(viewModel) { state ->
controller.setData(state)
}
override fun onResume() {
super.onResume()
(activity as? MXCActionBarActivity)?.supportActionBar?.setTitle(R.string.settings_discovery_category)
//If some 3pids are pending, we can try to check if they have been verified here
viewModel.refreshPendingEmailBindings()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == TERMS_REQUEST_CODE) {
if (Activity.RESULT_OK == resultCode) {
viewModel.refreshModel()
} else {
//add some error?
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onSelectIdentityServer() = withState(viewModel) { state ->
if (state.termsNotSigned) {
ReviewTermsActivity.intent(requireContext(),
TermsManager.ServiceType.IdentityService,
SetIdentityServerViewModel.sanitatizeBaseURL(state.identityServer() ?: ""),
null).also {
startActivityForResult(it, TERMS_REQUEST_CODE)
}
}
}
override fun onTapRevokeEmail(email: String) {
viewModel.revokeEmail(email)
}
override fun onTapShareEmail(email: String) {
viewModel.shareEmail(email)
}
override fun checkEmailVerification(email: String, bind: Boolean) {
viewModel.finalizeBind3pid(ThreePid.MEDIUM_EMAIL, email, bind)
}
override fun checkMsisdnVerification(msisdn: String, code: String, bind: Boolean) {
viewModel.submitMsisdnToken(msisdn, code, bind)
}
override fun onTapRevokeMsisdn(msisdn: String) {
viewModel.revokeMsisdn(msisdn)
}
override fun onTapShareMsisdn(msisdn: String) {
viewModel.shareMsisdn(msisdn)
}
override fun onTapChangeIdentityServer() = withState(viewModel) { state ->
//we should prompt if there are bound items with current is
val pidList = ArrayList<PidInfo>().apply {
state.emailList()?.let { addAll(it) }
state.phoneNumbersList()?.let { addAll(it) }
}
val hasBoundIds = pidList.any { it.isShared() == PidInfo.SharedState.SHARED }
if (hasBoundIds) {
//we should prompt
AlertDialog.Builder(requireActivity())
.setTitle(R.string.change_identity_server)
.setMessage(getString(R.string.settings_discovery_disconnect_with_bound_pid, state.identityServer(), state.identityServer()))
.setPositiveButton(R.string._continue) { _, _ -> navigateToChangeIsFragment(state) }
.setNegativeButton(R.string.cancel, null)
.show()
Unit
} else {
navigateToChangeIsFragment(state)
}
}
override fun onTapDisconnectIdentityServer() {
//we should prompt if there are bound items with current is
withState(viewModel) { state ->
val pidList = ArrayList<PidInfo>().apply {
state.emailList()?.let { addAll(it) }
state.phoneNumbersList()?.let { addAll(it) }
}
val hasBoundIds = pidList.any { it.isShared() == PidInfo.SharedState.SHARED }
if (hasBoundIds) {
//we should prompt
AlertDialog.Builder(requireActivity())
.setTitle(R.string.disconnect_identity_server)
.setMessage(getString(R.string.settings_discovery_disconnect_with_bound_pid, state.identityServer(), state.identityServer()))
.setPositiveButton(R.string._continue) { _, _ -> viewModel.changeIdentityServer(null) }
.setNegativeButton(R.string.cancel, null)
.show()
} else {
viewModel.changeIdentityServer(null)
}
}
}
override fun onTapRetryToRetrieveBindings() {
viewModel.retrieveBinding()
}
private fun navigateToChangeIsFragment(state: DiscoverySettingsState) {
SetIdentityServerFragment.newInstance(args<String>().toString(), state.identityServer()).also {
requireFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.anim_slide_in_bottom, R.anim.anim_slide_out_bottom, R.anim.anim_slide_in_bottom, R.anim.anim_slide_out_bottom)
.replace(R.id.vector_settings_page, it, getString(R.string.identity_server))
.addToBackStack(null)
.commit()
}
}
companion object {
fun newInstance(matrixId: String) = VectorSettingsDiscoveryFragment()
.withArgs {
putString(MvRx.KEY_ARG, matrixId)
}
}
}
| apache-2.0 | 3bc011a59a0391066df50cf917434d65 | 37.407035 | 158 | 0.658904 | 4.79185 | false | false | false | false |
rbatista/algorithms | challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/hashmaps/FrequencyQueries.kt | 1 | 1539 | /**
* https://www.hackerrank.com/challenges/frequency-queries/problem
*/
package com.raphaelnegrisoli.hackerrank.hashmaps
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.StringBuilder
fun main(args: Array<String>) {
val reader = BufferedReader(InputStreamReader(System.`in`))
val q = reader.readLine()!!.trim().toInt()
val frequency : MutableMap<Int, Int> = HashMap(1000000)
val dataByOccurrence : MutableMap<Int, Int> = HashMap(1000000)
val builder = StringBuilder()
for (i in 0 until q) {
val (op, data) = reader.readLine()!!.trim().split(" ").map { it.toInt() }
when (op) {
1 -> {
val f = frequency[data] ?: 0
frequency[data] = f + 1
dataByOccurrence[f] = if ((dataByOccurrence[f] ?: 0) > 0) dataByOccurrence[f]!! - 1 else 0
dataByOccurrence[f + 1] = (dataByOccurrence[f + 1] ?: 0) + 1
}
2 -> {
val f = frequency[data] ?: 0
frequency[data] = if (f > 0) f - 1 else 0
dataByOccurrence[f] = if ((dataByOccurrence[f] ?: 0) > 0) dataByOccurrence[f]!! - 1 else 0
if (f > 0) {
dataByOccurrence[f - 1] = (dataByOccurrence[f - 1] ?: 0) + 1
}
}
3 -> {
val r = if ((dataByOccurrence[data] ?: 0) > 0) 1 else 0
builder.append(r).append("\n")
}
}
}
println(builder.toString())
} | mit | 2ae8034ad293e736b52ad34408e4a6c1 | 28.615385 | 106 | 0.525666 | 4.071429 | false | false | false | false |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/data/source/local/DoubanMomentContentLocalDataSource.kt | 1 | 2616 | /*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.data.source.local
import android.support.annotation.VisibleForTesting
import com.marktony.zhihudaily.data.DoubanMomentContent
import com.marktony.zhihudaily.data.source.LocalDataNotFoundException
import com.marktony.zhihudaily.data.source.Result
import com.marktony.zhihudaily.data.source.datasource.DoubanMomentContentDataSource
import com.marktony.zhihudaily.database.dao.DoubanMomentContentDao
import com.marktony.zhihudaily.util.AppExecutors
import kotlinx.coroutines.experimental.withContext
/**
* Created by lizhaotailang on 2017/5/25.
*
* Concrete implementation of a [DoubanMomentContent] data source as database.
*/
class DoubanMomentContentLocalDataSource private constructor(
private val mAppExecutors: AppExecutors,
private val mDoubanMomentContentDao: DoubanMomentContentDao
) : DoubanMomentContentDataSource {
companion object {
private var INSTANCE: DoubanMomentContentLocalDataSource? = null
@JvmStatic
fun getInstance(appExecutors: AppExecutors, doubanMomentContentDao: DoubanMomentContentDao): DoubanMomentContentLocalDataSource {
if (INSTANCE == null) {
synchronized(DoubanMomentContentLocalDataSource::javaClass) {
INSTANCE = DoubanMomentContentLocalDataSource(appExecutors, doubanMomentContentDao)
}
}
return INSTANCE!!
}
@VisibleForTesting
fun clearInstance() {
INSTANCE = null
}
}
override suspend fun getDoubanMomentContent(id: Int): Result<DoubanMomentContent> = withContext(mAppExecutors.ioContext) {
val content = mDoubanMomentContentDao.queryContentById(id)
if (content != null) Result.Success(content) else Result.Error(LocalDataNotFoundException())
}
override suspend fun saveContent(content: DoubanMomentContent) {
withContext(mAppExecutors.ioContext) {
mDoubanMomentContentDao.insert(content)
}
}
}
| apache-2.0 | 717fd8c4d2bea8fb91f1b7c666a456d6 | 35.84507 | 137 | 0.740061 | 5.211155 | false | false | false | false |
JetBrains/teamcity-azure-plugin | plugin-azure-server/src/main/kotlin/jetbrains/buildServer/clouds/azure/arm/connector/tasks/FetchInstancesTaskImpl.kt | 1 | 20760 | /*
* Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure.arm.connector.tasks
import com.google.common.cache.CacheBuilder
import com.intellij.openapi.diagnostic.Logger
import com.microsoft.azure.management.Azure
import com.microsoft.azure.management.compute.VirtualMachine
import com.microsoft.azure.management.compute.implementation.*
import com.microsoft.azure.management.containerinstance.ContainerGroup
import com.microsoft.azure.management.network.PublicIPAddress
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasId
import jetbrains.buildServer.clouds.azure.arm.AzureCloudDeployTarget
import jetbrains.buildServer.clouds.azure.arm.AzureConstants
import jetbrains.buildServer.clouds.azure.arm.throttler.*
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo
import jetbrains.buildServer.serverSide.TeamCityProperties
import jetbrains.buildServer.util.StringUtil
import rx.Observable
import rx.Single
import java.time.Clock
import java.time.LocalDateTime
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
import kotlin.collections.HashSet
data class FetchInstancesTaskInstanceDescriptor (
val id: String,
val name: String,
val tags: Map<String, String>,
val publicIpAddress: String?,
val provisioningState: String?,
val startDate: Date?,
val powerState: String?,
val error: TypedCloudErrorInfo?
)
data class FetchInstancesTaskParameter(val serverId: String)
class FetchInstancesTaskImpl(private val myNotifications: AzureTaskNotifications) : AzureThrottlerCacheableTask<Azure, FetchInstancesTaskParameter, List<FetchInstancesTaskInstanceDescriptor>> {
private val myTimeoutInSeconds = AtomicLong(60)
private val myIpAddresses = AtomicReference<Array<IPAddressDescriptor>>(emptyArray())
private val myInstancesCache = createCache()
private val myNotifiedInstances = ConcurrentHashMap.newKeySet<String>()
private val myLastUpdatedDate = AtomicReference<LocalDateTime>(LocalDateTime.MIN)
init {
myNotifications.register<AzureTaskVirtualMachineStatusChangedEventArgs> {
updateVirtualMachine(it.api, it.virtualMachine)
}
myNotifications.register<AzureTaskDeploymentStatusChangedEventArgs> { args ->
val dependency = args.deployment.dependencies().firstOrNull { it.resourceType() == VIRTUAL_MACHINES_RESOURCE_TYPE }
if (dependency != null) {
if (args.isDeleting) {
updateVirtualMachine(args.api, dependency.id(), args.isDeleting)
} else {
if (args.deployment.provisioningState() == PROVISIONING_STATE_SUCCEEDED) {
updateVirtualMachine(args.api, dependency.id(), args.isDeleting)
}
}
return@register
}
val containerProvider = args.deployment.providers().firstOrNull { it.namespace() == CONTAINER_INSTANCE_NAMESPACE }
if (containerProvider != null) {
val id = args.deployment.id()
val name = args.deployment.name()
val containerId = ResourceUtils.constructResourceId(
ResourceUtils.subscriptionFromResourceId(id),
ResourceUtils.groupFromResourceId(id),
containerProvider.namespace(),
CONTAINER_GROUPS_RESOURCE_TYPE,
name,
"")
updateContainer(args.api, containerId, args.isDeleting)
}
}
}
override fun create(api: Azure, parameter: FetchInstancesTaskParameter): Single<List<FetchInstancesTaskInstanceDescriptor>> {
if (StringUtil.isEmptyOrSpaces(api.subscriptionId())) {
LOG.debug("FetchInstancesTask returns empty list. Subscription is empty")
return Single
.just(emptyList<FetchInstancesTaskInstanceDescriptor>());
}
val ipAddresses =
fetchIPAddresses(api)
val machineInstancesImpl =
if (TeamCityProperties.getBoolean(TEAMCITY_CLOUDS_AZURE_TASKS_FETCHINSTANCES_FULLSTATEAPI_DISABLE))
Observable.just(emptyMap())
else api.virtualMachines().inner()
.listAsync("true")
.flatMap { x -> Observable.from(x.items()) }
.toMap { vm -> vm.id() }
val machineInstances =
api
.virtualMachines()
.listAsync()
.materialize()
.filter {
if (it.isOnError) LOG.warnAndDebugDetails("Could not read VM state:", it.throwable)
!it.isOnError
}
.dematerialize<VirtualMachine>()
.withLatestFrom(machineInstancesImpl) { vm, vmStatusesMap ->
vm to vmStatusesMap[vm.id()]
}
.flatMap { (vm, vmStatus) ->
fetchVirtualMachineWithCache(vm, vmStatus)
}
val containerInstances =
api
.containerGroups()
.listAsync()
.materialize()
.filter {
if (it.isOnError) LOG.warnAndDebugDetails("Could not read container state:", it.throwable)
!it.isOnError
}
.dematerialize<ContainerGroup>()
.map { getLiveInstanceFromSnapshot(it) ?: fetchContainer(it) }
return machineInstances
.mergeWith(containerInstances)
.toList()
.takeLast(1)
.withLatestFrom(ipAddresses) { instances, ipList ->
myLastUpdatedDate.set(getCurrentUTC())
myIpAddresses.set(ipList.toTypedArray())
val newInstances = instances.associateBy { it.id.toLowerCase() }
myInstancesCache.putAll(newInstances)
val keysInCache = myInstancesCache.asMap().keys.toSet()
val notifiedInstances = HashSet(myNotifiedInstances)
myInstancesCache.invalidateAll(keysInCache.minus(newInstances.keys.plus(notifiedInstances)))
myNotifiedInstances.removeAll(notifiedInstances)
Unit
}
.map { getFilteredResources(parameter) }
.toSingle()
}
private fun getLiveInstanceFromSnapshot(resource: HasId?): InstanceDescriptor? {
if (resource?.id() == null) return null
val instance = myInstancesCache.getIfPresent(resource.id().toLowerCase())
if (instance == null) return null
if (needUpdate(instance.lastUpdatedDate)) return null
return instance
}
private fun fetchIPAddresses(api: Azure): Observable<MutableList<IPAddressDescriptor>> {
return api
.publicIPAddresses()
.listAsync()
.filter { !it.ipAddress().isNullOrBlank() }
.map { IPAddressDescriptor(it.name(), it.resourceGroupName(), it.ipAddress(), getAssignedNetworkInterfaceId(it)) }
.toList()
.takeLast(1)
.doOnNext {
LOG.debug("Received list of ip addresses")
}
.onErrorReturn {
val message = "Failed to get list of public ip addresses: " + it.message
LOG.debug(message, it)
emptyList()
}
}
private fun updateContainer(api: Azure, containerId: String, isDeleting: Boolean) {
if (isDeleting) {
myNotifiedInstances.remove(containerId.toLowerCase())
myInstancesCache.invalidate(containerId.toLowerCase())
return
}
api.containerGroups()
.getByIdAsync(containerId)
.map { it?.let { fetchContainer(it) } }
.withLatestFrom(fetchIPAddresses(api)) {
instance, ipList ->
myIpAddresses.set(ipList.toTypedArray())
if (instance != null) {
myNotifiedInstances.add(instance.id.toLowerCase())
myInstancesCache.put(instance.id.toLowerCase(), instance)
} else {
myNotifiedInstances.remove(containerId.toLowerCase())
myInstancesCache.invalidate(containerId.toLowerCase())
}
}
.take(1)
.toCompletable()
.await()
}
private fun fetchContainer(containerGroup: ContainerGroup): InstanceDescriptor {
val state = containerGroup.containers()[containerGroup.name()]?.instanceView()?.currentState()
val startDate = state?.startTime()?.toDate()
val powerState = state?.state()
val instance = InstanceDescriptor(
containerGroup.id(),
containerGroup.name(),
containerGroup.tags(),
null,
startDate,
powerState,
null,
null,
getCurrentUTC())
return instance
}
private fun fetchVirtualMachineWithCache(vm: VirtualMachine, vmStatus: VirtualMachineInner?): Observable<InstanceDescriptor> {
if (vmStatus?.instanceView() == null) {
val cachedInstance = getLiveInstanceFromSnapshot(vm)
if (cachedInstance != null)
return Observable.just(cachedInstance)
else
return fetchVirtualMachine(vm)
}
return fetchVirtualMachine(vm, vmStatus.instanceView())
}
private fun fetchVirtualMachine(vm: VirtualMachine, instanceView: VirtualMachineInstanceViewInner): Observable<InstanceDescriptor> {
val tags = vm.tags()
val name = vm.name()
val instanceState = getInstanceState(instanceView, tags, name)
LOG.debug("Reading state of virtual machine '$name' using full state API")
return Observable.just(InstanceDescriptor(
vm.id(),
vm.name(),
vm.tags(),
instanceState.provisioningState,
instanceState.startDate,
instanceState.powerState,
null,
vm.primaryNetworkInterfaceId(),
getCurrentUTC()
))
}
private fun fetchVirtualMachine(vm: VirtualMachine): Observable<InstanceDescriptor> {
val tags = vm.tags()
val id = vm.id()
val name = vm.name()
LOG.debug("Reading state of virtual machine '$name'")
return vm.refreshInstanceViewAsync()
.map { getInstanceState(it.inner(), tags, name) }
.onErrorReturn {
LOG.debug("Failed to get status of virtual machine '$name': $it.message", it)
InstanceViewState(null, null, null, it)
}
.map { instanceView ->
val instance = InstanceDescriptor(
id,
name,
tags,
instanceView.provisioningState,
instanceView.startDate,
instanceView.powerState,
if (instanceView.error != null) TypedCloudErrorInfo.fromException(instanceView.error) else null,
vm.primaryNetworkInterfaceId(),
getCurrentUTC())
instance
}
}
private fun updateVirtualMachine(api: Azure, virtualMachine: VirtualMachine) {
fetchVirtualMachine(virtualMachine)
.withLatestFrom(fetchIPAddresses(api)) { instance, ipList ->
myIpAddresses.set(ipList.toTypedArray())
myInstancesCache.put(instance.id.toLowerCase(), instance)
}
.take(1)
.toCompletable()
.await()
}
private fun updateVirtualMachine(api: Azure, virtualMachineId: String, isDeleting: Boolean) {
if (isDeleting) {
myNotifiedInstances.remove(virtualMachineId.toLowerCase())
myInstancesCache.invalidate(virtualMachineId.toLowerCase())
return
}
api.virtualMachines()
.getByIdAsync(virtualMachineId)
.flatMap { if (it != null) fetchVirtualMachine(it) else Observable.just(null) }
.withLatestFrom(fetchIPAddresses(api)) {
instance, ipList ->
myIpAddresses.set(ipList.toTypedArray())
if (instance != null) {
myNotifiedInstances.add(instance.id.toLowerCase())
myInstancesCache.put(instance.id.toLowerCase(), instance)
} else {
myNotifiedInstances.remove(virtualMachineId.toLowerCase())
myInstancesCache.invalidate(virtualMachineId.toLowerCase())
}
}
.take(1)
.toCompletable()
.await()
}
private fun getAssignedNetworkInterfaceId(publicIpAddress: PublicIPAddress?): String? {
if (publicIpAddress == null || !publicIpAddress.hasAssignedNetworkInterface()) return null
val refId: String = publicIpAddress.inner().ipConfiguration().id()
val parentId = ResourceUtils.parentResourceIdFromResourceId(refId)
return parentId
}
override fun getFromCache(parameter: FetchInstancesTaskParameter): List<FetchInstancesTaskInstanceDescriptor>? {
return if (needUpdate(myLastUpdatedDate.get())) null else getFilteredResources(parameter)
}
override fun needCacheUpdate(parameter: FetchInstancesTaskParameter): Boolean {
return needUpdate(myLastUpdatedDate.get())
}
override fun checkThrottleTime(parameter: FetchInstancesTaskParameter): Boolean {
val lastUpdatedDateTime = myLastUpdatedDate.get()
return lastUpdatedDateTime.plusSeconds(getTaskThrottleTime()) < getCurrentUTC()
}
override fun areParametersEqual(parameter: FetchInstancesTaskParameter, other: FetchInstancesTaskParameter): Boolean {
return parameter == other
}
private fun getTaskThrottleTime(): Long {
return TeamCityProperties.getLong(TEAMCITY_CLOUDS_AZURE_THROTTLER_TASK_THROTTLE_TIMEOUT_SEC, 10)
}
private fun getFilteredResources(filter: FetchInstancesTaskParameter): List<FetchInstancesTaskInstanceDescriptor> {
return myInstancesCache.asMap().values
.filter {
val resourceServerId = it.tags[AzureConstants.TAG_SERVER]
filter.serverId.equals(resourceServerId, true).also {
if (!it) LOG.debug("Ignore resource with invalid server tag $resourceServerId")
}
}
.map { instance ->
FetchInstancesTaskInstanceDescriptor(
instance.id,
instance.name,
instance.tags,
getPublicIPAddressOrDefault(instance),
instance.provisioningState,
instance.startDate,
instance.powerState,
instance.error
) }
.toList()
}
override fun invalidateCache() {
myInstancesCache.invalidateAll()
myIpAddresses.set(emptyArray())
myNotifiedInstances.clear()
}
private fun getInstanceState(instanceView: VirtualMachineInstanceViewInner, tags: Map<String, String>, name: String): InstanceViewState {
var provisioningState: String? = null
var startDate: Date? = null
var powerState: String? = null
for (status in instanceView.statuses()) {
val code = status.code()
if (code.startsWith(PROVISIONING_STATE)) {
provisioningState = code.substring(PROVISIONING_STATE.length)
val dateTime = status.time()
if (dateTime != null) {
startDate = dateTime.toDate()
}
}
if (code.startsWith(POWER_STATE)) {
powerState = code.substring(POWER_STATE.length)
}
}
if (tags.containsKey(AzureConstants.TAG_INVESTIGATION)) {
LOG.debug("Virtual machine $name is marked by ${AzureConstants.TAG_INVESTIGATION} tag")
provisioningState = "Investigation"
}
return InstanceViewState(provisioningState, startDate, powerState, null)
}
override fun setCacheTimeout(timeoutInSeconds: Long) {
myTimeoutInSeconds.set(timeoutInSeconds)
}
private fun getPublicIPAddressOrDefault(instance: InstanceDescriptor): String? {
var ipAddresses = myIpAddresses.get()
if (ipAddresses.isEmpty()) return null
val name = instance.name
val ips = ipAddresses.filter {
instance.primaryNetworkInterfaceId != null && it.assignedNetworkInterfaceId == instance.primaryNetworkInterfaceId
}
if (ips.isNotEmpty()) {
for (ip in ips) {
LOG.debug("Received public ip ${ip.ipAddress} for virtual machine $name, assignedNetworkInterfaceId ${ip.assignedNetworkInterfaceId}")
}
val ip = ips.first().ipAddress
if (!ip.isNullOrBlank()) {
return ip
}
} else {
LOG.debug("No public ip received for virtual machine $name")
}
return null
}
private fun createCache() = CacheBuilder.newBuilder().expireAfterWrite(32 * 60, TimeUnit.SECONDS).build<String, InstanceDescriptor>()
private fun getCurrentUTC() = LocalDateTime.now(Clock.systemUTC())
private fun needUpdate(lastUpdatedDate: LocalDateTime) : Boolean {
return lastUpdatedDate.plusSeconds(myTimeoutInSeconds.get()) < getCurrentUTC()
}
data class InstanceViewState (val provisioningState: String?, val startDate: Date?, val powerState: String?, val error: Throwable?)
data class CacheKey (val server: String?)
data class CacheValue(val instances: List<InstanceDescriptor>, val ipAddresses: List<IPAddressDescriptor>, val lastUpdatedDateTime: LocalDateTime)
data class InstanceDescriptor (
val id: String,
val name: String,
val tags: Map<String, String>,
val provisioningState: String?,
val startDate: Date?,
val powerState: String?,
val error: TypedCloudErrorInfo?,
val primaryNetworkInterfaceId: String?,
val lastUpdatedDate: LocalDateTime
)
data class IPAddressDescriptor (
val name: String,
val resourceGroupName: String,
val ipAddress: String,
val assignedNetworkInterfaceId: String?
)
companion object {
private val LOG = Logger.getInstance(FetchInstancesTaskImpl::class.java.name)
private const val PUBLIC_IP_SUFFIX = "-pip"
private const val PROVISIONING_STATE = "ProvisioningState/"
private const val PROVISIONING_STATE_SUCCEEDED = "Succeeded"
private const val POWER_STATE = "PowerState/"
private const val CACHE_KEY = "key"
private const val VIRTUAL_MACHINES_RESOURCE_TYPE = "Microsoft.Compute/virtualMachines"
private const val CONTAINER_INSTANCE_NAMESPACE = "Microsoft.ContainerInstance"
private const val CONTAINER_GROUPS_RESOURCE_TYPE = "containerGroups"
}
}
| apache-2.0 | f070457de556cbe598f5fe13a93ecaf0 | 41.453988 | 193 | 0.605106 | 5.662848 | false | false | false | false |
VoIPGRID/vialer-android | app/src/main/java/com/voipgrid/vialer/api/PhoneAccountFetcher.kt | 1 | 3472 | package com.voipgrid.vialer.api
import com.voipgrid.vialer.User
import com.voipgrid.vialer.api.models.PhoneAccount
import org.joda.time.DateTime
import retrofit2.Call
import retrofit2.Response
/**
* This class exists to provide a caching layer between when fetching PhoneAccounts, this is because
* it is a task that we need to perform on potentially hundreds of call records and the actual data
* being retrieved rarely changes, so we do not want to perform the same request very often.
*
*/
class PhoneAccountFetcher(private val api : VoipgridApi) {
private var cache: PhoneAccountsCache = PhoneAccountsCache()
/**
* Fetch a phone account, this has a caching layer in-front of it so
* it can be called frequently without spamming network requests
* for the same record.
*
*/
fun fetch(id: String, callback: Callback) {
cache = loadCacheFromSharedPreferences()
if (cache.isOutdated()) {
invalidateCache()
}
val account = cache[id]
if (account != null) {
callback.onSuccess(account)
return
}
api.phoneAccount(id).enqueue(HttpHandler(id, callback))
}
/**
* Completed resets our cache from both in-memory and shared
* preferences.
*
*/
private fun invalidateCache() {
cache = PhoneAccountsCache()
User.internal.phoneAccountsCache = null
}
/**
* Attempt to check shared preferences for a version of our PhoneAccounts cache.
*
*/
private fun loadCacheFromSharedPreferences() : PhoneAccountsCache {
if (!cache.isEmpty()) return cache
val storedCache : PhoneAccountsCache? = User.internal.phoneAccountsCache
if (storedCache != null) {
return storedCache
}
return PhoneAccountsCache()
}
/**
* The HTTP handler receives responses from the retrofit.
*
*/
inner class HttpHandler(private val id: String, private val callback: Callback) : retrofit2.Callback<PhoneAccount> {
override fun onFailure(call: Call<PhoneAccount>, t: Throwable) {
}
override fun onResponse(call: Call<PhoneAccount>, response: Response<PhoneAccount>) {
if (!response.isSuccessful) {
return
}
val account = response.body() ?: return
cache[id] = account
callback.onSuccess(account)
User.internal.phoneAccountsCache = cache
}
}
/**
* Provide a callback for when the fetcher has found a phone account.
*
*/
interface Callback {
fun onSuccess(phoneAccount: PhoneAccount)
}
/**
* Provides a class to cache the phone accounts that are found.
*
*/
class PhoneAccountsCache : HashMap<String, PhoneAccount>() {
private val initialTime = DateTime()
/**
* Check if the data held by this cache is outdated, if so this should
* be invalidated and the information reset.
*
*/
fun isOutdated() : Boolean {
return initialTime.isBefore(DateTime().minusDays(DAYS_VALID_FOR))
}
companion object {
/**
* We will store the records for this many days before invalidating the cache
* completely and re-fetching the records.
*
*/
const val DAYS_VALID_FOR = 3
}
}
} | gpl-3.0 | a8d5e3228505886a7fb97e20debf9385 | 26.132813 | 120 | 0.617224 | 4.945869 | false | false | false | false |
VerifAPS/verifaps-lib | ide/src/main/kotlin/edu/kit/iti/formal/automation/ide/editors/smv.kt | 1 | 2674 | package edu.kit.iti.formal.automation.ide.editors
import edu.kit.iti.formal.automation.ide.AntlrLexerFactory
import edu.kit.iti.formal.automation.ide.Colors
import edu.kit.iti.formal.automation.ide.Lookup
import edu.kit.iti.formal.smv.parser.SMVLexer
import edu.kit.iti.formal.smv.parser.SMVLexer.*
import edu.kit.iti.formal.automation.ide.BaseLanguageSupport
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.Lexer
import org.fife.ui.rsyntaxtextarea.Style
import org.fife.ui.rsyntaxtextarea.SyntaxScheme
import java.util.*
class SmvLanguageSupport(lookup: Lookup) : BaseLanguageSupport() {
override val mimeType: String = "text/smv"
override val extension: Collection<String> = Collections.singleton("smv")
override val syntaxScheme: SyntaxScheme = SmvSyntaxScheme(lookup)
override val antlrLexerFactory: AntlrLexerFactory
get() = object : AntlrLexerFactory {
override fun create(code: String): Lexer =
SMVLexer(CharStreams.fromString(code))
}
//override val parserData: ParserData?
// get() = ParserData(SMVParser.ruleNames, SMVLexer.VOCABULARY, SMVLexer._ATN)
}
class SmvSyntaxScheme(lookup: Lookup) : SyntaxScheme(true) {
private val colors: Colors by lookup.with()
private val STRUCTURAL_KEYWORDS = setOf(
ASSIGN, TRANS, CTLSPEC, SPEC, PSLSPEC, LTLSPEC, INVAR, INVARSPEC, MODULE,
INIT, NEXT, ARRAY, ASSIGN, BOOLEAN, CASE, COMMA, COMPASSION, CONSTANTS,
CTLSPEC, DEFINE, FAIRNESS, FROZENVAR, INITBIG, INVAR,
INVARSPEC, ISA, IVAR, JUSTICE, LTLSPEC, MODULE, NAME, PROCESS,
PSLSPEC, SIGNED, SPEC,
TRANS, UNSIGNED,
VAR, WORD, OF
)
private val SEPS = setOf(
COLON, COLONEQ, DCOLON, SEMI, LBRACE, RBRACE, LPAREN, RPAREN, RBRACKET, LBRACKET, DOTDOT, DOT)
private val OPERATORS = setOf(S,
IN, INIT, NEXT, LT, LTE, MINUS, MOD, NEQ, O, OR,
PLUS, SHIFTL, SHIFTR, STAR, DIV, EF, EG, EQ, EQUIV, ESAC,
EU, EX, F, G, GT, GTE, H, IMP, V, X, XNOR, XOR, Y, Z, NOT,
AF, AG, AND, AU, AX, T, U, UNION
)
private val LITERALS = setOf(
TRUE, FALSE, WORD_LITERAL, FLOAT, NUMBER
)
override fun getStyle(index: Int): Style {
return when (index) {
in SEPS -> colors.separators
ERROR_CHAR -> colors.error
in STRUCTURAL_KEYWORDS -> colors.structural
in OPERATORS -> colors.control
in LITERALS -> colors.literal
ID -> colors.identifier
SL_COMMENT -> colors.comment
else -> colors.default
}
}
}
| gpl-3.0 | cceed9f7bde5f680a0abbf7dc4e81dcc | 39.515152 | 106 | 0.653702 | 3.643052 | false | false | false | false |
AlmasB/FXGL | fxgl/src/main/kotlin/com/almasb/fxgl/app/scene/ErrorSubScene.kt | 1 | 2150 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.app.scene
import com.almasb.fxgl.logging.stackTraceToString
import com.almasb.fxgl.scene.SubScene
import com.almasb.fxgl.ui.MDIWindow
import javafx.scene.control.Button
import javafx.scene.control.ScrollPane
import javafx.scene.control.TextArea
import javafx.scene.layout.VBox
class ErrorSubScene(
val sceneWidth: Double,
val sceneHeight: Double,
/**
* Error to be displayed.
*/
val error: Throwable,
/**
* Action to run on subscene close.
*/
val action: Runnable) : SubScene() {
init {
val btnOK = Button("Exit game")
btnOK.setOnAction {
action.run()
}
val scrollPane = ScrollPane(makeStackTraceArea())
scrollPane.setPrefSize(sceneWidth, sceneHeight)
val window = MDIWindow()
window.isCloseable = false
window.title = "Error Reporter"
window.contentPane.children += VBox(btnOK, scrollPane)
contentRoot.children += window
}
private fun makeStackTraceArea() = TextArea(makeErrorMessage() + "\n\n" + makeStackTrace()).apply {
isEditable = false
isWrapText = true
// guesstimate size
setPrefSize(sceneWidth, (text.count { it == '\n' } + 1) * 20.0)
}
private fun makeErrorMessage(): String {
val name: String
val line: String
if (error.stackTrace.isEmpty()) {
name = "Empty stack trace"
line = "Empty stack trace"
} else {
val trace = error.stackTrace.first()
name = trace.className.substringAfterLast('.') + "." + trace.methodName + "()"
line = trace.toString().substringAfter('(').substringBefore(')')
}
return "Message: ${error.message}\n" +
"Type: ${error.javaClass.simpleName}\n" +
"Method: $name\n" +
"Line: $line"
}
private fun makeStackTrace() = error.stackTraceToString()
} | mit | f0b5d1a1e5abea627ae2ed9c7d275d69 | 26.576923 | 103 | 0.595349 | 4.369919 | false | false | false | false |
luxons/seven-wonders | sw-server/src/main/kotlin/org/luxons/sevenwonders/server/validation/DestinationAccessValidator.kt | 1 | 1736 | package org.luxons.sevenwonders.server.validation
import org.luxons.sevenwonders.server.repositories.LobbyRepository
import org.springframework.stereotype.Component
import java.util.regex.Pattern
@Component
class DestinationAccessValidator(private val lobbyRepository: LobbyRepository) {
fun hasAccess(username: String?, destination: String): Boolean {
return when {
username == null -> false // unnamed user cannot belong to anything
hasForbiddenGameReference(username, destination) -> false
hasForbiddenLobbyReference(username, destination) -> false
else -> true
}
}
private fun hasForbiddenGameReference(username: String, destination: String): Boolean {
val gameMatcher = gameDestination.matcher(destination)
if (!gameMatcher.matches()) {
return false // no game reference is always OK
}
val gameId = gameMatcher.group("id").toLong()
return !isUserInLobby(username, gameId)
}
private fun hasForbiddenLobbyReference(username: String, destination: String): Boolean {
val lobbyMatcher = lobbyDestination.matcher(destination)
if (!lobbyMatcher.matches()) {
return false // no lobby reference is always OK
}
val lobbyId = lobbyMatcher.group("id").toLong()
return !isUserInLobby(username, lobbyId)
}
private fun isUserInLobby(username: String, lobbyId: Long): Boolean =
lobbyRepository.find(lobbyId).containsUser(username)
companion object {
private val lobbyDestination = Pattern.compile(".*?/lobby/(?<id>\\d+?)(/.*)?")
private val gameDestination = Pattern.compile(".*?/game/(?<id>\\d+?)(/.*)?")
}
}
| mit | 6255ee3ec10eac74b9d9c0314e18542e | 36.73913 | 92 | 0.675115 | 4.717391 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/permissions/PermissionsManager.kt | 1 | 3616 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.permissions
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
object PermissionsManager {
private fun Context.hasPermission(perm: String) =
ContextCompat.checkSelfPermission(this, perm) == PackageManager.PERMISSION_GRANTED
private fun Activity.shouldShowRationale(perm: String) =
ActivityCompat.shouldShowRequestPermissionRationale(this, perm)
fun hasWriteCalendarNoCache(context: Context)
= context.hasPermission(Manifest.permission.WRITE_CALENDAR)
fun hasReadCalendarNoCache(context: Context)
= context.hasPermission(Manifest.permission.READ_CALENDAR)
fun hasCoarseLocationNoCache(context: Context)
= context.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
private var hasWriteCalendarCached: Boolean = false
private var hasReadCalendarCached: Boolean = false
private var hasAccessCoarseLocationCached: Boolean = false
fun hasWriteCalendar(context: Context): Boolean {
if (!hasWriteCalendarCached)
hasWriteCalendarCached = hasWriteCalendarNoCache(context)
return hasWriteCalendarCached
}
fun hasReadCalendar(context: Context): Boolean {
if (!hasReadCalendarCached)
hasReadCalendarCached = hasReadCalendarNoCache(context)
return hasReadCalendarCached
}
fun hasAccessCoarseLocation(context: Context): Boolean {
if (!hasAccessCoarseLocationCached)
hasAccessCoarseLocationCached = hasCoarseLocationNoCache(context)
return hasAccessCoarseLocationCached
}
fun hasAllCalendarPermissions(context: Context) = hasWriteCalendar(context) && hasReadCalendar(context)
fun hasAllCalendarPermissionsNoCache(context: Context) = hasWriteCalendarNoCache(context) && hasReadCalendarNoCache(context)
fun shouldShowCalendarRationale(activity: Activity) =
activity.shouldShowRationale(Manifest.permission.WRITE_CALENDAR) || activity.shouldShowRationale(Manifest.permission.READ_CALENDAR)
fun shouldShowLocationRationale(activity: Activity) =
activity.shouldShowRationale(Manifest.permission.ACCESS_COARSE_LOCATION)
fun requestCalendarPermissions(activity: Activity) =
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR), 0)
fun requestLocationPermissions(activity: Activity) =
ActivityCompat.requestPermissions(activity,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 0)
} | gpl-3.0 | a1d3d08f8c24fd7a556262e101b3754d | 41.552941 | 143 | 0.74917 | 5.129078 | false | false | false | false |
hyst329/OpenFool | core/src/ru/hyst329/openfool/MainMenuScreen.kt | 1 | 5571 | package ru.hyst329.openfool
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.viewport.FitViewport
import com.kotcrab.vis.ui.widget.VisProgressBar
import com.kotcrab.vis.ui.widget.VisTextButton
/**
* Created by hyst329 on 13.03.2017.
* Licensed under MIT License.
*/
internal class MainMenuScreen(private val game: OpenFoolGame) : Screen {
private val stage: Stage = Stage(FitViewport(800f, 480f))
private var logo: Sprite = Sprite(Texture(Gdx.files.internal("logos/mm_logo.png")))
private var hammerAndSickle: Sprite = Sprite(Texture(Gdx.files.internal("holidays/hammersickle.png")))
private var santaHat: Sprite = Sprite(Texture(Gdx.files.internal("holidays/santahat.png")))
private var canStart: Boolean = false
private val newGameButton: VisTextButton
private val settingsButton: VisTextButton
private val quitButton: VisTextButton
private val progressBar: VisProgressBar
init {
// Initialise the stage
Gdx.input.inputProcessor = stage
game.orientationHelper.requestOrientation(OrientationHelper.Orientation.LANDSCAPE)
newGameButton = VisTextButton(game.localeBundle.get("NewGame"))
newGameButton.setBounds(40f, 300f, 250f, 80f)
newGameButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
// super.clicked(event, x, y);
if (canStart)
newGame()
}
})
stage.addActor(newGameButton)
settingsButton = VisTextButton(game.localeBundle.get("Settings"))
settingsButton.setBounds(40f, 200f, 250f, 80f)
settingsButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
// super.clicked(event, x, y);
showSettings()
}
})
stage.addActor(settingsButton)
quitButton = VisTextButton(game.localeBundle.get("Quit"))
quitButton.setBounds(40f, 100f, 250f, 80f)
quitButton.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
// super.clicked(event, x, y);
quit()
}
})
stage.addActor(quitButton)
progressBar = VisProgressBar(0f, 1f, 1e-3f, false)
progressBar.setBounds(40f, 40f, 720f, 60f)
progressBar.setAnimateDuration(0.2f)
stage.addActor(progressBar)
}
override fun show() {
}
override fun render(delta: Float) {
when (getCurrentHoliday()) {
Holiday.OCTOBER_REVOLUTION -> Gdx.gl.glClearColor(0.8f, 0.0f, 0.0f, 1f)
Holiday.NEW_YEAR -> Gdx.gl.glClearColor(0.0f, 0.6f, 0.9f, 1f)
null -> Gdx.gl.glClearColor(0.2f, 0.8f, 0.3f, 1f)
}
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
stage.act(delta)
stage.draw()
game.batch.transformMatrix = stage.viewport.camera.view
game.batch.projectionMatrix = stage.viewport.camera.projection
game.batch.begin()
if (game.assetManager.update()) {
canStart = true
logo.setCenter(stage.viewport.worldWidth * 560f / 840f, stage.viewport.worldHeight * 250f / 480f)
logo.draw(game.batch)
when (getCurrentHoliday()) {
Holiday.OCTOBER_REVOLUTION -> {
hammerAndSickle.setCenter(stage.viewport.worldWidth * 165f / 840f, stage.viewport.worldHeight * 430f / 480f)
hammerAndSickle.setScale(0.35f)
hammerAndSickle.draw(game.batch)
}
Holiday.NEW_YEAR -> {
santaHat.setCenter(stage.viewport.worldWidth * 165f / 840f, stage.viewport.worldHeight * 430f / 480f)
santaHat.setScale(0.3f)
santaHat.draw(game.batch)
}
null -> {
}
}
} else {
val progress = game.assetManager.progress
game.font.draw(game.batch, game.localeBundle.format("LoadingAssets",
Math.round(progress * 100)), stage.viewport.worldWidth / 2.8f, stage.viewport.worldHeight / 4.4f)
progressBar.value = progress
}
game.batch.end()
newGameButton.isVisible = canStart
settingsButton.isVisible = canStart
quitButton.isVisible = canStart
progressBar.isVisible = !canStart
if (Gdx.input.isKeyJustPressed(Input.Keys.BACK) || Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
Gdx.app.exit()
}
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
stage.viewport.camera.update()
}
override fun pause() {
}
override fun resume() {
}
override fun hide() {
}
override fun dispose() {
}
private fun newGame() {
game.screen = NewGameScreen(game)
dispose()
}
private fun showSettings() {
game.screen = SettingsScreen(game)
dispose()
}
private fun quit() {
dispose()
Gdx.app.exit()
}
}
| gpl-3.0 | 9de1bc9de249a48de40d891fdf5b1683 | 33.602484 | 128 | 0.620355 | 4.126667 | false | false | false | false |
ysl3000/PathfindergoalAPI | PathfinderAPI/src/main/java/com/github/ysl3000/bukkit/pathfinding/goals/PathfinderGoalGimmiCookie.kt | 1 | 2453 | package com.github.ysl3000.bukkit.pathfinding.goals
import com.github.ysl3000.bukkit.pathfinding.entity.Insentient
import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderGoal
import org.bukkit.Material
import org.bukkit.entity.Creature
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import java.util.*
/**
* Created by 2008Choco
*/
class PathfinderGoalGimmiCookie(private val pathfinderGoalEntity: Insentient, private val creature: Creature) : PathfinderGoal {
private var isGenerous = true
private var hasGivenCookie = false
private var nearbyEntities: List<Entity>? = null
private var nearestPlayer: Player? = null
override fun shouldExecute(): Boolean {
if (!isGenerous) {
return false
}
val nearbyEntities = creature.getNearbyEntities(5.0, 5.0, 5.0)
if (nearbyEntities.isEmpty()) {
return false
}
this.nearbyEntities = nearbyEntities
return nearbyEntities.stream().anyMatch { Player::class.java.isInstance(it) }
}
override fun shouldTerminate(): Boolean {
return !hasGivenCookie
}
override fun init() {
this.nearestPlayer = getNearestPlayerFrom(nearbyEntities!!).orElse(null)
this.nearbyEntities = null
this.creature.equipment?.setItemInMainHand(COOKIE)
this.creature.target = nearestPlayer
this.pathfinderGoalEntity.getNavigation().moveTo(nearestPlayer!!)
}
override fun execute() {
this.pathfinderGoalEntity.jump()
if (creature.location.distanceSquared(nearestPlayer!!.location) <= 1) {
this.creature.world.dropItem(nearestPlayer!!.location, COOKIE)
this.creature.equipment?.setItemInMainHand(null)
this.isGenerous = false
this.hasGivenCookie = true
}
}
override fun reset() {
this.nearestPlayer = null
this.hasGivenCookie = false
}
private fun getNearestPlayerFrom(entities: List<Entity>): Optional<Player> {
return entities.stream()
.filter { Player::class.java.isInstance(it) }
.map<Player> { Player::class.java.cast(it) }
.min(Comparator
.comparingDouble { p -> creature.location.distanceSquared(p.location) })
}
companion object {
private val COOKIE = ItemStack(Material.COOKIE)
}
} | mit | f998462cccac40d2c0f7744b4db2f2e7 | 30.87013 | 128 | 0.6702 | 4.593633 | false | false | false | false |
xfournet/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/LogEvents.kt | 1 | 2954 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.internal.statistic.eventLog
import com.intellij.util.containers.ContainerUtil
import java.util.*
open class LogEvent(val session: String, val bucket: String,
recorderId: String,
recorderVersion: String,
type: String) {
val time = System.currentTimeMillis()
val recorder: LogEventRecorder = LogEventRecorder(removeTabsOrSpaces(recorderId), recorderVersion)
val action: LogEventAction = LogEventAction(removeTabsOrSpaces(type))
fun shouldMerge(next: LogEvent): Boolean {
if (session != next.session) return false
if (bucket != next.bucket) return false
if (recorder.id != next.recorder.id) return false
if (recorder.version != next.recorder.version) return false
if (action.id != next.action.id) return false
if (action.data != next.action.data) return false
return true
}
private fun removeTabsOrSpaces(str : String) : String {
return str.replace(" ", "_").replace("\t", "_")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEvent
if (session != other.session) return false
if (bucket != other.bucket) return false
if (time != other.time) return false
if (recorder != other.recorder) return false
if (action != other.action) return false
return true
}
override fun hashCode(): Int {
var result = session.hashCode()
result = 31 * result + bucket.hashCode()
result = 31 * result + time.hashCode()
result = 31 * result + recorder.hashCode()
result = 31 * result + action.hashCode()
return result
}
}
class LogEventRecorder(val id: String, val version: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventRecorder
if (id != other.id) return false
if (version != other.version) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + version.hashCode()
return result
}
}
class LogEventAction(val id: String) {
var data: MutableMap<String, Any> = Collections.emptyMap()
fun addData(key: String, value: Any) {
if (data.isEmpty()) {
data = ContainerUtil.newHashMap()
}
data.put(key, value)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventAction
if (id != other.id) return false
if (data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + (data?.hashCode() ?: 0)
return result
}
} | apache-2.0 | 3a139f1085d36d3730300c921921f858 | 27.413462 | 140 | 0.660122 | 4.190071 | false | false | false | false |
Ekito/koin | koin-projects/koin-androidx-viewmodel/src/main/java/org/koin/androidx/viewmodel/scope/ScopeExt.kt | 1 | 2901 | /*
* Copyright 2017-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.koin.androidx.viewmodel.scope
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStore
import androidx.savedstate.SavedStateRegistryOwner
import org.koin.androidx.viewmodel.ViewModelOwnerDefinition
import org.koin.androidx.viewmodel.ViewModelParameter
import org.koin.androidx.viewmodel.createViewModelProvider
import org.koin.androidx.viewmodel.resolveInstance
import org.koin.core.parameter.ParametersDefinition
import org.koin.core.qualifier.Qualifier
import org.koin.core.scope.Scope
import kotlin.reflect.KClass
/**
* Scope extensions to help for ViewModel
*
* @author Arnaud Giuliani
*/
typealias SavedStateRegistryOwnerDefinition = () -> SavedStateRegistryOwner
typealias ViewModelStoreDefinition = () -> ViewModelStore
fun emptyState(): BundleDefinition = { Bundle() }
typealias BundleDefinition = () -> Bundle
inline fun <reified T : ViewModel> Scope.viewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition? = null,
noinline owner: ViewModelOwnerDefinition,
noinline parameters: ParametersDefinition? = null
): Lazy<T> {
return lazy(LazyThreadSafetyMode.NONE) {
getViewModel<T>(qualifier, state, owner, parameters)
}
}
inline fun <reified T : ViewModel> Scope.getViewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition? = null,
noinline owner: ViewModelOwnerDefinition,
noinline parameters: ParametersDefinition? = null
): T {
return getViewModel(qualifier, state, owner, T::class, parameters)
}
fun <T : ViewModel> Scope.getViewModel(
qualifier: Qualifier? = null,
state: BundleDefinition? = null,
owner: ViewModelOwnerDefinition,
clazz: KClass<T>,
parameters: ParametersDefinition? = null
): T {
val ownerDef = owner()
return getViewModel(
ViewModelParameter(
clazz,
qualifier,
parameters,
state?.invoke() ?: Bundle(),
ownerDef.store,
ownerDef.stateRegistry
)
)
}
fun <T : ViewModel> Scope.getViewModel(viewModelParameters: ViewModelParameter<T>): T {
val viewModelProvider = createViewModelProvider(viewModelParameters)
return viewModelProvider.resolveInstance(viewModelParameters)
} | apache-2.0 | 7c58316d85933f6c7b8cf0e8562f0cc7 | 32.744186 | 87 | 0.741124 | 4.663987 | false | false | false | false |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/sample/ui/SampleCodeFragment.kt | 1 | 2526 | package io.noties.markwon.app.sample.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import io.noties.markwon.app.App
import io.noties.markwon.app.R
import io.noties.markwon.app.sample.Sample
import io.noties.markwon.app.utils.hidden
import io.noties.markwon.app.utils.readCode
import io.noties.markwon.syntax.Prism4jSyntaxHighlight
import io.noties.markwon.syntax.Prism4jThemeDefault
import io.noties.prism4j.Prism4j
import io.noties.prism4j.annotations.PrismBundle
@PrismBundle(include = ["java", "kotlin"], grammarLocatorClassName = ".GrammarLocatorSourceCode")
class SampleCodeFragment : Fragment() {
private lateinit var progressBar: View
private lateinit var textView: TextView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_sample_code, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressBar = view.findViewById(R.id.progress_bar)
textView = view.findViewById(R.id.text_view)
load()
}
private fun load() {
App.executorService.submit {
val code = sample.readCode(requireContext())
val prism = Prism4j(GrammarLocatorSourceCode())
val highlight = Prism4jSyntaxHighlight.create(prism, Prism4jThemeDefault.create(0))
val language = when (code.language) {
Sample.Language.KOTLIN -> "kotlin"
Sample.Language.JAVA -> "java"
}
val text = highlight.highlight(language, code.sourceCode)
textView.post {
//attached
if (context != null) {
progressBar.hidden = true
textView.text = text
}
}
}
}
private val sample: Sample by lazy(LazyThreadSafetyMode.NONE) {
val temp: Sample = (arguments!!.getParcelable(ARG_SAMPLE))!!
temp
}
companion object {
private const val ARG_SAMPLE = "arg.Sample"
fun init(sample: Sample): SampleCodeFragment {
return SampleCodeFragment().apply {
arguments = Bundle().apply {
putParcelable(ARG_SAMPLE, sample)
}
}
}
}
} | apache-2.0 | 6b97056882676308a5de2d812bc60556 | 32.693333 | 116 | 0.655186 | 4.486679 | false | false | false | false |
http4k/http4k | http4k-format/xml/src/main/kotlin/org/http4k/format/Xml.kt | 1 | 2314 | package org.http4k.format
import com.google.gson.JsonElement
import org.http4k.asByteBuffer
import org.http4k.asString
import org.http4k.core.Body
import org.http4k.core.ContentType.Companion.APPLICATION_XML
import org.http4k.lens.BiDiBodyLensSpec
import org.http4k.lens.BiDiLensSpec
import org.http4k.lens.ContentNegotiation
import org.http4k.lens.Meta
import org.http4k.lens.ParamMeta
import org.http4k.lens.httpBodyRoot
import org.json.XML
import org.w3c.dom.Document
import java.io.InputStream
import java.io.StringWriter
import java.nio.ByteBuffer
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import kotlin.reflect.KClass
object Xml : AutoMarshallingXml() {
override fun Any.asXmlString(): String = throw UnsupportedOperationException("")
override fun <T : Any> asA(input: String, target: KClass<T>): T = Gson.asA(input.asXmlToJsonElement(), target)
override fun <T : Any> asA(input: InputStream, target: KClass<T>): T = Gson.asA(input.reader().readText().asXmlToJsonElement(), target)
fun String.asXmlToJsonElement(): JsonElement = Gson.parse(XML.toJSONObject(this, true).toString())
@JvmName("stringAsXmlToJsonElement")
fun asXmlToJsonElement(input: String): JsonElement = input.asXmlToJsonElement()
fun String.asXmlDocument(): Document =
DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(byteInputStream())
fun Document.asXmlString(): String = StringWriter().let {
TransformerFactory.newInstance().newTransformer().transform(DOMSource(this), StreamResult(it))
it.toString()
}
fun <IN : Any> BiDiLensSpec<IN, String>.xml() = map({ it.asXmlDocument() }, { it.asXmlString() })
fun Body.Companion.xml(description: String? = null,
contentNegotiation: ContentNegotiation = ContentNegotiation.None): BiDiBodyLensSpec<Document> =
httpBodyRoot(listOf(Meta(true, "body", ParamMeta.ObjectParam, "body", description)), APPLICATION_XML, contentNegotiation)
.map(Body::payload) { Body(it) }
.map(ByteBuffer::asString, String::asByteBuffer).map({ it.asXmlDocument() }, { it.asXmlString() })
}
| apache-2.0 | 3b890f80873f93936d04fbe668a3ea27 | 40.321429 | 139 | 0.736819 | 4.066784 | false | false | false | false |
pdvrieze/ProcessManager | PMEditor/src/main/java/nl/adaptivity/android/util/MasterListFragment.kt | 1 | 5675 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.android.util
import android.app.Activity
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import nl.adaptivity.android.recyclerview.SelectableAdapter
import nl.adaptivity.process.ui.ProcessSyncManager
import nl.adaptivity.sync.SyncManager
open class MasterListFragment<M : SyncManager> : RecyclerFragment() {
/**
* A dummy implementation of the [ListCallbacks] interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
val sDummyCallbacks = object : ListCallbacks<ProcessSyncManager> {
internal var context = [email protected]?.applicationContext
override val isTwoPane: Boolean
get() = false
override val syncManager: ProcessSyncManager?
get() = ProcessSyncManager(context, null)
override fun onItemClicked(row: Int, id: Long): Boolean {/*dummy, not processed*/
return false
}
override fun onItemSelected(row: Int, id: Long) {/*dummy*/
}
}
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private var mCallbacks: ListCallbacks<M> = sDummyCallbacks as ListCallbacks<M>
protected val callbacks: ListCallbacks<M>
get() {
if (mCallbacks === sDummyCallbacks) {
var parent = parentFragment
while (parent != null) {
if (parent is ListCallbacks<*>) {
mCallbacks = parent as ListCallbacks<M>
return mCallbacks
}
parent = parent.parentFragment
}
}
return mCallbacks
}
init {
Log.i(MasterListFragment::class.java.simpleName, "Creating a new instanceo of " + javaClass.simpleName)
}
interface ListCallbacks<M : SyncManager> {
val isTwoPane: Boolean
val syncManager: M?
/** Initiate a click. When this returns true, further ignore the event (don't select) */
fun onItemClicked(row: Int, id: Long): Boolean
fun onItemSelected(row: Int, id: Long)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
callbacks
}
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
if (mCallbacks === sDummyCallbacks) {
if (getActivity() is ListCallbacks<*>) {
mCallbacks = getActivity() as ListCallbacks<M>
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Restore the previously serialized activated item position.
if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_ID)) {
setActivatedId(savedInstanceState.getLong(STATE_ACTIVATED_ID))
} else {
val arguments = arguments
if (arguments != null && arguments.containsKey(MasterDetailOuterFragment.ARG_ITEM_ID)) {
setActivatedId(arguments.getLong(MasterDetailOuterFragment.ARG_ITEM_ID))
}
}
}
override fun onDetach() {
super.onDetach()
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks as ListCallbacks<M>
}
protected fun doOnItemClicked(position: Int, nodeId: Long): Boolean {
return callbacks.onItemClicked(position, nodeId)
}
protected fun doOnItemSelected(position: Int, nodeId: Long) {
callbacks.onItemSelected(position, nodeId)
}
protected fun setActivatedId(id: Long) {
val vh = recyclerView!!.findViewHolderForItemId(id)
val adapter = listAdapter
if (adapter is SelectableAdapter<*>) {
val selectableAdapter = adapter as SelectableAdapter<*>
if (vh != null) {
selectableAdapter.setSelectedItem(vh.adapterPosition.toLong())
} else {
selectableAdapter.setSelectedItem(id)
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val adapter = listAdapter
if (adapter is SelectableAdapter<*>) {
val selectableAdapter = adapter as SelectableAdapter<*>
if (selectableAdapter.selectedId != RecyclerView.NO_ID) {
// Serialize and persist the activated item position.
outState.putLong(STATE_ACTIVATED_ID, selectableAdapter.selectedId)
}
}
}
companion object {
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
val STATE_ACTIVATED_ID = "activated_id"
}
}
| lgpl-3.0 | ed1e30eba6b5968165320c23c61c0daf | 33.603659 | 112 | 0.643524 | 5.126468 | false | false | false | false |
pdvrieze/ProcessManager | PE-diagram/src/commonMain/kotlin/nl.adaptivity.process/diagram/ProcessThemeItems.kt | 1 | 5687 | /*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.diagram
import net.devrieze.util.hasFlag
import nl.adaptivity.diagram.Drawable.Companion.STATE_CUSTOM1
import nl.adaptivity.diagram.Drawable.Companion.STATE_CUSTOM2
import nl.adaptivity.diagram.Drawable.Companion.STATE_CUSTOM3
import nl.adaptivity.diagram.Drawable.Companion.STATE_CUSTOM4
import nl.adaptivity.diagram.Drawable.Companion.STATE_DEFAULT
import nl.adaptivity.diagram.Drawable.Companion.STATE_SELECTED
import nl.adaptivity.diagram.Drawable.Companion.STATE_TOUCHED
import nl.adaptivity.diagram.DrawingStrategy
import nl.adaptivity.diagram.Pen
import nl.adaptivity.diagram.ThemeItem
enum class ProcessThemeItems(
private var fill: Boolean = false,
private var parent: ProcessThemeItems? = null,
private var stroke: Double = 0.0,
private var fontSize: Double = Double.NaN,
vararg private var specifiers: StateSpecifier) : ThemeItem {
LINE(RootDrawableProcessModel.STROKEWIDTH, state(STATE_DEFAULT, 0, 0, 0),
stateStroke(STATE_SELECTED, 0, 0, 255, 255, 2.0),
stateStroke(STATE_TOUCHED, 255, 255, 0, 127, 7.0),
state(STATE_CUSTOM1, 0, 0, 255),
state(STATE_CUSTOM2, 255, 255, 0),
state(STATE_CUSTOM3, 255, 0, 0),
state(STATE_CUSTOM4, 0, 255, 0)) {
override fun getEffectiveState(state: Int): Int {
if (state hasFlag STATE_TOUCHED) return STATE_TOUCHED
return effectiveStateHelper(state).ifInvalid(super.getEffectiveState(state))
}
},
INNERLINE(RootDrawableProcessModel.STROKEWIDTH * 0.85, state(STATE_DEFAULT, 0, 0, 0x20, 0xb0)),
BACKGROUND(state(STATE_DEFAULT, 255, 255, 255)) {
override fun getEffectiveState(state: Int) = STATE_DEFAULT
},
ENDNODEOUTERLINE(RootDrawableProcessModel.ENDNODEOUTERSTROKEWIDTH, LINE),
LINEBG(LINE),
DIAGRAMTEXT(RootDrawableProcessModel.STROKEWIDTH, RootDrawableProcessModel.DIAGRAMTEXT_SIZE,
state(STATE_DEFAULT, 0, 0, 0)),
DIAGRAMLABEL(RootDrawableProcessModel.STROKEWIDTH, RootDrawableProcessModel.DIAGRAMLABEL_SIZE,
state(STATE_DEFAULT, 0, 0, 0));
constructor(stroke: Double, parent: ProcessThemeItems) : this(false, parent = parent, stroke = stroke)
constructor(parent: ProcessThemeItems) : this(fill = true, parent = parent)
constructor(stroke: Double, vararg specifiers: StateSpecifier) : this(fill=false, stroke = stroke, specifiers = *specifiers)
constructor(stroke: Double, fontSize: Double, vararg specifiers: StateSpecifier) :
this(fill = true, stroke = stroke, fontSize = fontSize, specifiers = *specifiers)
constructor(vararg specifiers: StateSpecifier) : this(fill = true, specifiers = *specifiers)
override val itemNo: Int get() = ordinal
override fun getEffectiveState(state: Int): Int {
parent?.let { return it.getEffectiveState(state) }
return effectiveStateHelper(state).ifInvalid(state)
}
internal fun effectiveStateHelper(state: Int): Int {
return when {
state hasFlag STATE_CUSTOM1 -> STATE_CUSTOM1
state hasFlag STATE_CUSTOM2 -> STATE_CUSTOM2
state hasFlag STATE_CUSTOM3 -> STATE_CUSTOM3
state hasFlag STATE_CUSTOM4 -> STATE_CUSTOM4
else -> -1
}
}
override fun <PEN_T : Pen<PEN_T>> createPen(strategy: DrawingStrategy<*, PEN_T, *>, state: Int): PEN_T {
val specifier = getSpecifier(state)
val result = with(specifier) { strategy.newPen().setColor(red, green, blue, alpha) }
if (!fill) {
val stroke = when {
stroke > 0.0 -> stroke
else -> parent?.stroke ?: stroke
}
result.setStrokeWidth(stroke * specifier.strokeMultiplier)
}
if (fontSize.isFinite()) result.setFontSize(fontSize)
return result
}
private fun getSpecifier(state: Int): StateSpecifier {
parent?.apply { return getSpecifier(state) }
specifiers.firstOrNull { it.state == state }?.let { return it }
return specifiers.reduce { a, b ->
when {
b.state hasFlag state && b.state > a.state -> b
else -> a
}
}
}
}
private open class StateSpecifier(val state: Int, val red: Int, val green: Int, val blue: Int, val alpha: Int) {
open val strokeMultiplier: Double get() = 1.0
}
private class StrokeStateSpecifier(state: Int, r: Int, g: Int, b: Int, a: Int, override val strokeMultiplier: Double) :
StateSpecifier(state, r, g, b, a)
@Suppress("NOTHING_TO_INLINE")
private inline fun stateStroke(state: Int, r: Int, g: Int, b: Int, a: Int, strokeMultiplier: Double)
= StrokeStateSpecifier(state, r, g, b, a, strokeMultiplier)
@Suppress("NOTHING_TO_INLINE")
private inline fun state(state: Int, r: Int, g: Int, b: Int) = StateSpecifier(state, r, g, b, 255)
// This method can be useful when colors with alpha are desired.
@Suppress("NOTHING_TO_INLINE")
private inline fun state(state: Int, r: Int, g: Int, b: Int, a: Int) = StateSpecifier(state, r, g, b, a)
@Suppress("NOTHING_TO_INLINE")
private inline fun Int.ifInvalid(alternate:Int): Int = if (this >= 0) this else alternate | lgpl-3.0 | a0d23cefd30fc2cd104266c131537a38 | 35.935065 | 126 | 0.711975 | 3.913971 | false | false | false | false |
cfig/Nexus_boot_image_editor | bbootimg/src/main/kotlin/bootimg/cpio/NewAsciiCpio.kt | 1 | 4031 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfig.bootimg.cpio
import cfig.io.Struct3
import org.apache.commons.compress.archivers.cpio.CpioConstants
/*
cpio "New ASCII Format" with 070701 as magic
*/
class NewAsciiCpio(
var c_magic: String = "070701", //start-of-header
var c_ino: Long = 0,//var
var c_mode: Long = 0,//var
var c_uid: Int = 0,
var c_gid: Int = 0,
var c_nlink: Int = 1,
var c_mtime: Long = 0,
var c_filesize: Int = 0,//var
var c_devmajor: Int = 0,
var c_devminor: Int = 0,
var c_rdevmajor: Int = 0,
var c_rdevminor: Int = 0, //end-of-header
var c_namesize: Int = 0, //c_string name with '\0', aka. name_len + 1
var c_check: Int = 0
) {
init {
if (SIZE != Struct3(FORMAT_STRING).calcSize()) {
throw RuntimeException()
}
}
fun encode(): ByteArray {
return Struct3(FORMAT_STRING).pack(
String.format("%s", c_magic),
String.format("%08x", c_ino),
String.format("%08x", c_mode),
String.format("%08x", c_uid),
String.format("%08x", c_gid),
String.format("%08x", c_nlink),
String.format("%08x", c_mtime),
String.format("%08x", c_filesize),
String.format("%08x", c_devmajor),
String.format("%08x", c_devminor),
String.format("%08x", c_rdevmajor),
String.format("%08x", c_rdevminor),
String.format("%08x", c_namesize),
String.format("%08x", c_check),
)
}
private fun fileType(): Long {
return c_mode and CpioConstants.S_IFMT.toLong()
}
fun isRegularFile(): Boolean {
return fileType() == CpioConstants.C_ISREG.toLong()
}
fun isDirectory(): Boolean {
return fileType() == CpioConstants.C_ISDIR.toLong()
}
fun isSymbolicLink(): Boolean {
return fileType() == CpioConstants.C_ISLNK.toLong()
}
companion object {
const val SIZE = 110
const val FORMAT_STRING = "6s8s8s8s8s8s8s8s8s8s8s8s8s8s" //6 + 8 *13
}
}
/* <bits/stat.h>
/* File types. */
#define __S_IFDIR 0040000 /* Directory. */
#define __S_IFCHR 0020000 /* Character device. */
#define __S_IFBLK 0060000 /* Block device. */
#define __S_IFREG 0100000 /* Regular file. */
#define __S_IFIFO 0010000 /* FIFO. */
#define __S_IFLNK 0120000 /* Symbolic link. */
#define __S_IFSOCK 0140000 /* Socket. */
/* Protection bits. */
#define __S_ISUID 04000 /* Set user ID on execution. */
#define __S_ISGID 02000 /* Set group ID on execution. */
#define __S_ISVTX 01000 /* Save swapped text after use (sticky). */
#define __S_IREAD 0400 /* Read by owner. */
#define __S_IWRITE 0200 /* Write by owner. */
#define __S_IEXEC 0100 /* Execute by owner. */
/* Read, write, and execute by owner. */
#define S_IRWXU (__S_IREAD|__S_IWRITE|__S_IEXEC)
#define S_IRGRP (S_IRUSR >> 3) /* Read by group. */
#define S_IWGRP (S_IWUSR >> 3) /* Write by group. */
#define S_IXGRP (S_IXUSR >> 3) /* Execute by group. */
Read, write, and execute by group.
#define S_IRWXG (S_IRWXU >> 3)
#define S_IROTH (S_IRGRP >> 3) /* Read by others. */
#define S_IWOTH (S_IWGRP >> 3) /* Write by others. */
#define S_IXOTH (S_IXGRP >> 3) /* Execute by others. */
Read, write, and execute by others.
#define S_IRWXO (S_IRWXG >> 3)
# define ACCESSPERMS (S_IRWXU|S_IRWXG|S_IRWXO) 0777
*/
| apache-2.0 | 5fe22516141a5eb32a548f79b3d5c99b | 32.591667 | 76 | 0.599603 | 3.122386 | false | false | false | false |
jamieadkins95/Roach | data/src/main/java/com/jamieadkins/gwent/data/update/repository/NoticesRepositoryImpl.kt | 1 | 1681 | package com.jamieadkins.gwent.data.update.repository
import com.google.firebase.firestore.FirebaseFirestore
import com.google.gson.reflect.TypeToken
import com.jamieadkins.gwent.data.update.model.FirebaseNotice
import com.jamieadkins.gwent.domain.update.model.Notice
import com.jamieadkins.gwent.domain.update.repository.NoticesRepository
import io.reactivex.Observable
import timber.log.Timber
import javax.inject.Inject
class NoticesRepositoryImpl @Inject constructor(private val firestore: FirebaseFirestore) : NoticesRepository {
override fun getNotices(): Observable<List<Notice>> {
return Observable.create<List<Notice>> { emitter ->
val noticesRef = firestore.collection("notices")
.document("en")
.collection("notices")
val listener = noticesRef.addSnapshotListener { snapshot, e ->
if (e != null) {
emitter.onError(e)
}
val notices = snapshot?.documents?.mapNotNull { doc ->
val data = doc.toObject(FirebaseNotice::class.java)
data?.let {
Notice(
it.id,
it.title,
it.body,
it.enabled
)
}
}
emitter.onNext(notices ?: emptyList())
}
emitter.setCancellable { listener.remove() }
}
.doOnError { Timber.e(it) }
.onErrorReturnItem(emptyList())
}
inline fun <reified T> genericType() = object : TypeToken<T>() {}.type
} | apache-2.0 | 8eeb7fe35dbffab0fbd64a0cd84e4737 | 34.787234 | 111 | 0.568709 | 5.172308 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/reporter/EffectiveActionsMF.kt | 1 | 4742 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.reporter
import kotlinx.coroutines.CoroutineName
import org.droidmate.deviceInterface.exploration.isClick
import org.droidmate.exploration.ExplorationContext
import org.droidmate.exploration.modelFeatures.ModelFeature
import org.droidmate.explorationModel.interaction.Interaction
import org.droidmate.explorationModel.interaction.State
import org.droidmate.explorationModel.interaction.Widget
import org.droidmate.misc.withExtension
import org.droidmate.exploration.modelFeatures.misc.plot
import java.nio.file.Files
import java.nio.file.Path
import java.time.temporal.ChronoUnit
import java.util.*
import kotlin.coroutines.CoroutineContext
class EffectiveActionsMF(private val includePlots: Boolean = true) : ModelFeature() {
override val coroutineContext: CoroutineContext = CoroutineName("EffectiveActionsMF")
/**
* Keep track of effective actions during exploration
* This is not used to dump the report at the end
*/
private var totalActions = 0
private var effectiveActions = 0
override suspend fun onNewInteracted(traceId: UUID, targetWidgets: List<Widget>, prevState: State<*>, newState: State<*>) {
totalActions++
if (prevState != newState)
effectiveActions++
}
fun getTotalActions(): Int {
return totalActions
}
fun getEffectiveActions(): Int {
return effectiveActions
}
override suspend fun onAppExplorationFinished(context: ExplorationContext<*, *, *>) {
val sb = StringBuilder()
val header = "Time_Seconds\tTotal_Actions\tTotal_Effective\n"
sb.append(header)
val reportData: HashMap<Long, Pair<Int, Int>> = HashMap()
// Ignore app start
val records = context.explorationTrace.P_getActions().drop(1)
val nrActions = records.size
val startTimeStamp = records.first().startTimestamp
var totalActions = 1
var effectiveActions = 1
for (i in 1 until nrActions) {
val prevAction = records[i - 1]
val currAction = records[i]
val currTimestamp = currAction.startTimestamp
val currTimeDiff = ChronoUnit.SECONDS.between(startTimeStamp, currTimestamp)
if (actionWasEffective(prevAction, currAction))
effectiveActions++
totalActions++
reportData[currTimeDiff] = Pair(totalActions, effectiveActions)
if (i % 100 == 0)
log.info("Processing $i")
}
reportData.keys.sorted().forEach { key ->
val value = reportData[key]!!
sb.appendln("$key\t${value.first}\t${value.second}")
}
val reportFile = context.model.config.baseDir.resolve("effective_actions.txt")
Files.write(reportFile, sb.toString().toByteArray())
if (includePlots) {
log.info("Writing out plot $")
this.writeOutPlot(reportFile, context.model.config.baseDir)
}
}
// Currently used in child projects
@Suppress("MemberVisibilityCanBePrivate")
fun actionWasEffective(prevAction: Interaction<*>, currAction: Interaction<*>): Boolean {
return if ((!prevAction.actionType.isClick()) ||
(! currAction.actionType.isClick()))
true
else {
currAction.prevState != currAction.resState
}
}
private fun writeOutPlot(dataFile: Path, resourceDir: Path) {
val fileName = dataFile.fileName.withExtension("pdf")
val outFile = dataFile.resolveSibling(fileName)
plot(dataFile.toAbsolutePath().toString(), outFile.toAbsolutePath().toString(), resourceDir)
}
} | gpl-3.0 | f6154318bc093f3def13a278751e889d | 34.661654 | 127 | 0.690848 | 4.737263 | false | false | false | false |
viniciussoares/ribot-android-boilerplate-kotlin | app/src/main/kotlin/uk/co/ribot/androidboilerplate/util/extension/CursorExtension.kt | 1 | 798 | package uk.co.ribot.androidboilerplate.util.extension
import android.database.Cursor
fun Cursor.getString(columnName: String, defaultValue: String = ""): String {
val index = getColumnIndex(columnName)
return getString(index) ?: defaultValue
}
fun Cursor.getInt(columnName: String, defaultValue: Int = 0): Int {
val index = getColumnIndex(columnName)
return if (index >= 0) getInt(index) else defaultValue
}
fun Cursor.getLong(columnName: String, defaultValue: Long = 0): Long {
val index = getColumnIndex(columnName)
return if (index >= 0) getLong(index) else defaultValue
}
fun Cursor.getBoolean(columnName: String, defaultValue: Boolean = false): Boolean {
val index = getColumnIndex(columnName)
return if (index >= 0) getInt(index) == 1 else defaultValue
}
| apache-2.0 | e7f8ffd70b0a4a0955420fcb8ad36686 | 33.695652 | 83 | 0.734336 | 4.244681 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/SimpleDragHelper.kt | 1 | 2621 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.gui
import javafx.scene.Node
import javafx.scene.input.*
open class SimpleDragHelper<T>(
val dataFormat: DataFormat,
allowCopy: Boolean = true,
allowMove: Boolean = true,
allowLink: Boolean = true,
val onMoved: ((T) -> Unit)? = null,
val obj: () -> (T))
: DragHelper {
val modes = modes(allowCopy, allowMove, allowLink)
override fun applyTo(node: Node) {
node.setOnDragDetected { onDragDetected(it) }
node.setOnDragDone { onDone(it) }
}
fun addContentToClipboard(clipboard: ClipboardContent): Boolean {
obj()?.let {
clipboard.put(dataFormat, it)
return true
}
return false
}
open fun onDragDetected(event: MouseEvent) {
val dragboard = event.pickResult.intersectedNode.startDragAndDrop(* modes)
val clipboard = ClipboardContent()
if (addContentToClipboard(clipboard)) {
dragboard.setContent(clipboard)
}
event.consume()
}
open fun onDone(event: DragEvent) {
val content = content(event)
if (content != null && event.transferMode == TransferMode.MOVE) {
onMoved?.let {
it(content)
}
}
event.consume()
}
fun content(event: DragEvent): T? {
@Suppress("UNCHECKED_CAST")
return event.dragboard.getContent(dataFormat) as T
}
companion object {
fun modes(allowCopy: Boolean, allowMove: Boolean, allowLink: Boolean): Array<TransferMode> {
val set = mutableSetOf<TransferMode>()
if (allowCopy) {
set.add(TransferMode.COPY)
}
if (allowMove) {
set.add(TransferMode.MOVE)
}
if (allowLink) {
set.add(TransferMode.LINK)
}
return set.toTypedArray()
}
}
}
| gpl-3.0 | 76d36031c4feeec6c11472090a335a78 | 27.802198 | 100 | 0.621519 | 4.427365 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-elastic/src/main/java/net/nemerosa/ontrack/extension/elastic/metrics/ElasticMetricsConfigProperties.kt | 1 | 2619 | package net.nemerosa.ontrack.extension.elastic.metrics
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.convert.DurationUnit
import org.springframework.stereotype.Component
import java.time.Duration
import java.time.temporal.ChronoUnit
@ConfigurationProperties(prefix = ElasticMetricsConfigProperties.ELASTIC_METRICS_PREFIX)
@Component
class ElasticMetricsConfigProperties {
companion object {
/**
* Prefix for the Elastic metrics configuration.
*/
const val ELASTIC_METRICS_PREFIX = "ontrack.extension.elastic.metrics"
}
/**
* Is the export of metrics to Elastic enabled?
*/
var enabled: Boolean = false
/**
* Must we trace the behaviour of the export of the metrics in the logs?
*/
var debug: Boolean = false
/**
* Defines where the Elastic metrics should be sent.
*/
var target: ElasticMetricsTarget = ElasticMetricsTarget.MAIN
/**
* Index properties
*/
var index = IndexConfigProperties()
/**
* Custom connection
*/
var custom = ElasticsearchProperties()
/**
* Set to true to enable the API Compatibility mode when accessing a 8.x ES server.
*
* See https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.17/java-rest-high-compatibility.html
*/
var apiCompatibilityMode: Boolean = false
/**
* Set to false to disable the possibility to clear the index in case of re-indexation
*/
var allowDrop: Boolean = true
/**
* Index properties
*/
class IndexConfigProperties {
/**
* Name of the index to contains all Ontrack metrics
*/
var name = "ontrack_metrics"
/**
* Flag to enable immediate re-indexation after items are added into the index (used mostly
* for testing).
*/
var immediate = false
}
/**
* Queue configuration
*/
var queue = QueueConfigProperties()
/**
* Queue configuration
*/
class QueueConfigProperties {
/**
* Maximum capacity for the queue
*/
var capacity: UInt = 1024U
/**
* Maximum buffer for the queue before flushing
*/
var buffer: UInt = 512U
/**
* Interval between the regular flushing of the queue of events
*/
@DurationUnit(ChronoUnit.MINUTES)
var flushing: Duration = Duration.ofMinutes(1)
}
}
| mit | f5d3f32f10621e8c8df0f12306478a88 | 24.427184 | 112 | 0.641084 | 4.913696 | false | true | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/timer_recordings/TimerRecordingDetailsFragment.kt | 1 | 5218 | package org.tvheadend.tvhclient.ui.features.dvr.timer_recordings
import android.os.Bundle
import android.view.*
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import org.tvheadend.data.entity.TimerRecording
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.databinding.TimerRecordingDetailsFragmentBinding
import org.tvheadend.tvhclient.ui.base.BaseFragment
import org.tvheadend.tvhclient.ui.common.*
import org.tvheadend.tvhclient.ui.common.interfaces.ClearSearchResultsOrPopBackStackInterface
import org.tvheadend.tvhclient.ui.common.interfaces.RecordingRemovedInterface
import org.tvheadend.tvhclient.util.extensions.gone
import org.tvheadend.tvhclient.util.extensions.visible
class TimerRecordingDetailsFragment : BaseFragment(), RecordingRemovedInterface, ClearSearchResultsOrPopBackStackInterface {
private lateinit var timerRecordingViewModel: TimerRecordingViewModel
private var recording: TimerRecording? = null
private lateinit var binding: TimerRecordingDetailsFragmentBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = DataBindingUtil.inflate(inflater, R.layout.timer_recording_details_fragment, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
timerRecordingViewModel = ViewModelProvider(requireActivity())[TimerRecordingViewModel::class.java]
if (!isDualPane) {
toolbarInterface.setTitle(getString(R.string.details))
toolbarInterface.setSubtitle("")
}
arguments?.let {
timerRecordingViewModel.currentIdLiveData.value = it.getString("id", "")
}
timerRecordingViewModel.recordingLiveData.observe(viewLifecycleOwner, {
recording = it
showRecordingDetails()
})
}
private fun showRecordingDetails() {
if (recording != null) {
binding.recording = recording
binding.htspVersion = htspVersion
binding.isDualPane = isDualPane
// The toolbar is hidden as a default to prevent pressing any icons if no recording
// has been loaded yet. The toolbar is shown here because a recording was loaded
binding.nestedToolbar.visible()
activity?.invalidateOptionsMenu()
} else {
binding.scrollview.gone()
binding.status.text = getString(R.string.error_loading_recording_details)
binding.status.visible()
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
val recording = this.recording ?: return
preparePopupOrToolbarSearchMenu(menu, recording.title, isConnectionToServerAvailable)
binding.nestedToolbar.menu.findItem(R.id.menu_edit_recording)?.isVisible = true
binding.nestedToolbar.menu.findItem(R.id.menu_remove_recording)?.isVisible = true
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.external_search_options_menu, menu)
binding.nestedToolbar.inflateMenu(R.menu.recording_details_toolbar_menu)
binding.nestedToolbar.setOnMenuItemClickListener { this.onOptionsItemSelected(it) }
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val ctx = context ?: return super.onOptionsItemSelected(item)
val recording = this.recording ?: return super.onOptionsItemSelected(item)
return when (item.itemId) {
R.id.menu_edit_recording -> editSelectedTimerRecording(requireActivity(), recording.id)
R.id.menu_remove_recording -> showConfirmationToRemoveSelectedTimerRecording(ctx, recording, this)
R.id.menu_search_imdb -> return searchTitleOnImdbWebsite(ctx, recording.title)
R.id.menu_search_fileaffinity -> return searchTitleOnFileAffinityWebsite(ctx, recording.title)
R.id.menu_search_youtube -> return searchTitleOnYoutube(ctx, recording.title)
R.id.menu_search_google -> return searchTitleOnGoogle(ctx, recording.title)
R.id.menu_search_epg -> return searchTitleInTheLocalDatabase(requireActivity(), baseViewModel, recording.title)
else -> super.onOptionsItemSelected(item)
}
}
override fun onRecordingRemoved() {
if (!isDualPane) {
activity?.onBackPressed()
} else {
val detailsFragment = activity?.supportFragmentManager?.findFragmentById(R.id.details)
if (detailsFragment != null) {
activity?.supportFragmentManager?.beginTransaction()?.also {
it.remove(detailsFragment)
it.commit()
}
}
}
}
companion object {
fun newInstance(id: String): TimerRecordingDetailsFragment {
val f = TimerRecordingDetailsFragment()
val args = Bundle()
args.putString("id", id)
f.arguments = args
return f
}
}
}
| gpl-3.0 | 741c50de1157db835d93f947ec2aae75 | 42.848739 | 124 | 0.699693 | 5.156126 | false | false | false | false |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/main/fragments/festival/adapter/FestivalViewHolder.kt | 1 | 1581 | /*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.view.main.fragments.festival.adapter
import android.support.v7.widget.RecyclerView
import android.view.View
import com.bumptech.glide.Glide
import com.pickth.gachi.util.OnFestivalClickListener
import kotlinx.android.synthetic.main.item_main_festival.view.*
class FestivalViewHolder(view: View, val listener: OnFestivalClickListener?): RecyclerView.ViewHolder(view) {
fun onBind(item: Festival, position: Int) {
with(itemView) {
if(item.imageUrl != "") Glide.with(itemView.context)
.load(item.imageUrl)
.into(iv_main_festival)
tv_main_festival_title.text = item.title
tv_main_festival_date.text = item.date
}
itemView.setOnClickListener {
if(item.type == "popular") {
listener?.onPopularFestivalClick(position)
} else {
listener?.onImmediateFestivalClick(position)
}
}
}
} | apache-2.0 | d4efbe8eb8cac5ce7b21c98ea064e6a3 | 35.790698 | 109 | 0.679949 | 4.127937 | false | false | false | false |
sinnerschrader/account-tool | src/main/kotlin/com/sinnerschrader/s2b/accounttool/presentation/validation/ChangeProfileFormValidator.kt | 1 | 6625 | package com.sinnerschrader.s2b.accounttool.presentation.validation
import com.sinnerschrader.s2b.accounttool.logic.component.security.PasswordAnalyzeService
import com.sinnerschrader.s2b.accounttool.logic.component.security.PwnedPasswordService
import com.sinnerschrader.s2b.accounttool.presentation.RequestUtils
import com.sinnerschrader.s2b.accounttool.presentation.controller.ProfileController
import com.sinnerschrader.s2b.accounttool.presentation.controller.ProfileController.Edit.*
import com.sinnerschrader.s2b.accounttool.presentation.model.ChangeProfile
import org.apache.commons.codec.binary.Base64
import org.apache.commons.lang3.StringUtils
import org.apache.sshd.common.util.buffer.ByteArrayBuffer
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.validation.Errors
import org.springframework.validation.ValidationUtils.rejectIfEmptyOrWhitespace
import org.springframework.validation.Validator
import java.security.interfaces.DSAPublicKey
import java.security.interfaces.ECPublicKey
import java.security.interfaces.RSAPublicKey
import javax.servlet.http.HttpServletRequest
@Component(value = "changeProfileFormValidator")
class ChangeProfileFormValidator : Validator {
@Autowired
private lateinit var passwordAnalyzeService: PasswordAnalyzeService
@Autowired
private lateinit var request: HttpServletRequest
override fun supports(clazz: Class<*>) =ChangeProfile::class.java.isAssignableFrom(clazz)
private fun validateAndSanitizeSSHKey(form: ChangeProfile, errors: Errors) {
val formAttribute = "publicKey"
rejectIfEmptyOrWhitespace(errors, "publicKey", "required")
if (errors.hasErrors()) return
var sanitizedKey = ""
val parts = StringUtils.split(form.publicKey, " ")
if (parts.size >= 2) {
try {
val base64Key = parts[1]
val binary = Base64.decodeBase64(base64Key)
val publicKey = ByteArrayBuffer(binary).rawPublicKey
if (StringUtils.equals(publicKey.algorithm, "EC")) {
val ecKey = publicKey as ECPublicKey
if (ecKey.params.order.bitLength() < 256) {
errors.rejectValue(formAttribute, "publicKey.ec.insecure",
"ec key with minimum of 256 bit required")
return
}
sanitizedKey = "ecdsa-sha2-nistp" + ecKey.params.order.bitLength() + " "
} else if (StringUtils.equals(publicKey.algorithm, "RSA")) {
val rsaPublicKey = publicKey as RSAPublicKey
if (rsaPublicKey.modulus.bitLength() < 2048) {
errors.rejectValue(formAttribute, "publicKey.rsa.insecure",
"rsa key with minimum of 2048 bit required")
return
}
sanitizedKey = "ssh-rsa "
} else if (StringUtils.equals(publicKey.algorithm, "DSA")) {
val dsaPublicKey = publicKey as DSAPublicKey
if (dsaPublicKey.params.p.bitLength() < 2048) {
errors.rejectValue(formAttribute, "publicKey.dsa.insecure",
"dsa key with minimum of 2048 bit required")
return
}
sanitizedKey = "ssh-dss "
}
val buffer = ByteArrayBuffer()
buffer.putRawPublicKey(publicKey)
sanitizedKey += Base64.encodeBase64String(buffer.compactData)
form.publicKey = sanitizedKey
} catch (e: Exception) {
val msg = "Could not parse public key"
errors.rejectValue(formAttribute, "publicKey.invalid",
"The defined public can't be parsed")
LOG.error(msg)
if (LOG.isDebugEnabled) {
LOG.error(msg, e)
}
}
} else {
errors.rejectValue(formAttribute, "publicKey.invalid", "The defined public can't be parsed")
}
}
private fun validatePassword(form: ChangeProfile, errors: Errors) {
rejectIfEmptyOrWhitespace(errors, "oldPassword", "required",
"Please enter your current password")
rejectIfEmptyOrWhitespace(errors, "password", "required",
"Please enter a password")
if (errors.hasErrors()) return
rejectIfEmptyOrWhitespace(errors, "passwordRepeat", "required",
"Please repeat the password")
if (form.password != form.passwordRepeat)
errors.reject("passwordRepeat", "Passwords don't match")
if (form.password.length < 10)
errors.reject("password", "The password required at least 10 characters")
if (errors.hasErrors()) return
val currentUser = RequestUtils.currentUserDetails!!
if (currentUser.password != form.oldPassword) {
errors.rejectValue("oldPassword", "password.previous.notMatch")
}
if (currentUser.password == form.password) {
errors.rejectValue("password", "password.noChange")
}
val result = passwordAnalyzeService.analyze(form.password, currentUser.uid, currentUser.username)
if (!result.isValid) {
val codes = result.errorCodes
if (codes.isEmpty()) {
// this is a fallback, if no message and no suggestions are provided
errors.rejectValue("password", "passwordValidation.general.error", "The password is too weak")
} else {
for (code in result.errorCodes) {
errors.rejectValue("password", code, "Your password violates a rule.")
}
}
} else if (PwnedPasswordService.isPwned(form.password)) {
errors.rejectValue("password", "passwordValidation.isPwned.error",
"The password has previously appeared in a security breach")
}
}
override fun validate(target: Any, errors: Errors) {
with(target as ChangeProfile){
when(edit){
SSH_KEY -> validateAndSanitizeSSHKey(this, errors)
PASSWORD -> validatePassword(this, errors)
else -> Unit
}
}
}
companion object {
private val LOG = LoggerFactory.getLogger(ChangeProfileFormValidator::class.java)
}
}
| mit | 60db45a1df3c129f64f19b074c5df6b2 | 44.068027 | 110 | 0.626415 | 5.053394 | false | false | false | false |
stoman/competitive-programming | problems/2021adventofcode14a/submissions/accepted/Stefan.kt | 2 | 898 | import java.util.*
@ExperimentalStdlibApi
fun main() {
val s = Scanner(System.`in`).useDelimiter("""\s->\s|\n\n|\n""")
val input = s.next()
var polymers = (0 until input.length - 1).map { input.slice(it..(it + 1)) }.groupBy { it }.mapValues { it.value.size }
val rules = buildMap<String, String> { while (s.hasNext()) { put(s.next(), s.next()) } }
repeat(10) {
val newPolymers = mutableMapOf<String, Int>()
for ((str, count) in polymers) {
val n = rules[str]!!
newPolymers[str[0] + n] = newPolymers.getOrDefault(str[0] + n, 0) + count
newPolymers[n + str[1]] = newPolymers.getOrDefault(n + str[1], 0) + count
}
polymers = newPolymers
}
val counts = mutableMapOf(input.last() to 1)
for ((str, count) in polymers) {
counts[str[0]] = counts.getOrDefault(str[0], 0) + count
}
println(counts.maxOf { it.value } - counts.minOf { it.value })
}
| mit | 2df706c3f7ddb0a62b48e9bd53c8ac09 | 34.92 | 120 | 0.613586 | 3.218638 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/pruefung/LengthValidator.kt | 1 | 4234 | /*
* Copyright (c) 2017-2022 by Oliver Boehm
*
* 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.
*
* (c)reated 21.02.2017 by oboehm ([email protected])
*/
package de.jfachwert.pruefung
import de.jfachwert.PruefzifferVerfahren
import de.jfachwert.pruefung.exception.InvalidLengthException
import de.jfachwert.pruefung.exception.LocalizedIllegalArgumentException
import java.io.Serializable
import java.util.*
/**
* Bei der Laengen-Validierung wird nur die Laenge des Fachwertes geprueft, ob
* er zwischen der erlaubten Minimal- und Maximallaenge liegt. Ist die
* Minimallaenge 0, sind leere Werte erlaubt, ist die Maximallaenge unendlich
* (bzw. groesster Integer-Wert), gibt es keine Laengenbeschraenkung.
*
* Urspruenglich besass diese Klasse rein statisiche Methoden fuer die
* Laengenvaliderung. Ab v0.3.1 kann sie auch anstelle eines
* Pruefziffernverfahrens eingesetzt werden.
*
* @author oboehm
* @since 0.2 (20.04.2017)
*/
open class LengthValidator<T : Serializable> @JvmOverloads constructor(private val min: Int, private val max: Int = Int.MAX_VALUE) : NoopVerfahren<T>() {
/**
* Liefert true zurueck, wenn der uebergebene Wert innerhalb der erlaubten
* Laenge liegt.
*
* @param wert Fachwert oder gekapselter Wert
* @return true oder false
*/
override fun isValid(wert: T): Boolean {
val length = Objects.toString(wert, "").length
return length >= min && length <= max
}
/**
* Ueberprueft, ob der uebergebenen Werte innerhalb der min/max-Werte
* liegt.
*
* @param wert zu ueberpruefender Wert
* @return den ueberprueften Wert (zur Weiterverarbeitung)
*/
override fun validate(wert: T): T {
if (!isValid(wert)) {
throw InvalidLengthException(Objects.toString(wert), min, max)
}
return wert
}
companion object {
val NOT_EMPTY_VALIDATOR: PruefzifferVerfahren<String> = LengthValidator(1)
/**
* Validiert die Laenge des uebergebenen Wertes.
*
* @param value zu pruefender Wert
* @param expected erwartete Laenge
* @return der gepruefte Wert (zur evtl. Weiterverarbeitung)
*/
fun validate(value: String, expected: Int): String {
if (value.length != expected) {
throw InvalidLengthException(value, expected)
}
return value
}
/**
* Validiert die Laenge des uebergebenen Wertes.
*
* @param value zu pruefender Wert
* @param min geforderte Minimal-Laenge
* @param max Maximal-Laenge
* @return der gepruefte Wert (zur evtl. Weiterverarbeitung)
*/
fun validate(value: String, min: Int, max: Int): String {
if (min == max) {
return validate(value, min)
}
if (value.length < min || value.length > max) {
throw InvalidLengthException(value, min, max)
}
return value
}
/**
* Verifziert die Laenge des uebergebenen Wertes. Im Gegensatz zur
* [.validate]-Methode wird herbei eine
* [IllegalArgumentException] geworfen.
*
* @param value zu pruefender Wert
* @param min geforderte Minimal-Laenge
* @param max Maximal-Laenge
* @return der gepruefte Wert (zur evtl. Weiterverarbeitung)
*/
fun verify(value: String, min: Int, max: Int): String {
return try {
validate(value, min, max)
} catch (ex: IllegalArgumentException) {
throw LocalizedIllegalArgumentException(ex)
}
}
}
} | apache-2.0 | 4b950bf25b2fa8e881359fa4e9ac9254 | 32.88 | 153 | 0.636986 | 3.960711 | false | false | false | false |
Orchextra/orchextra-android-sdk | core/src/main/java/com/gigigo/orchextra/core/data/datasources/network/models/ApiOxDevice.kt | 1 | 1528 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.data.datasources.network.models
class ApiOxDevice(
val instanceId: String,
val secureId: String? = null,
val serialNumber: String? = null,
val bluetoothMacAddress: String? = null,
val wifiMacAddress: String? = null,
val clientApp: ApiClientApp? = null,
val notificationPush: ApiNotificationPush? = null,
val device: ApiDeviceInfo? = null,
val tags: List<String>? = null,
val businessUnits: List<String>? = null)
class ApiDeviceInfo(
val timeZone: String?,
val osVersion: String?,
val language: String?,
val handset: String?,
val type: String?)
class ApiClientApp(
val bundleId: String,
val buildVersion: String,
val appVersion: String,
val sdkVersion: String,
val sdkDevice: String)
class ApiNotificationPush(
val senderId: String = "DEPRECATED",
val token: String) | apache-2.0 | cdbcdacb6c4448abea9edc7717ac1a2e | 30.204082 | 75 | 0.712696 | 4.085561 | false | false | false | false |
255BITS/hypr | app/src/main/java/hypr/hypergan/com/hypr/ModelFragmnt/InlineImage.kt | 1 | 1725 | package hypr.hypergan.com.hypr.ModelFragmnt
import android.graphics.*
import hypr.hypergan.com.hypr.Util.scaleBitmap
class InlineImage{
var widthRatio: Float = 0.0f
var heightRatio: Float = 0.0f
var isOldCoppedImageBigger = false
val paint = Paint()
init{
paint.style = Paint.Style.STROKE
paint.color = Color.RED
}
fun setBeforeAfterCropSizingRatio(oldCroppedImage: Bitmap, newCroppedImage: Bitmap){
if(oldCroppedImage.byteCount < newCroppedImage.byteCount){
isOldCoppedImageBigger = true
widthRatio = newCroppedImage.width.toFloat() / oldCroppedImage.width.toFloat()
heightRatio = newCroppedImage.height.toFloat() / oldCroppedImage.height.toFloat()
}else{
widthRatio = oldCroppedImage.width.toFloat() / newCroppedImage.width.toFloat()
heightRatio = oldCroppedImage.height.toFloat() / newCroppedImage.height.toFloat()
}
}
fun inlineCroppedImageToFullImage(croppedImage: Bitmap, fullImage: Bitmap, croppedPoint: Rect): Bitmap {
val mutableFullImage = fullImage.copy(Bitmap.Config.ARGB_8888, true)
val scaledCroppedImage = croppedImage.scaleBitmap(croppedPoint.width(), croppedPoint.height())
insertCroppedImageWithinFullImage(mutableFullImage, scaledCroppedImage, croppedPoint)
return mutableFullImage
}
private fun insertCroppedImageWithinFullImage(fullImageMutable: Bitmap, scaledCropped: Bitmap, croppedPoint: Rect): Bitmap {
val fullImageCanvas = Canvas(fullImageMutable)
fullImageCanvas.drawBitmap(scaledCropped, croppedPoint.left.toFloat(), croppedPoint.top.toFloat(), Paint())
return fullImageMutable
}
} | mit | 54f569a4caa57b9829c8817205882fbf | 37.355556 | 128 | 0.721159 | 4.726027 | false | false | false | false |
akinaru/bbox-api-client | sample/src/main/kotlin/fr/bmartel/bboxapi/router/sample/WifiMacFilter.kt | 2 | 5057 | package fr.bmartel.bboxapi.router.sample
import com.github.kittinunf.result.Result
import fr.bmartel.bboxapi.router.BboxApiRouter
import fr.bmartel.bboxapi.router.model.MacFilterRule
import java.util.concurrent.CountDownLatch
fun main(args: Array<String>) {
val bboxapi = BboxApiRouter()
bboxapi.init()
bboxapi.password = "admin"
/**
* Get wifi mac filter
*/
//asynchronous call
var latch = CountDownLatch(1)
bboxapi.getWifiMacFilter { _, _, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
val data = result.get()
println(data)
}
}
latch.countDown()
}
latch.await()
//synchronous call
val (_, _, wifiMacFilter) = bboxapi.getWifiMacFilterSync()
when (wifiMacFilter) {
is Result.Failure -> {
val ex = wifiMacFilter.getException()
println(ex)
}
is Result.Success -> {
val data = wifiMacFilter.get()
println(data)
}
}
/**
* enable/disable wifi mac filter
*/
//asynchronous call
latch = CountDownLatch(1)
bboxapi.setWifiMacFilter(state = false) { _, res, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
println("wifi mac filter enabled ${res.statusCode}")
}
}
latch.countDown()
}
latch.await()
//synchronous call
val (_, res, stateResult) = bboxapi.setWifiMacFilterSync(state = false)
when (stateResult) {
is Result.Failure -> {
val ex = stateResult.getException()
println(ex)
}
is Result.Success -> {
println("wifi mac filter enabled ${res.statusCode}")
}
}
/**
* delete wifi mac filter rules
*/
deleteAllRules(bboxapi = bboxapi, size = wifiMacFilter.get()[0].acl?.rules?.size ?: 0)
showNewSize(bboxapi = bboxapi)
/**
* create wifi mac filter rule
*/
//asynchronous call
val rule1 = MacFilterRule(enable = true, macaddress = "01:23:45:67:89:01", ip = "")
latch = CountDownLatch(1)
bboxapi.createMacFilterRule(rule = rule1) { _, res, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
println("create rule 1 ${res.statusCode}")
}
}
latch.countDown()
}
latch.await()
//synchronous call
val rule2 = MacFilterRule(enable = true, macaddress = "34:56:78:90:12:34", ip = "")
val (_, res2, createResult) = bboxapi.createMacFilterRuleSync(rule = rule2)
when (createResult) {
is Result.Failure -> {
val ex = createResult.getException()
println(ex)
}
is Result.Success -> {
println("create rule 2 ${res2.statusCode}")
}
}
showNewSize(bboxapi = bboxapi)
/**
* update rule
*/
//asynchronous call
latch = CountDownLatch(1)
bboxapi.updateMacFilterRule(ruleIndex = 1, rule = rule2) { _, res, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
println("updated rule 1 ${res.statusCode}")
}
}
latch.countDown()
}
latch.await()
//synchronous call
val (_, res3, updateResult) = bboxapi.updateMacFilterRuleSync(ruleIndex = 2, rule = rule1)
when (updateResult) {
is Result.Failure -> {
val ex = updateResult.getException()
println(ex)
}
is Result.Success -> {
println("updated rule 2 ${res3.statusCode}")
}
}
showNewSize(bboxapi = bboxapi)
deleteAllRules(bboxapi = bboxapi, size = 2)
}
fun showNewSize(bboxapi: BboxApiRouter) {
val (_, _, wifiMacFilter2) = bboxapi.getWifiMacFilterSync()
when (wifiMacFilter2) {
is Result.Failure -> {
val ex = wifiMacFilter2.getException()
println(ex)
}
is Result.Success -> {
println("new size : ${wifiMacFilter2.get()[0].acl?.rules?.size}")
}
}
}
fun deleteAllRules(bboxapi: BboxApiRouter, size: Int) {
for (i in 1..size) {
val (_, res, stateResult) = bboxapi.deleteMacFilterRuleSync(ruleIndex = i)
when (stateResult) {
is Result.Failure -> {
val ex = stateResult.getException()
println("failed to delete rule with id $i")
println(ex)
}
is Result.Success -> {
println("deleted rule with id $i")
}
}
}
} | mit | d293ccccb5ab917608934043c376dba8 | 26.791209 | 94 | 0.533913 | 4.519214 | false | false | false | false |
SapuSeven/BetterUntis | app/src/main/java/com/sapuseven/untis/helpers/api/LoginHelper.kt | 1 | 6091 | package com.sapuseven.untis.helpers.api
import com.sapuseven.untis.R
import com.sapuseven.untis.data.connectivity.UntisApiConstants
import com.sapuseven.untis.data.connectivity.UntisAuthentication
import com.sapuseven.untis.data.connectivity.UntisRequest
import com.sapuseven.untis.helpers.ErrorMessageDictionary
import com.sapuseven.untis.helpers.SerializationUtils
import com.sapuseven.untis.models.UntisSchoolInfo
import com.sapuseven.untis.models.untis.params.AppSharedSecretParams
import com.sapuseven.untis.models.untis.params.SchoolSearchParams
import com.sapuseven.untis.models.untis.params.UserDataParams
import com.sapuseven.untis.models.untis.response.AppSharedSecretResponse
import com.sapuseven.untis.models.untis.response.SchoolSearchResponse
import com.sapuseven.untis.models.untis.response.UserDataResponse
import com.sapuseven.untis.models.untis.response.UserDataResult
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerializationException
import kotlinx.serialization.decodeFromString
import java.net.UnknownHostException
class LoginHelper(
val loginData: LoginDataInfo,
val onStatusUpdate: (statusStringRes: Int) -> Unit,
val onError: (error: LoginErrorInfo) -> Unit
) {
private val api: UntisRequest = UntisRequest()
private val proxyHost: String? = null // TODO: Pass proxy host
init {
onStatusUpdate(R.string.logindatainput_connecting)
}
@ExperimentalSerializationApi
suspend fun loadSchoolInfo(school: String): UntisSchoolInfo? {
onStatusUpdate(R.string.logindatainput_aquiring_schoolid)
val schoolId = school.toIntOrNull()
val query = UntisRequest.UntisRequestQuery()
query.data.method = UntisApiConstants.METHOD_SEARCH_SCHOOLS
query.url = UntisApiConstants.SCHOOL_SEARCH_URL
query.proxyHost = proxyHost
query.data.params =
if (schoolId != null) listOf(SchoolSearchParams(schoolid = schoolId))
else listOf(SchoolSearchParams(search = school))
val result = api.request(query)
result.fold({ data ->
try {
val untisResponse =
SerializationUtils.getJSON().decodeFromString<SchoolSearchResponse>(data)
untisResponse.result?.let {
if (it.schools.isNotEmpty()) {
val schoolResult = it.schools.find { schoolInfoResult ->
schoolInfoResult.schoolId == schoolId || schoolInfoResult.loginName.equals(
school,
true
)
}
// TODO: Show manual selection dialog when there are more than one results are returned
if (schoolResult != null)
return schoolResult
}
onError(LoginErrorInfo(errorMessageStringRes = R.string.logindatainput_error_invalid_school))
} ?: run {
onError(
LoginErrorInfo(
errorCode = untisResponse.error?.code,
errorMessage = untisResponse.error?.message
)
)
}
} catch (e: SerializationException) {
onError(
LoginErrorInfo(
errorMessageStringRes = R.string.logindatainput_error_generic,
errorMessage = e.message
)
)
}
}, { error ->
onError(
LoginErrorInfo(
errorMessageStringRes = R.string.logindatainput_error_generic,
errorMessage = error.message
)
)
})
return null
}
suspend fun loadAppSharedSecret(apiUrl: String): String? {
onStatusUpdate(R.string.logindatainput_aquiring_app_secret)
val query = UntisRequest.UntisRequestQuery()
query.url = apiUrl
query.proxyHost = proxyHost
query.data.method = UntisApiConstants.METHOD_GET_APP_SHARED_SECRET
query.data.params = listOf(AppSharedSecretParams(loginData.user, loginData.password))
val appSharedSecretResult = api.request(query)
appSharedSecretResult.fold({ data ->
try {
val untisResponse =
SerializationUtils.getJSON().decodeFromString<AppSharedSecretResponse>(data)
if (untisResponse.error?.code == ErrorMessageDictionary.ERROR_CODE_INVALID_CREDENTIALS)
return loginData.password
if (untisResponse.result.isNullOrEmpty())
onError(
LoginErrorInfo(
errorCode = untisResponse.error?.code,
errorMessage = untisResponse.error?.message
)
)
else
return untisResponse.result
} catch (e: SerializationException) {
onError(
LoginErrorInfo(
errorMessageStringRes = R.string.logindatainput_error_generic,
errorMessage = e.message
)
)
}
}, { error ->
when (error.exception) {
is UnknownHostException -> onError(LoginErrorInfo(errorCode = ErrorMessageDictionary.ERROR_CODE_NO_SERVER_FOUND))
else -> onError(
LoginErrorInfo(
errorMessageStringRes = R.string.logindatainput_error_generic,
errorMessage = error.message
)
)
}
})
return null
}
suspend fun loadUserData(apiUrl: String, key: String?): UserDataResult? {
onStatusUpdate(R.string.logindatainput_loading_user_data)
val query = UntisRequest.UntisRequestQuery()
query.url = apiUrl
query.proxyHost = proxyHost
query.data.method = UntisApiConstants.METHOD_GET_USER_DATA
if (loginData.anonymous)
query.data.params =
listOf(UserDataParams(auth = UntisAuthentication.createAuthObject()))
else {
if (key == null) return null
query.data.params = listOf(
UserDataParams(
auth = UntisAuthentication.createAuthObject(
loginData.user,
key
)
)
)
}
val userDataResult = api.request(query)
userDataResult.fold({ data ->
try {
val untisResponse =
SerializationUtils.getJSON().decodeFromString<UserDataResponse>(data)
if (untisResponse.result != null) {
return untisResponse.result
} else {
onError(
LoginErrorInfo(
errorCode = untisResponse.error?.code,
errorMessage = untisResponse.error?.message
)
)
}
} catch (e: SerializationException) {
onError(
LoginErrorInfo(
errorMessageStringRes = R.string.logindatainput_error_generic,
errorMessage = e.message
)
)
}
}, { error ->
onError(
LoginErrorInfo(
errorMessageStringRes = R.string.logindatainput_error_generic,
errorMessage = error.message
)
)
})
return null
}
}
| gpl-3.0 | b1d24b4efa54ef1ccdb494dac180a4bc | 28.425121 | 117 | 0.727138 | 4.071524 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/provider/TwidereDataProvider.kt | 1 | 22449 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.provider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.SharedPreferences
import android.database.Cursor
import android.database.MatrixCursor
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteFullException
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.support.v4.text.BidiFormatter
import com.squareup.otto.Bus
import okhttp3.Dns
import org.mariotaku.ktextension.isNullOrEmpty
import org.mariotaku.ktextension.toNulls
import org.mariotaku.sqliteqb.library.Columns.Column
import org.mariotaku.sqliteqb.library.Expression
import org.mariotaku.sqliteqb.library.RawItemArray
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.annotation.ReadPositionTag
import de.vanita5.twittnuker.app.TwittnukerApplication
import de.vanita5.twittnuker.extension.withAppendedPath
import de.vanita5.twittnuker.model.AccountPreferences
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.event.UnreadCountUpdatedEvent
import de.vanita5.twittnuker.provider.TwidereDataStore.*
import de.vanita5.twittnuker.util.*
import de.vanita5.twittnuker.util.SQLiteDatabaseWrapper.LazyLoadCallback
import de.vanita5.twittnuker.util.dagger.GeneralComponent
import de.vanita5.twittnuker.util.database.CachedUsersQueryBuilder
import de.vanita5.twittnuker.util.database.SuggestionsCursorCreator
import de.vanita5.twittnuker.util.notification.ContentNotificationManager
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import javax.inject.Inject
class TwidereDataProvider : ContentProvider(), LazyLoadCallback {
@Inject
lateinit internal var readStateManager: ReadStateManager
@Inject
lateinit internal var twitterWrapper: AsyncTwitterWrapper
@Inject
lateinit internal var notificationManager: NotificationManagerWrapper
@Inject
lateinit internal var preferences: SharedPreferences
@Inject
lateinit internal var dns: Dns
@Inject
lateinit internal var bus: Bus
@Inject
lateinit internal var userColorNameManager: UserColorNameManager
@Inject
lateinit internal var bidiFormatter: BidiFormatter
@Inject
lateinit internal var contentNotificationManager: ContentNotificationManager
private lateinit var databaseWrapper: SQLiteDatabaseWrapper
private lateinit var backgroundExecutor: Executor
private lateinit var handler: Handler
override fun onCreate(): Boolean {
val context = context!!
GeneralComponent.get(context).inject(this)
handler = Handler(Looper.getMainLooper())
databaseWrapper = SQLiteDatabaseWrapper(this)
backgroundExecutor = Executors.newSingleThreadExecutor()
// final GetWritableDatabaseTask task = new
// GetWritableDatabaseTask(context, helper, mDatabaseWrapper);
// task.executeTask();
return true
}
override fun onCreateSQLiteDatabase(): SQLiteDatabase {
val app = TwittnukerApplication.getInstance(context!!)
val helper = app.sqLiteOpenHelper
return helper.writableDatabase
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
try {
return insertInternal(uri, values)
} catch (e: SQLException) {
if (handleSQLException(e)) {
try {
return insertInternal(uri, values)
} catch (e1: SQLException) {
throw IllegalStateException(e1)
}
}
throw IllegalStateException(e)
}
}
override fun bulkInsert(uri: Uri, valuesArray: Array<ContentValues>): Int {
try {
return bulkInsertInternal(uri, valuesArray)
} catch (e: SQLException) {
if (handleSQLException(e)) {
try {
return bulkInsertInternal(uri, valuesArray)
} catch (e1: SQLException) {
throw IllegalStateException(e1)
}
}
throw IllegalStateException(e)
}
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?,
sortOrder: String?): Cursor? {
try {
val tableId = DataStoreUtils.getTableId(uri)
val table = DataStoreUtils.getTableNameById(tableId)
when (tableId) {
VIRTUAL_TABLE_ID_DATABASE_PREPARE -> {
databaseWrapper.prepare()
return MatrixCursor(projection ?: arrayOfNulls<String>(0))
}
VIRTUAL_TABLE_ID_CACHED_USERS_WITH_RELATIONSHIP -> {
val accountKey = UserKey.valueOf(uri.lastPathSegment)
val accountHost = uri.getQueryParameter(EXTRA_ACCOUNT_HOST)
val accountType = uri.getQueryParameter(EXTRA_ACCOUNT_TYPE)
val query = CachedUsersQueryBuilder.withRelationship(projection,
Expression(selection), selectionArgs, sortOrder, accountKey,
accountHost, accountType)
val c = databaseWrapper.rawQuery(query.first.sql, query.second)
c?.setNotificationUri(context.contentResolver, CachedUsers.CONTENT_URI)
return c
}
VIRTUAL_TABLE_ID_CACHED_USERS_WITH_SCORE -> {
val accountKey = UserKey.valueOf(uri.lastPathSegment)
val accountHost = uri.getQueryParameter(EXTRA_ACCOUNT_HOST)
val accountType = uri.getQueryParameter(EXTRA_ACCOUNT_TYPE)
val query = CachedUsersQueryBuilder.withScore(projection, Expression(selection),
selectionArgs, sortOrder, accountKey, accountHost, accountType, 0)
val c = databaseWrapper.rawQuery(query.first.sql, query.second)
c?.setNotificationUri(context.contentResolver, CachedUsers.CONTENT_URI)
return c
}
VIRTUAL_TABLE_ID_DRAFTS_UNSENT -> {
val twitter = twitterWrapper
val sendingIds = RawItemArray(twitter.getSendingDraftIds())
val where: Expression
if (selection != null) {
where = Expression.and(Expression(selection),
Expression.notIn(Column(Drafts._ID), sendingIds))
} else {
where = Expression.and(Expression.notIn(Column(Drafts._ID), sendingIds))
}
val c = databaseWrapper.query(Drafts.TABLE_NAME, projection,
where.sql, selectionArgs, null, null, sortOrder)
c?.setNotificationUri(context.contentResolver, uri)
return c
}
VIRTUAL_TABLE_ID_SUGGESTIONS_AUTO_COMPLETE -> {
return SuggestionsCursorCreator.forAutoComplete(databaseWrapper,
userColorNameManager, uri, projection)
}
VIRTUAL_TABLE_ID_SUGGESTIONS_SEARCH -> {
return SuggestionsCursorCreator.forSearch(databaseWrapper,
userColorNameManager, uri, projection)
}
VIRTUAL_TABLE_ID_NULL -> {
return null
}
VIRTUAL_TABLE_ID_EMPTY -> {
return MatrixCursor(projection ?: arrayOfNulls<String>(0))
}
VIRTUAL_TABLE_ID_RAW_QUERY -> {
if (projection != null || selection != null || sortOrder != null) {
throw IllegalArgumentException()
}
val c = databaseWrapper.rawQuery(uri.lastPathSegment, selectionArgs)
uri.getQueryParameter(QUERY_PARAM_NOTIFY_URI)?.let {
c?.setNotificationUri(context.contentResolver, Uri.parse(it))
}
return c
}
}
if (table == null) return null
val limit = uri.getQueryParameter(QUERY_PARAM_LIMIT)
val c = databaseWrapper.query(table, projection, selection, selectionArgs,
null, null, sortOrder, limit)
c?.setNotificationUri(context.contentResolver, uri)
return c
} catch (e: SQLException) {
throw IllegalStateException(e)
}
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
try {
return updateInternal(uri, values, selection, selectionArgs)
} catch (e: SQLException) {
if (handleSQLException(e)) {
try {
return updateInternal(uri, values, selection, selectionArgs)
} catch (e1: SQLException) {
throw IllegalStateException(e1)
}
}
throw IllegalStateException(e)
}
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
try {
return deleteInternal(uri, selection, selectionArgs)
} catch (e: SQLException) {
if (handleSQLException(e)) {
try {
return deleteInternal(uri, selection, selectionArgs)
} catch (e1: SQLException) {
throw IllegalStateException(e1)
}
}
throw IllegalStateException(e)
}
}
override fun getType(uri: Uri): String? {
return null
}
private fun handleSQLException(e: SQLException): Boolean {
try {
if (e is SQLiteFullException) {
// Drop cached databases
databaseWrapper.delete(CachedUsers.TABLE_NAME, null, null)
databaseWrapper.delete(CachedStatuses.TABLE_NAME, null, null)
databaseWrapper.delete(CachedHashtags.TABLE_NAME, null, null)
databaseWrapper.execSQL("VACUUM")
return true
}
} catch (ee: SQLException) {
throw IllegalStateException(ee)
}
throw IllegalStateException(e)
}
private fun bulkInsertInternal(uri: Uri, valuesArray: Array<ContentValues>): Int {
val tableId = DataStoreUtils.getTableId(uri)
val table = DataStoreUtils.getTableNameById(tableId)
var result = 0
val newIds = LongArray(valuesArray.size)
if (table != null && valuesArray.isNotEmpty()) {
databaseWrapper.beginTransaction()
if (tableId == TABLE_ID_CACHED_USERS) {
for (values in valuesArray) {
val where = Expression.equalsArgs(CachedUsers.USER_KEY)
databaseWrapper.update(table, values, where.sql, arrayOf(values.getAsString(CachedUsers.USER_KEY)))
newIds[result++] = databaseWrapper.insertWithOnConflict(table, null,
values, SQLiteDatabase.CONFLICT_REPLACE)
}
} else if (tableId == TABLE_ID_SEARCH_HISTORY) {
for (values in valuesArray) {
values.put(SearchHistory.RECENT_QUERY, System.currentTimeMillis())
val where = Expression.equalsArgs(SearchHistory.QUERY)
val args = arrayOf(values.getAsString(SearchHistory.QUERY))
databaseWrapper.update(table, values, where.sql, args)
newIds[result++] = databaseWrapper.insertWithOnConflict(table, null,
values, SQLiteDatabase.CONFLICT_IGNORE)
}
} else {
val conflictAlgorithm = getConflictAlgorithm(tableId)
if (conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE) {
for (values in valuesArray) {
newIds[result++] = databaseWrapper.insertWithOnConflict(table, null,
values, conflictAlgorithm)
}
} else {
for (values in valuesArray) {
newIds[result++] = databaseWrapper.insert(table, null, values)
}
}
}
databaseWrapper.setTransactionSuccessful()
databaseWrapper.endTransaction()
}
if (result > 0) {
onDatabaseUpdated(tableId, uri)
}
onNewItemsInserted(uri, tableId, valuesArray.toNulls())
return result
}
private fun deleteInternal(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val tableId = DataStoreUtils.getTableId(uri)
when (tableId) {
VIRTUAL_TABLE_ID_DRAFTS_NOTIFICATIONS -> {
notificationManager.cancel(uri.toString(), NOTIFICATION_ID_DRAFTS)
return 1
}
else -> {
val table = DataStoreUtils.getTableNameById(tableId) ?: return 0
val result = databaseWrapper.delete(table, selection, selectionArgs)
if (result > 0) {
onDatabaseUpdated(tableId, uri)
}
onItemDeleted(uri, tableId)
return result
}
}
}
private fun insertInternal(uri: Uri, values: ContentValues?): Uri? {
val tableId = DataStoreUtils.getTableId(uri)
val table = DataStoreUtils.getTableNameById(tableId)
var rowId: Long = -1
when (tableId) {
TABLE_ID_CACHED_USERS -> {
if (values != null) {
val where = Expression.equalsArgs(CachedUsers.USER_KEY)
val whereArgs = arrayOf(values.getAsString(CachedUsers.USER_KEY))
databaseWrapper.update(table, values, where.sql, whereArgs)
}
rowId = databaseWrapper.insertWithOnConflict(table, null, values,
SQLiteDatabase.CONFLICT_IGNORE)
}
TABLE_ID_SEARCH_HISTORY -> {
if (values != null) {
values.put(SearchHistory.RECENT_QUERY, System.currentTimeMillis())
val where = Expression.equalsArgs(SearchHistory.QUERY)
val args = arrayOf(values.getAsString(SearchHistory.QUERY))
databaseWrapper.update(table, values, where.sql, args)
}
rowId = databaseWrapper.insertWithOnConflict(table, null, values,
SQLiteDatabase.CONFLICT_IGNORE)
}
TABLE_ID_CACHED_RELATIONSHIPS -> {
var updated = false
if (values != null) {
val accountKey = values.getAsString(CachedRelationships.ACCOUNT_KEY)
val userKey = values.getAsString(CachedRelationships.USER_KEY)
val where = Expression.and(Expression.equalsArgs(CachedRelationships.ACCOUNT_KEY),
Expression.equalsArgs(CachedRelationships.USER_KEY))
if (databaseWrapper.update(table, values, where.sql, arrayOf(accountKey,
userKey)) > 0) {
val projection = arrayOf(CachedRelationships._ID)
val c = databaseWrapper.query(table, projection, where.sql, null,
null, null, null)
if (c.moveToFirst()) {
rowId = c.getLong(0)
}
c.close()
updated = true
}
}
if (!updated) {
rowId = databaseWrapper.insertWithOnConflict(table, null, values,
SQLiteDatabase.CONFLICT_IGNORE)
}
}
VIRTUAL_TABLE_ID_DRAFTS_NOTIFICATIONS -> {
rowId = contentNotificationManager.showDraft(uri)
}
else -> {
val conflictAlgorithm = getConflictAlgorithm(tableId)
if (conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE) {
rowId = databaseWrapper.insertWithOnConflict(table, null, values,
conflictAlgorithm)
} else if (table != null) {
rowId = databaseWrapper.insert(table, null, values)
} else {
return null
}
}
}
onDatabaseUpdated(tableId, uri)
onNewItemsInserted(uri, tableId, arrayOf(values))
return uri.withAppendedPath(rowId.toString())
}
private fun updateInternal(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
val tableId = DataStoreUtils.getTableId(uri)
val table = DataStoreUtils.getTableNameById(tableId)
var result = 0
if (table != null) {
result = databaseWrapper.update(table, values, selection, selectionArgs)
}
if (result > 0) {
onDatabaseUpdated(tableId, uri)
}
return result
}
private fun notifyContentObserver(uri: Uri) {
if (!uri.getBooleanQueryParameter(QUERY_PARAM_NOTIFY_CHANGE, true)) return
handler.post {
context?.contentResolver?.notifyChange(uri, null)
}
}
private fun notifyUnreadCountChanged(position: Int) {
handler.post { bus.post(UnreadCountUpdatedEvent(position)) }
}
private fun onDatabaseUpdated(tableId: Int, uri: Uri?) {
if (uri == null) return
notifyContentObserver(uri)
}
private fun onItemDeleted(uri: Uri, tableId: Int) {
}
private fun onNewItemsInserted(uri: Uri, tableId: Int, valuesArray: Array<ContentValues?>?) {
val context = context ?: return
if (valuesArray.isNullOrEmpty()) return
when (tableId) {
// TABLE_ID_STATUSES -> {
// if (!uri.getBooleanQueryParameter(QUERY_PARAM_SHOW_NOTIFICATION, true)) return
// backgroundExecutor.execute {
// val prefs = AccountPreferences.getAccountPreferences(context, preferences,
// DataStoreUtils.getAccountKeys(context))
// prefs.filter { it.isNotificationEnabled && it.isHomeTimelineNotificationEnabled }.forEach {
// val positionTag = getPositionTag(CustomTabType.HOME_TIMELINE, it.accountKey)
// contentNotificationManager.showTimeline(it, positionTag)
// }
// notifyUnreadCountChanged(NOTIFICATION_ID_HOME_TIMELINE)
// }
// }
TABLE_ID_ACTIVITIES_ABOUT_ME -> {
if (!uri.getBooleanQueryParameter(QUERY_PARAM_SHOW_NOTIFICATION, true)) return
backgroundExecutor.execute {
val prefs = AccountPreferences.getAccountPreferences(context, preferences,
DataStoreUtils.getAccountKeys(context))
prefs.filter { it.isNotificationEnabled && it.isInteractionsNotificationEnabled }.forEach {
val positionTag = getPositionTag(ReadPositionTag.ACTIVITIES_ABOUT_ME, it.accountKey)
contentNotificationManager.showInteractions(it, positionTag)
}
notifyUnreadCountChanged(NOTIFICATION_ID_INTERACTIONS_TIMELINE)
}
}
TABLE_ID_MESSAGES_CONVERSATIONS -> {
if (!uri.getBooleanQueryParameter(QUERY_PARAM_SHOW_NOTIFICATION, true)) return
backgroundExecutor.execute {
val prefs = AccountPreferences.getAccountPreferences(context, preferences,
DataStoreUtils.getAccountKeys(context))
prefs.filter { it.isNotificationEnabled && it.isDirectMessagesNotificationEnabled }.forEach {
contentNotificationManager.showMessages(it)
}
notifyUnreadCountChanged(NOTIFICATION_ID_DIRECT_MESSAGES)
}
}
TABLE_ID_DRAFTS -> {
}
}
}
private fun getPositionTag(tag: String, accountKey: UserKey): Long {
val position = readStateManager.getPosition(Utils.getReadPositionTagWithAccount(tag,
accountKey))
if (position != -1L) return position
return readStateManager.getPosition(tag)
}
companion object {
private fun getConflictAlgorithm(tableId: Int): Int {
when (tableId) {
TABLE_ID_CACHED_HASHTAGS, TABLE_ID_CACHED_STATUSES, TABLE_ID_CACHED_USERS,
TABLE_ID_CACHED_RELATIONSHIPS, TABLE_ID_SEARCH_HISTORY, TABLE_ID_MESSAGES,
TABLE_ID_MESSAGES_CONVERSATIONS -> {
return SQLiteDatabase.CONFLICT_REPLACE
}
TABLE_ID_FILTERED_USERS, TABLE_ID_FILTERED_KEYWORDS, TABLE_ID_FILTERED_SOURCES,
TABLE_ID_FILTERED_LINKS -> {
return SQLiteDatabase.CONFLICT_IGNORE
}
}
return SQLiteDatabase.CONFLICT_NONE
}
}
} | gpl-3.0 | 059fcf3c43ae37788136b02aef73bae6 | 42.762183 | 122 | 0.592187 | 5.492782 | false | false | false | false |
AndroidX/androidx | compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/ComposableTargetAnnotationsTransformer.kt | 3 | 45484 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin.lower
import androidx.compose.compiler.plugins.kotlin.ComposeClassIds
import androidx.compose.compiler.plugins.kotlin.ComposeFqNames
import androidx.compose.compiler.plugins.kotlin.KtxNameConventions
import androidx.compose.compiler.plugins.kotlin.ModuleMetrics
import androidx.compose.compiler.plugins.kotlin.analysis.ComposeWritableSlices
import androidx.compose.compiler.plugins.kotlin.inference.ApplierInferencer
import androidx.compose.compiler.plugins.kotlin.inference.ErrorReporter
import androidx.compose.compiler.plugins.kotlin.inference.TypeAdapter
import androidx.compose.compiler.plugins.kotlin.inference.Item
import androidx.compose.compiler.plugins.kotlin.inference.LazyScheme
import androidx.compose.compiler.plugins.kotlin.inference.LazySchemeStorage
import androidx.compose.compiler.plugins.kotlin.inference.NodeAdapter
import androidx.compose.compiler.plugins.kotlin.inference.NodeKind
import androidx.compose.compiler.plugins.kotlin.inference.Open
import androidx.compose.compiler.plugins.kotlin.inference.Scheme
import androidx.compose.compiler.plugins.kotlin.inference.Token
import androidx.compose.compiler.plugins.kotlin.inference.deserializeScheme
import androidx.compose.compiler.plugins.kotlin.irTrace
import androidx.compose.compiler.plugins.kotlin.mergeWith
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrLocalDelegatedProperty
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.declarations.IrValueParameter
import org.jetbrains.kotlin.ir.declarations.IrVariable
import org.jetbrains.kotlin.ir.declarations.name
import org.jetbrains.kotlin.ir.expressions.IrBlock
import org.jetbrains.kotlin.ir.expressions.IrBody
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrConst
import org.jetbrains.kotlin.ir.expressions.IrConstructorCall
import org.jetbrains.kotlin.ir.expressions.IrContainerExpression
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrFunctionExpression
import org.jetbrains.kotlin.ir.expressions.IrGetField
import org.jetbrains.kotlin.ir.expressions.IrGetValue
import org.jetbrains.kotlin.ir.expressions.IrReturn
import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin
import org.jetbrains.kotlin.ir.expressions.IrTypeOperatorCall
import org.jetbrains.kotlin.ir.expressions.impl.IrConstructorCallImpl
import org.jetbrains.kotlin.ir.interpreter.getLastOverridden
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.IrTypeArgument
import org.jetbrains.kotlin.ir.types.IrTypeProjection
import org.jetbrains.kotlin.ir.types.classFqName
import org.jetbrains.kotlin.ir.types.classOrNull
import org.jetbrains.kotlin.ir.types.defaultType
import org.jetbrains.kotlin.ir.types.impl.buildSimpleType
import org.jetbrains.kotlin.ir.types.impl.toBuilder
import org.jetbrains.kotlin.ir.types.isAny
import org.jetbrains.kotlin.ir.types.isClassWithFqName
import org.jetbrains.kotlin.ir.types.isNullableAny
import org.jetbrains.kotlin.ir.types.typeOrNull
import org.jetbrains.kotlin.ir.util.constructors
import org.jetbrains.kotlin.ir.util.dump
import org.jetbrains.kotlin.ir.util.file
import org.jetbrains.kotlin.ir.util.fqNameWhenAvailable
import org.jetbrains.kotlin.ir.util.functions
import org.jetbrains.kotlin.ir.util.hasAnnotation
import org.jetbrains.kotlin.ir.util.isFunction
import org.jetbrains.kotlin.ir.util.isNullConst
import org.jetbrains.kotlin.ir.util.isTypeParameter
import org.jetbrains.kotlin.ir.util.parentAsClass
import org.jetbrains.kotlin.ir.util.statements
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
/**
* This transformer walks the IR tree to infer the applier annotations such as ComposableTarget,
* ComposableOpenTarget, and
*/
class ComposableTargetAnnotationsTransformer(
context: IrPluginContext,
symbolRemapper: ComposableSymbolRemapper,
metrics: ModuleMetrics
) : AbstractComposeLowering(context, symbolRemapper, metrics) {
private val ComposableTargetClass = symbolRemapper.getReferencedClassOrNull(
getTopLevelClassOrNull(ComposeClassIds.ComposableTarget)
)
private val ComposableOpenTargetClass = symbolRemapper.getReferencedClassOrNull(
getTopLevelClassOrNull(ComposeClassIds.ComposableOpenTarget)
)
private val ComposableInferredTargetClass = symbolRemapper.getReferencedClassOrNull(
getTopLevelClassOrNull(ComposeClassIds.ComposableInferredTarget)
)
/**
* A map of element to the owning function of the element.
*/
private val ownerMap = mutableMapOf<IrElement, IrFunction>()
/**
* Map of a parameter symbol to its function and parameter index.
*/
private val parameterOwners = mutableMapOf<IrSymbol, Pair<IrFunction, Int>>()
/**
* A map of variables to their corresponding inference node.
*/
private val variableDeclarations = mutableMapOf<IrSymbol, InferenceVariable>()
private var currentOwner: IrFunction? = null
private var currentFile: IrFile? = null
private val transformer get() = this
private fun lineInfoOf(element: IrElement?): String {
val file = currentFile
if (element != null && file != null) {
return " ${file.name}:${
file.fileEntry.getLineNumber(element.startOffset) + 1
}:${
file.fileEntry.getColumnNumber(element.startOffset) + 1
}"
}
return ""
}
private val infer = ApplierInferencer(
typeAdapter = object : TypeAdapter<InferenceFunction> {
val current = mutableMapOf<InferenceFunction, Scheme>()
override fun declaredSchemaOf(type: InferenceFunction): Scheme =
type.toDeclaredScheme().also {
type.recordScheme(it)
}
override fun currentInferredSchemeOf(type: InferenceFunction): Scheme? =
if (type.schemeIsUpdatable) current[type] ?: declaredSchemaOf(type) else null
override fun updatedInferredScheme(type: InferenceFunction, scheme: Scheme) {
type.recordScheme(scheme)
type.updateScheme(scheme)
current[type] = scheme
}
},
nodeAdapter = object : NodeAdapter<InferenceFunction, InferenceNode> {
override fun containerOf(node: InferenceNode): InferenceNode =
ownerMap[node.element]?.let {
inferenceNodeOf(it, transformer)
} ?: (node as? InferenceResolvedParameter)?.referenceContainer ?: node
override fun kindOf(node: InferenceNode): NodeKind = node.kind
override fun schemeParameterIndexOf(
node: InferenceNode,
container: InferenceNode
): Int = node.parameterIndex(container)
override fun typeOf(node: InferenceNode): InferenceFunction? = node.function
override fun referencedContainerOf(node: InferenceNode): InferenceNode? =
node.referenceContainer
},
lazySchemeStorage = object : LazySchemeStorage<InferenceNode> {
// The transformer is transitory so we can just store this in a map.
val map = mutableMapOf<InferenceNode, LazyScheme>()
override fun getLazyScheme(node: InferenceNode): LazyScheme? = map[node]
override fun storeLazyScheme(node: InferenceNode, value: LazyScheme) {
map[node] = value
}
},
errorReporter = object : ErrorReporter<InferenceNode> {
override fun reportCallError(node: InferenceNode, expected: String, received: String) {
// Ignored, should be reported by the front-end
}
override fun reportParameterError(
node: InferenceNode,
index: Int,
expected: String,
received: String
) {
// Ignored, should be reported by the front-end
}
override fun log(node: InferenceNode?, message: String) {
val element = node?.element
if (!metrics.isEmpty)
metrics.log("applier inference${lineInfoOf(element)}: $message")
}
}
)
override fun lower(module: IrModuleFragment) {
// Only transform if the attributes being inferred are in the runtime
if (
ComposableTargetClass != null &&
ComposableInferredTargetClass != null &&
ComposableOpenTargetClass != null
) {
module.transformChildrenVoid(this)
}
}
override fun visitFile(declaration: IrFile): IrFile {
includeFileNameInExceptionTrace(declaration) {
currentFile = declaration
return super.visitFile(declaration).also { currentFile = null }
}
}
override fun visitFunction(declaration: IrFunction): IrStatement {
if (
declaration.hasSchemeSpecified() ||
(!declaration.isComposable && !declaration.hasComposableParameter()) ||
declaration.hasOverlyWideParameters() ||
declaration.hasOpenTypeParameters()
) {
return super.visitFunction(declaration)
}
val oldOwner = currentOwner
currentOwner = declaration
var currentParameter = 0
fun recordParameter(parameter: IrValueParameter) {
if (parameter.type.isOrHasComposableLambda) {
parameterOwners[parameter.symbol] = declaration to currentParameter++
}
}
declaration.valueParameters.forEach { recordParameter(it) }
declaration.extensionReceiverParameter?.let { recordParameter(it) }
val result = super.visitFunction(declaration)
currentOwner = oldOwner
return result
}
override fun visitVariable(declaration: IrVariable): IrStatement {
if (declaration.type.isOrHasComposableLambda) {
currentOwner?.let { ownerMap[declaration] = it }
val initializerNode = declaration.initializer
if (initializerNode != null) {
val initializer = resolveExpressionOrNull(initializerNode)
?: InferenceElementExpression(transformer, initializerNode)
val variable = InferenceVariable(this, declaration)
variableDeclarations[declaration.symbol] = variable
infer.visitVariable(variable, initializer)
}
}
return super.visitVariable(declaration)
}
override fun visitLocalDelegatedProperty(declaration: IrLocalDelegatedProperty): IrStatement {
val result = super.visitLocalDelegatedProperty(declaration)
if (declaration.type.isOrHasComposableLambda) {
// Find the inference variable for the delegate which should have been created
// when visiting the delegate node. If not, then ignore this declaration
val variable = variableDeclarations[declaration.delegate.symbol] ?: return result
// Allow the variable to be found from the getter as this is what is used to access
// the variable, not the delegate directly.
variableDeclarations[declaration.getter.symbol] = variable
}
return result
}
override fun visitCall(expression: IrCall): IrExpression {
val owner = currentOwner
if (
owner == null || (
!expression.isTransformedComposableCall() &&
!expression.hasComposableArguments()
) || when (expression.symbol.owner.fqNameWhenAvailable) {
ComposeFqNames.getCurrentComposerFullName,
ComposeFqNames.composableLambdaFullName -> true
else -> false
}
) {
return super.visitCall(expression)
}
ownerMap[expression] = owner
val result = super.visitCall(expression)
val target = (
if (
expression.isInvoke() ||
expression.dispatchReceiver?.type?.isSamComposable == true
) {
expression.dispatchReceiver?.let {
resolveExpressionOrNull(it)
}
} else resolveExpressionOrNull(expression)
) ?: InferenceCallTargetNode(this, expression)
if (target.isOverlyWide()) return result
val arguments = expression.arguments.filterIndexed { index, argument ->
argument?.let {
it.isComposableLambda || it.isComposableParameter || (
if (
// There are three cases where the expression type is not good enough here,
// one, the type is a default parameter and there is no actual expression
// and, two, when the expression is a SAM conversion where the type is
// too specific (it is the class) and we need the SAM interface, and three
// the value is null for a nullable type.
(
argument is IrContainerExpression &&
argument.origin == IrStatementOrigin.DEFAULT_VALUE
) || (
argument is IrBlock
) || (
argument.isNullConst()
)
) {
// If the parameter is a default value, grab the type from the function
// being called.
expression.symbol.owner.valueParameters.let { parameters ->
if (index < parameters.size) parameters[index].type else null
}
} else it.type)?.isOrHasComposableLambda == true
} == true
}.filterNotNull().toMutableList()
fun recordArgument(argument: IrExpression?) {
if (
argument != null && (
argument.isComposableLambda ||
argument.isComposableParameter ||
argument.type.isOrHasComposableLambda
)
) {
arguments.add(argument)
}
}
recordArgument(expression.extensionReceiver)
infer.visitCall(
call = inferenceNodeOf(expression, transformer),
target = target,
arguments = arguments.map {
resolveExpressionOrNull(it) ?: inferenceNodeOf(it, transformer)
}
)
return result
}
private fun inferenceParameterOrNull(getValue: IrGetValue): InferenceResolvedParameter? =
parameterOwners[getValue.symbol]?.let {
InferenceResolvedParameter(
getValue,
inferenceFunctionOf(it.first),
inferenceNodeOf(it.first, this),
it.second
)
}
/**
* Resolve references to local variables and parameters.
*/
private fun resolveExpressionOrNull(expression: IrElement?): InferenceNode? =
when (expression) {
is IrGetValue ->
// Get the inference node for referencing a local variable or parameter if this
// expression does.
inferenceParameterOrNull(expression) ?: variableDeclarations[expression.symbol]
is IrCall ->
// If this call is a call to the getter of a local delegate get the inference
// node of the delegate.
variableDeclarations[expression.symbol]
else -> null
}
val List<IrConstructorCall>.target: Item get() =
firstOrNull { it.isComposableTarget }?.let { constructor ->
constructor.firstParameterOrNull<String>()?.let { Token(it) }
} ?: firstOrNull { it.isComposableOpenTarget }?.let { constructor ->
constructor.firstParameterOrNull<Int>()?.let { Open(it) }
} ?: firstOrNull { it.isComposableTargetMarked }?.let { constructor ->
val fqName = constructor.symbol.owner.parentAsClass.fqNameWhenAvailable
fqName?.let {
Token(it.asString())
}
} ?: Open(-1, isUnspecified = true)
val IrFunction.scheme: Scheme? get() =
annotations.firstOrNull { it.isComposableInferredTarget }?.let { constructor ->
constructor.firstParameterOrNull<String>()?.let {
deserializeScheme(it)
}
}
fun IrFunction.hasSchemeSpecified(): Boolean =
annotations.any {
it.isComposableTarget || it.isComposableOpenTarget || it.isComposableInferredTarget ||
it.isComposableTargetMarked
}
fun IrType.toScheme(defaultTarget: Item): Scheme =
when {
this is IrSimpleType && isFunction() -> arguments
else -> emptyList()
}.let { typeArguments ->
val target = annotations.target.let {
if (it.isUnspecified) defaultTarget else it
}
fun toScheme(argument: IrTypeArgument): Scheme? =
if (argument is IrTypeProjection && argument.type.isOrHasComposableLambda)
argument.type.toScheme(defaultTarget)
else null
val parameters = typeArguments.takeUpTo(typeArguments.size - 1).mapNotNull { argument ->
toScheme(argument)
}
val result = typeArguments.lastOrNull()?.let { argument ->
toScheme(argument)
}
Scheme(target, parameters, result)
}
private val IrElement?.isComposableLambda: Boolean get() = when (this) {
is IrFunctionExpression -> function.isComposable
is IrCall -> isComposableSingletonGetter() || hasTransformedLambda()
is IrGetField -> symbol.owner.initializer?.findTransformedLambda() != null
else -> false
}
private val IrElement?.isComposableParameter: Boolean get() = when (this) {
is IrGetValue -> parameterOwners[symbol] != null && type.isComposable
else -> false
}
internal fun IrCall.hasTransformedLambda() =
context.irTrace[ComposeWritableSlices.HAS_TRANSFORMED_LAMBDA, this] == true
private fun IrElement.findTransformedLambda(): IrFunctionExpression? =
when (this) {
is IrCall -> arguments.firstNotNullOfOrNull { it?.findTransformedLambda() }
is IrGetField -> symbol.owner.initializer?.findTransformedLambda()
is IrBody -> statements.firstNotNullOfOrNull { it.findTransformedLambda() }
is IrReturn -> value.findTransformedLambda()
is IrFunctionExpression -> if (isTransformedLambda()) this else null
else -> null
}
private fun IrFunctionExpression.isTransformedLambda() =
context.irTrace[ComposeWritableSlices.IS_TRANSFORMED_LAMBDA, this] == true
internal fun IrElement.transformedLambda(): IrFunctionExpression =
findTransformedLambda() ?: error("Could not find the lambda for ${dump()}")
// If this function throws an error it is because the IR transformation for singleton functions
// changed. This function should be updated to account for the change.
internal fun IrCall.singletonFunctionExpression(): IrFunctionExpression =
symbol.owner.body?.findTransformedLambda()
?: error("Could not find the singleton lambda for ${dump()}")
private fun Item.toAnnotation(): IrConstructorCall? =
if (ComposableTargetClass != null && ComposableOpenTargetClass != null) {
when (this) {
is Token -> annotation(ComposableTargetClass).also {
it.putValueArgument(0, irConst(value))
}
is Open ->
if (index < 0) null else annotation(
ComposableOpenTargetClass
).also {
it.putValueArgument(0, irConst(index))
}
}
} else null
private fun Item.toAnnotations(): List<IrConstructorCall> =
toAnnotation()?.let { listOf(it) } ?: emptyList()
private fun Scheme.toAnnotations(): List<IrConstructorCall> =
if (ComposableInferredTargetClass != null) {
listOf(
annotation(ComposableInferredTargetClass).also {
it.putValueArgument(0, irConst(serialize()))
}
)
} else emptyList()
private fun annotation(classSymbol: IrClassSymbol) =
IrConstructorCallImpl(
UNDEFINED_OFFSET,
UNDEFINED_OFFSET,
classSymbol.defaultType,
classSymbol.constructors.first(),
0,
0,
1,
null
)
private fun filteredAnnotations(annotations: List<IrConstructorCall>) = annotations
.filter {
!it.isComposableTarget &&
!it.isComposableOpenTarget &&
!it.isComposableInferredTarget
}
fun updatedAnnotations(annotations: List<IrConstructorCall>, target: Item) =
filteredAnnotations(annotations) + target.toAnnotations()
fun updatedAnnotations(annotations: List<IrConstructorCall>, scheme: Scheme) =
filteredAnnotations(annotations) + scheme.toAnnotations()
fun inferenceFunctionOf(function: IrFunction) =
InferenceFunctionDeclaration(this, function)
fun inferenceFunctionTypeOf(type: IrType) =
InferenceFunctionType(this, type)
/**
* A function is composable if it has a composer parameter added by the
* [ComposerParamTransformer] or it still has the @Composable annotation which
* can be because it is external and hasn't been transformed as the symbol remapper
* only remaps what is referenced as a symbol this method might not have been
* referenced directly in this module.
*/
private val IrFunction.isComposable get() =
valueParameters.any { it.name == KtxNameConventions.COMPOSER_PARAMETER } ||
annotations.hasAnnotation(ComposeFqNames.Composable)
private val IrType.isSamComposable get() =
samOwnerOrNull()?.isComposable == true
private val IrType.isComposableLambda get() =
(this.classFqName == ComposeFqNames.composableLambdaType) ||
(this as? IrSimpleType)
?.arguments
?.any {
it.typeOrNull?.classFqName == ComposeFqNames.Composer
} == true
internal val IrType.isOrHasComposableLambda: Boolean get() =
isComposableLambda || isSamComposable ||
(this as? IrSimpleType)?.arguments?.any {
it.typeOrNull?.isOrHasComposableLambda == true
} == true
private val IrType.isComposable get() = isComposableLambda || isSamComposable
private fun IrFunction.hasComposableParameter() =
valueParameters.any { it.type.isComposable }
private fun IrCall.hasComposableArguments() =
arguments.any { argument ->
argument?.type?.let { type ->
(type.isOrHasComposableLambda || type.isSamComposable)
} == true
}
}
/**
* An [InferenceFunction] is an abstraction to allow inference to translate a type into a scheme
* and update the declaration of a type if inference determines a more accurate scheme.
*/
sealed class InferenceFunction(
val transformer: ComposableTargetAnnotationsTransformer
) {
/**
* The name of the function. This is only supplied for debugging.
*/
abstract val name: String
/**
* Can the scheme be updated. If not, tell inference not to track it.
*/
abstract val schemeIsUpdatable: Boolean
/**
* Record a scheme for the function in metrics (if applicable).
*/
open fun recordScheme(scheme: Scheme) { }
/**
* The scheme has changed so the corresponding attributes should be updated to match the
* scheme provided.
*/
abstract fun updateScheme(scheme: Scheme)
/**
* Return a declared scheme for the function.
*/
abstract fun toDeclaredScheme(defaultTarget: Item = Open(0)): Scheme
/**
* Return true if this is a type with overly wide parameter types such as Any or
* unconstrained or insufficiently constrained type parameters.
*/
open fun isOverlyWide(): Boolean = false
/**
* Helper routine to produce an updated annotations list.
*/
fun updatedAnnotations(annotations: List<IrConstructorCall>, target: Item) =
transformer.updatedAnnotations(annotations, target)
/**
* Helper routine to produce an updated annotations list.
*/
fun updatedAnnotations(annotations: List<IrConstructorCall>, scheme: Scheme) =
transformer.updatedAnnotations(annotations, scheme)
}
/**
* An [InferenceFunctionDeclaration] refers to the type implied by a function declaration.
*
* Storing [Scheme] information is complicated by the current IR transformer limitation that
* annotations added to types are not serialized. Instead of updating the parameter types
* directly (for example adding a annotation to the IrType of the parameter declaration) the
* [Scheme] is serialized into a string and stored on the function declaration.
*/
class InferenceFunctionDeclaration(
transformer: ComposableTargetAnnotationsTransformer,
val function: IrFunction
) : InferenceFunction(transformer) {
override val name: String get() = function.name.toString()
override val schemeIsUpdatable: Boolean get() = true
override fun recordScheme(scheme: Scheme) {
if (!scheme.allAnonymous()) {
with(transformer) {
metricsFor(function).recordScheme(scheme.toString())
}
}
}
override fun updateScheme(scheme: Scheme) {
if (scheme.shouldSerialize) {
function.annotations = updatedAnnotations(function.annotations, scheme)
} else {
function.annotations = updatedAnnotations(function.annotations, scheme.target)
parameters().zip(scheme.parameters) { parameter, parameterScheme ->
parameter.updateScheme(parameterScheme)
}
}
}
override fun toDeclaredScheme(defaultTarget: Item): Scheme = with(transformer) {
function.scheme ?: function.toScheme(defaultTarget)
}
private fun IrFunction.toScheme(defaultTarget: Item): Scheme = with(transformer) {
val target = function.annotations.target.let { target ->
if (target.isUnspecified && function.body == null) {
defaultTarget
} else if (target.isUnspecified) {
// Default to the target specified at the file scope, if one.
function.file.annotations.target
} else target
}
val effectiveDefault =
if (function.body == null) defaultTarget
else Open(-1, isUnspecified = true)
val result = function.returnType.let { resultType ->
if (resultType.isOrHasComposableLambda)
resultType.toScheme(effectiveDefault)
else null
}
Scheme(
target,
parameters().map { it.toDeclaredScheme(effectiveDefault) },
result
).let { scheme ->
ancestorScheme(defaultTarget)?.let { scheme.mergeWith(listOf(it)) } ?: scheme
}
}
private fun IrFunction.ancestorScheme(defaultTarget: Item): Scheme? =
if (this is IrSimpleFunction && this.overriddenSymbols.isNotEmpty()) {
getLastOverridden().toScheme(defaultTarget)
} else null
override fun hashCode(): Int = function.hashCode() * 31
override fun equals(other: Any?) =
other is InferenceFunctionDeclaration && other.function == function
private fun parameters(): List<InferenceFunction> =
with(transformer) {
function.valueParameters.filter { it.type.isOrHasComposableLambda }.map { parameter ->
InferenceFunctionParameter(transformer, parameter)
}.let { parameters ->
function.extensionReceiverParameter?.let {
if (it.type.isOrHasComposableLambda) {
parameters + listOf(InferenceFunctionParameter(transformer, it))
} else parameters
} ?: parameters
}
}
private val Scheme.shouldSerialize get(): Boolean = parameters.isNotEmpty()
private fun Scheme.allAnonymous(): Boolean = target.isAnonymous &&
(result == null || result.allAnonymous()) &&
parameters.all { it.allAnonymous() }
}
/**
* An [InferenceFunctionCallType] is the type abstraction for a call. This is used for [IrCall]
* because it has the substituted types for generic types and the function's symbol has the original
* unsubstituted types. It is important, for example for calls to [let], that the arguments
* and result are after generic resolution so calls like `content?.let { it.invoke() }` correctly
* infer that the scheme is `[0[0]]` if `content` is a of type `(@Composable () -> Unit)?. This
* can only be determined after the generic parameters have been substituted.
*/
class InferenceFunctionCallType(
transformer: ComposableTargetAnnotationsTransformer,
private val call: IrCall
) : InferenceFunction(transformer) {
override val name: String get() = "Call(${call.symbol.owner.name})"
override val schemeIsUpdatable: Boolean get() = false
override fun toDeclaredScheme(defaultTarget: Item): Scheme =
with(transformer) {
val target = call.symbol.owner.annotations.target.let { target ->
if (target.isUnspecified) defaultTarget else target
}
val parameters = call.arguments.filterNotNull().filter {
it.type.isOrHasComposableLambda
}.map {
it.type.toScheme(defaultTarget)
}.toMutableList()
fun recordParameter(expression: IrExpression?) {
if (expression != null && expression.type.isOrHasComposableLambda) {
parameters.add(expression.type.toScheme(defaultTarget))
}
}
recordParameter(call.extensionReceiver)
val result = if (call.type.isOrHasComposableLambda)
call.type.toScheme(defaultTarget)
else null
Scheme(target, parameters, result)
}
override fun isOverlyWide(): Boolean =
call.symbol.owner.hasOverlyWideParameters()
override fun updateScheme(scheme: Scheme) {
// Ignore the updated scheme for the call as it can always be re-inferred.
}
}
/**
* Produce the scheme from a function type.
*/
class InferenceFunctionType(
transformer: ComposableTargetAnnotationsTransformer,
private val type: IrType
) : InferenceFunction(transformer) {
override val name: String get() = "<type>"
override val schemeIsUpdatable: Boolean get() = false
override fun toDeclaredScheme(defaultTarget: Item): Scheme = with(transformer) {
type.toScheme(defaultTarget)
}
override fun updateScheme(scheme: Scheme) {
// Cannot update the scheme of a type yet. This is worked around for parameters by recording
// the inferred scheme for the parameter in a serialized scheme for the function. For other
// types we don't need to record the inference we just need the declared scheme.
}
}
/**
* The type of a function parameter. The parameter of a function needs to update where it came from.
*/
class InferenceFunctionParameter(
transformer: ComposableTargetAnnotationsTransformer,
val parameter: IrValueParameter
) : InferenceFunction(transformer) {
override val name: String get() = "<parameter>"
override fun hashCode(): Int = parameter.hashCode() * 31
override fun equals(other: Any?) =
other is InferenceFunctionParameter && other.parameter == parameter
override val schemeIsUpdatable: Boolean get() = false
override fun toDeclaredScheme(defaultTarget: Item): Scheme = with(transformer) {
val samAnnotations = parameter.type.samOwnerOrNull()?.annotations ?: emptyList()
val annotations = parameter.type.annotations + samAnnotations
val target = annotations.target.let { if (it.isUnspecified) defaultTarget else it }
parameter.type.toScheme(target)
}
override fun updateScheme(scheme: Scheme) {
// Note that this is currently not called. Type annotations are serialized into an
// ComposableInferredAnnotation. This is kept here as example of how the type should
// be updated once such a modification is correctly serialized by Kotlin.
val type = parameter.type
if (type is IrSimpleType) {
val newType = type.toBuilder().apply {
annotations = updatedAnnotations(annotations, scheme.target)
}.buildSimpleType()
parameter.type = newType
}
}
}
/**
* A wrapper around IrElement to return the information requested by inference.
*/
sealed class InferenceNode {
/**
* The element being wrapped
*/
abstract val element: IrElement
/**
* The node kind of the node
*/
abstract val kind: NodeKind
/**
* The function type abstraction used by inference
*/
abstract val function: InferenceFunction?
/**
* The container node being referred to by the this node, if there is one. For example, if this
* is a parameter reference then this is the function that contains the parameter (which
* parameterIndex can be used to determine the parameter index). If it is a call to a static
* function then the reference is to the IrFunction that is being called.
*/
open val referenceContainer: InferenceNode? = null
/**
* [node] is one of the parameters of this container node then return its index. -1 indicates
* that [node] is not a parameter of this container (or this is not a container).
*/
open fun parameterIndex(node: InferenceNode): Int = -1
/**
* An overly wide function (a function with Any types) is too wide to use for to infer an
* applier (that is it contains parameters of type Any or Any?).
*/
open fun isOverlyWide(): Boolean = function?.isOverlyWide() == true
override fun hashCode() = element.hashCode() * 31
override fun equals(other: Any?) = other is InferenceNode && other.element == element
}
val IrSimpleFunctionSymbol.isGenericFunction get(): Boolean =
owner.typeParameters.isNotEmpty() || owner.dispatchReceiverParameter?.type?.let {
it is IrSimpleType && it.arguments.isNotEmpty()
} == true
/**
* An [InferenceCallTargetNode] is a wrapper around an [IrCall] which represents the target of
* the call, not the call itself. That its type is the type of the target of the call not the
* result of the call.
*/
class InferenceCallTargetNode(
private val transformer: ComposableTargetAnnotationsTransformer,
override val element: IrCall
) : InferenceNode() {
override fun equals(other: Any?): Boolean =
other is InferenceCallTargetNode && super.equals(other)
override fun hashCode(): Int = super.hashCode() * 31
override val kind: NodeKind get() = NodeKind.Function
override val function = with(transformer) {
if (element.symbol.owner.hasSchemeSpecified())
InferenceFunctionDeclaration(transformer, element.symbol.owner)
else InferenceFunctionCallType(transformer, element)
}
override val referenceContainer: InferenceNode? =
// If this is a generic function then don't redirect the scheme to the declaration
if (element.symbol.isGenericFunction) null else
with(transformer) {
val function = when {
element.isComposableSingletonGetter() ->
// If this was a lambda transformed into a singleton, find the singleton function
element.singletonFunctionExpression().function
element.hasTransformedLambda() ->
// If this is a normal lambda, find the lambda's IrFunction
element.transformedLambda().function
else -> element.symbol.owner
}
// If this is a call to a non-generic function with a body (e.g. non-abstract), return its
// function. Generic or abstract functions (interface members, lambdas, open methods, etc.)
// do not contain a body to infer anything from so we just use the declared scheme if
// there is one. Returning null from this function cause the scheme to be determined from
// the target expression (using, for example, the substituted type parameters) instead of
// the definition.
function.takeIf { it.body != null && it.typeParameters.isEmpty() }?.let {
inferenceNodeOf(function, transformer)
}
}
}
/**
* A node representing a variable declaration.
*/
class InferenceVariable(
private val transformer: ComposableTargetAnnotationsTransformer,
override val element: IrVariable,
) : InferenceNode() {
override val kind: NodeKind get() = NodeKind.Variable
override val function: InferenceFunction get() =
transformer.inferenceFunctionTypeOf(element.type)
override val referenceContainer: InferenceNode? get() = null
}
fun inferenceNodeOf(
element: IrElement,
transformer: ComposableTargetAnnotationsTransformer
): InferenceNode =
when (element) {
is IrFunction -> InferenceFunctionDeclarationNode(transformer, element)
is IrFunctionExpression -> InferenceFunctionExpressionNode(transformer, element)
is IrTypeOperatorCall -> inferenceNodeOf(element.argument, transformer)
is IrCall -> InferenceCallExpression(transformer, element)
is IrExpression -> InferenceElementExpression(transformer, element)
else -> InferenceUnknownElement(element)
}
/**
* A node wrapper for function declarations.
*/
class InferenceFunctionDeclarationNode(
transformer: ComposableTargetAnnotationsTransformer,
override val element: IrFunction
) : InferenceNode() {
override val kind: NodeKind get() = NodeKind.Function
override val function: InferenceFunction = transformer.inferenceFunctionOf(element)
override val referenceContainer: InferenceNode?
get() = this.takeIf { element.body != null }
}
/**
* A node wrapper for function expressions (i.e. lambdas).
*/
class InferenceFunctionExpressionNode(
private val transformer: ComposableTargetAnnotationsTransformer,
override val element: IrFunctionExpression
) : InferenceNode() {
override val kind: NodeKind get() = NodeKind.Lambda
override val function: InferenceFunction = transformer.inferenceFunctionOf(element.function)
override val referenceContainer: InferenceNode
get() = inferenceNodeOf(element.function, transformer)
}
/**
* A node wrapper for a call. This represents the result of a call. Use [InferenceCallTargetNode]
* to represent the target of a call.
*/
class InferenceCallExpression(
private val transformer: ComposableTargetAnnotationsTransformer,
override val element: IrCall
) : InferenceNode() {
private val isSingletonLambda = with(transformer) { element.isComposableSingletonGetter() }
private val isTransformedLambda = with(transformer) { element.hasTransformedLambda() }
override val kind: NodeKind get() =
if (isSingletonLambda || isTransformedLambda) NodeKind.Lambda else NodeKind.Expression
override val function: InferenceFunction = with(transformer) {
when {
isSingletonLambda ->
inferenceFunctionOf(element.singletonFunctionExpression().function)
isTransformedLambda ->
inferenceFunctionOf(element.transformedLambda().function)
else -> transformer.inferenceFunctionTypeOf(element.type)
}
}
override val referenceContainer: InferenceNode?
get() = with(transformer) {
when {
isSingletonLambda ->
inferenceNodeOf(element.singletonFunctionExpression().function, transformer)
isTransformedLambda ->
inferenceNodeOf(element.transformedLambda().function, transformer)
else -> null
}
}
}
/**
* An expression node whose scheme is determined by the type of the node.
*/
class InferenceElementExpression(
transformer: ComposableTargetAnnotationsTransformer,
override val element: IrExpression,
) : InferenceNode() {
override val kind: NodeKind get() = NodeKind.Expression
override val function: InferenceFunction = transformer.inferenceFunctionTypeOf(element.type)
}
/**
* An [InferenceUnknownElement] is a general wrapper around function declarations and lambda.
*/
class InferenceUnknownElement(
override val element: IrElement,
) : InferenceNode() {
override val kind: NodeKind get() = NodeKind.Expression
override val function: InferenceFunction? get() = null
override val referenceContainer: InferenceNode? get() = null
}
/**
* An [InferenceResolvedParameter] is a node that references a parameter of a container of this
* node. For example, if the parameter is captured by a nested lambda this is resolved to the
* captured parameter.
*/
class InferenceResolvedParameter(
override val element: IrGetValue,
override val function: InferenceFunction,
val container: InferenceNode,
val index: Int
) : InferenceNode() {
override val kind: NodeKind get() = NodeKind.ParameterReference
override fun parameterIndex(node: InferenceNode): Int =
if (node.function == function) index else -1
override val referenceContainer: InferenceNode get() = container
override fun equals(other: Any?): Boolean =
other is InferenceResolvedParameter && other.element == element
override fun hashCode(): Int = element.hashCode() * 31 + 103
}
private inline fun <reified T> IrConstructorCall.firstParameterOrNull() =
if (valueArgumentsCount >= 1) {
(getValueArgument(0) as? IrConst<*>)?.value as? T
} else null
private val IrConstructorCall.isComposableTarget get() =
annotationClass?.isClassWithFqName(
ComposeFqNames.ComposableTarget.toUnsafe()
) == true
private val IrConstructorCall.isComposableTargetMarked: Boolean get() =
annotationClass?.owner?.annotations?.hasAnnotation(
ComposeFqNames.ComposableTargetMarker
) == true
private val IrConstructorCall.isComposableInferredTarget get() =
annotationClass?.isClassWithFqName(
ComposeFqNames.ComposableInferredTarget.toUnsafe()
) == true
private val IrConstructorCall.isComposableOpenTarget get() =
annotationClass?.isClassWithFqName(
ComposeFqNames.ComposableOpenTarget.toUnsafe()
) == true
private fun IrType.samOwnerOrNull() =
classOrNull?.let { cls ->
if (cls.owner.kind == ClassKind.INTERFACE) {
cls.functions.singleOrNull {
it.owner.modality == Modality.ABSTRACT
}?.owner
} else null
}
private val IrCall.arguments get() = Array(valueArgumentsCount) {
getValueArgument(it)
}.toList()
private fun <T> Iterable<T>.takeUpTo(n: Int): List<T> =
if (n <= 0) emptyList() else take(n)
/**
* A function with overly wide parameters should be ignored for traversal as well as when
* it is called.
*/
private fun IrFunction.hasOverlyWideParameters(): Boolean =
valueParameters.any {
it.type.isAny() || it.type.isNullableAny()
}
private fun IrFunction.hasOpenTypeParameters(): Boolean =
valueParameters.any { it.type.isTypeParameter() } ||
dispatchReceiverParameter?.type?.isTypeParameter() == true ||
extensionReceiverParameter?.type?.isTypeParameter() == true
| apache-2.0 | d21e997bfd426720f3c9b7e0bc145970 | 40.236627 | 103 | 0.669158 | 5.332239 | false | false | false | false |
AndroidX/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/snapping/LazyListSnapLayoutInfoProvider.kt | 3 | 5133 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.gestures.snapping
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.core.calculateTargetValue
import androidx.compose.animation.splineBasedDecay
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.FlingBehavior
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.lazy.LazyListItemInfo
import androidx.compose.foundation.lazy.LazyListLayoutInfo
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.unit.Density
import androidx.compose.ui.util.fastForEach
import androidx.compose.ui.util.fastSumBy
import kotlin.math.absoluteValue
import kotlin.math.sign
/**
* A [SnapLayoutInfoProvider] for LazyLists.
*
* @param lazyListState The [LazyListState] with information about the current state of the list
* @param positionInLayout The desired positioning of the snapped item within the main layout.
* This position should be considered with regard to the start edge of the item and the placement
* within the viewport.
*
* @return A [SnapLayoutInfoProvider] that can be used with [SnapFlingBehavior]
*/
@ExperimentalFoundationApi
fun SnapLayoutInfoProvider(
lazyListState: LazyListState,
positionInLayout: Density.(layoutSize: Float, itemSize: Float) -> Float =
{ layoutSize, itemSize -> (layoutSize / 2f - itemSize / 2f) }
): SnapLayoutInfoProvider = object : SnapLayoutInfoProvider {
private val layoutInfo: LazyListLayoutInfo
get() = lazyListState.layoutInfo
// Decayed page snapping is the default
override fun Density.calculateApproachOffset(initialVelocity: Float): Float {
val decayAnimationSpec: DecayAnimationSpec<Float> = splineBasedDecay(this)
val offset =
decayAnimationSpec.calculateTargetValue(NoDistance, initialVelocity).absoluteValue
val finalDecayOffset = (offset - calculateSnapStepSize()).coerceAtLeast(0f)
return if (finalDecayOffset == 0f) {
finalDecayOffset
} else {
finalDecayOffset * initialVelocity.sign
}
}
override fun Density.calculateSnappingOffsetBounds(): ClosedFloatingPointRange<Float> {
var lowerBoundOffset = Float.NEGATIVE_INFINITY
var upperBoundOffset = Float.POSITIVE_INFINITY
layoutInfo.visibleItemsInfo.fastForEach { item ->
val offset =
calculateDistanceToDesiredSnapPosition(layoutInfo, item, positionInLayout)
// Find item that is closest to the center
if (offset <= 0 && offset > lowerBoundOffset) {
lowerBoundOffset = offset
}
// Find item that is closest to center, but after it
if (offset >= 0 && offset < upperBoundOffset) {
upperBoundOffset = offset
}
}
return lowerBoundOffset.rangeTo(upperBoundOffset)
}
override fun Density.calculateSnapStepSize(): Float = with(layoutInfo) {
if (visibleItemsInfo.isNotEmpty()) {
visibleItemsInfo.fastSumBy { it.size } / visibleItemsInfo.size.toFloat()
} else {
0f
}
}
}
/**
* Create and remember a FlingBehavior for decayed snapping in Lazy Lists. This will snap
* the item's center to the center of the viewport.
*
* @param lazyListState The [LazyListState] from the LazyList where this [FlingBehavior] will
* be used.
*/
@ExperimentalFoundationApi
@Composable
fun rememberSnapFlingBehavior(lazyListState: LazyListState): FlingBehavior {
val snappingLayout = remember(lazyListState) { SnapLayoutInfoProvider(lazyListState) }
return rememberSnapFlingBehavior(snappingLayout)
}
internal fun Density.calculateDistanceToDesiredSnapPosition(
layoutInfo: LazyListLayoutInfo,
item: LazyListItemInfo,
positionInLayout: Density.(layoutSize: Float, itemSize: Float) -> Float
): Float {
val containerSize =
with(layoutInfo) { singleAxisViewportSize - beforeContentPadding - afterContentPadding }
val desiredDistance =
positionInLayout(containerSize.toFloat(), item.size.toFloat())
val itemCurrentPosition = item.offset
return itemCurrentPosition - desiredDistance
}
private val LazyListLayoutInfo.singleAxisViewportSize: Int
get() = if (orientation == Orientation.Vertical) viewportSize.height else viewportSize.width | apache-2.0 | 315a64319a75fedc7471a21a061f0936 | 38.492308 | 97 | 0.740308 | 5.007805 | false | false | false | false |
JoachimR/Bible2net | app/src/main/java/de/reiss/bible2net/theword/note/details/NoteDetailsActivity.kt | 1 | 1673 | package de.reiss.bible2net.theword.note.details
import android.content.Context
import android.content.Intent
import android.os.Bundle
import de.reiss.bible2net.theword.R
import de.reiss.bible2net.theword.architecture.AppActivity
import de.reiss.bible2net.theword.databinding.NoteDetailsActivityBinding
import de.reiss.bible2net.theword.model.Note
import de.reiss.bible2net.theword.util.extensions.findFragmentIn
import de.reiss.bible2net.theword.util.extensions.replaceFragmentIn
class NoteDetailsActivity : AppActivity(), ConfirmDeleteDialog.Listener {
companion object {
private const val KEY_NOTE = "KEY_NOTE"
fun createIntent(context: Context, note: Note): Intent =
Intent(context, NoteDetailsActivity::class.java)
.putExtra(KEY_NOTE, note)
}
private lateinit var binding: NoteDetailsActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = NoteDetailsActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.noteDetailsToolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (findNoteDetailsFragment() == null) {
replaceFragmentIn(
container = R.id.note_details_fragment,
fragment = NoteDetailsFragment.createInstance(intent.getParcelableExtra(KEY_NOTE)!!)
)
}
}
override fun onDeleteConfirmed() {
findNoteDetailsFragment()?.tryDeleteNote()
}
private fun findNoteDetailsFragment() =
findFragmentIn(R.id.note_details_fragment) as? NoteDetailsFragment
}
| gpl-3.0 | 673dcc947d232be952c310703b1c2ced | 35.369565 | 100 | 0.731022 | 4.725989 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/os/PathResolver.kt | 1 | 2389 | /*
Copyright 2017-2020 Charles Korn.
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 batect.os
import java.nio.file.Files
import java.nio.file.InvalidPathException
import java.nio.file.Path
import java.util.Properties
data class PathResolver(val relativeTo: Path, private val systemProperties: Properties = System.getProperties()) {
private val homeDir = getPath(systemProperties.getProperty("user.home"))
fun resolve(path: String): PathResolutionResult {
try {
val originalPath = resolveHomeDir(getPath(path))
val resolvedPath = relativeTo.resolve(originalPath).normalize().toAbsolutePath()
return PathResolutionResult.Resolved(path, resolvedPath, pathType(resolvedPath))
} catch (e: InvalidPathException) {
return PathResolutionResult.InvalidPath(path)
}
}
private fun getPath(path: String): Path = relativeTo.fileSystem.getPath(path)
private fun resolveHomeDir(path: Path): Path {
val homeSymbol = getPath("~")
if (path.startsWith(homeSymbol)) {
return homeDir.resolve(homeSymbol.relativize(path))
} else {
return path
}
}
private fun pathType(path: Path): PathType {
return when {
!Files.exists(path) -> PathType.DoesNotExist
Files.isRegularFile(path) -> PathType.File
Files.isDirectory(path) -> PathType.Directory
else -> PathType.Other
}
}
}
sealed class PathResolutionResult(open val originalPath: String) {
data class Resolved(override val originalPath: String, val absolutePath: Path, val pathType: PathType) : PathResolutionResult(originalPath)
data class InvalidPath(override val originalPath: String) : PathResolutionResult(originalPath)
}
enum class PathType {
DoesNotExist,
File,
Directory,
Other
}
| apache-2.0 | 474c7ecac0627f6e5f1d2e07d574424d | 33.623188 | 143 | 0.699456 | 4.826263 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/logging/FileLogSinkSpec.kt | 1 | 3475 | /*
Copyright 2017-2020 Charles Korn.
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 batect.logging
import batect.testutils.on
import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import kotlinx.serialization.internal.BooleanSerializer
import kotlinx.serialization.internal.IntSerializer
import kotlinx.serialization.internal.StringSerializer
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.OutputStream
import java.io.PrintStream
import java.nio.file.Files
import java.time.ZoneOffset
import java.time.ZonedDateTime
object FileLogSinkSpec : Spek({
describe("a file log sink") {
val fileSystem = Jimfs.newFileSystem(Configuration.unix())
val path = fileSystem.getPath("/someLogFile.log")
val writer = mock<LogMessageWriter> {
on { writeTo(any(), any()) } doAnswer { invocation ->
val outputStream = invocation.arguments[1] as OutputStream
PrintStream(outputStream).print("The value written by the writer")
null
}
}
val standardAdditionalDataSource = mock<StandardAdditionalDataSource> {
on { getAdditionalData() } doReturn mapOf("someStandardInfo" to JsonableObject(false, BooleanSerializer))
}
val timestampToUse = ZonedDateTime.of(2017, 9, 25, 15, 51, 0, 0, ZoneOffset.UTC)
val timestampSource = { timestampToUse }
val sink = FileLogSink(path, writer, standardAdditionalDataSource, timestampSource)
on("writing a log message") {
sink.write(Severity.Info, mapOf("someAdditionalInfo" to JsonableObject("someValue", StringSerializer))) {
message("This is the message")
data("someLocalInfo", 888)
}
val expectedMessage = LogMessage(Severity.Info, "This is the message", timestampToUse, mapOf(
"someAdditionalInfo" to JsonableObject("someValue", StringSerializer),
"someLocalInfo" to JsonableObject(888, IntSerializer),
"someStandardInfo" to JsonableObject(false, BooleanSerializer)
))
it("calls the builder function to create the log message and passes it to the writer") {
verify(writer).writeTo(eq(expectedMessage), any())
}
it("passes a stream to the writer that writes to the path provided") {
val content = String(Files.readAllBytes(path))
assertThat(content, equalTo("The value written by the writer"))
}
}
}
})
| apache-2.0 | ab1b42725a0622c46802a7c8b29e9943 | 39.882353 | 117 | 0.702158 | 4.773352 | false | false | false | false |
androidx/androidx | room/room-common/src/main/java/androidx/room/RoomWarnings.kt | 3 | 9168 | /*
* Copyright (C) 2017 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.room
/**
* The list of warnings that are produced by Room.
*
* You can use these values inside a [SuppressWarnings] annotation to disable the warnings.
*/
// If you change this, don't forget to change androidx.room.vo.Warning
@SuppressWarnings("unused", "WeakerAccess")
public open class RoomWarnings {
public companion object {
/**
* The warning dispatched by Room when the return value of a [Query] method does not
* exactly match the fields in the query result.
*/
public const val CURSOR_MISMATCH: String = "ROOM_CURSOR_MISMATCH"
/**
* The warning dispatched by Room when the object in the provided method's multimap return
* type does not implement equals() and hashCode().
*/
public const val DOES_NOT_IMPLEMENT_EQUALS_HASHCODE: String =
"ROOM_TYPE_DOES_NOT_IMPLEMENT_EQUALS_HASHCODE"
/**
* Reported when Room cannot verify database queries during compilation due to lack of
* tmp dir access in JVM.
*/
public const val MISSING_JAVA_TMP_DIR: String = "ROOM_MISSING_JAVA_TMP_DIR"
/**
* Reported when Room cannot verify database queries during compilation. This usually
* happens when it cannot find the SQLite JDBC driver on the host machine.
*
* Room can function without query verification but its functionality will be limited.
*/
public const val CANNOT_CREATE_VERIFICATION_DATABASE: String =
"ROOM_CANNOT_CREATE_VERIFICATION_DATABASE"
/**
* Reported when an [Entity] field that is annotated with [Embedded] has a
* sub field which is annotated with [PrimaryKey] but the [PrimaryKey] is dropped
* while composing it into the parent object.
*/
public const val PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED: String =
"ROOM_EMBEDDED_PRIMARY_KEY_IS_DROPPED"
/**
* Reported when an [Entity] field that is annotated with [Embedded] has a
* sub field which has a [ColumnInfo] annotation with `index = true`.
*
* You can re-define the index in the containing [Entity].
*/
public const val INDEX_FROM_EMBEDDED_FIELD_IS_DROPPED: String =
"ROOM_EMBEDDED_INDEX_IS_DROPPED"
/**
* Reported when an [Entity] that has a [Embedded] field whose type is another
* [Entity] and that [Entity] has some indices defined.
* These indices will NOT be created in the containing [Entity]. If you want to preserve
* them, you can re-define them in the containing [Entity].
*/
public const val INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED: String =
"ROOM_EMBEDDED_ENTITY_INDEX_IS_DROPPED"
/**
* Reported when an [Entity]'s parent declares an [Index]. Room does not
* automatically inherit these indices to avoid hidden costs or unexpected constraints.
*
* If you want your child class to have the indices of the parent, you must re-declare
* them in the child class. Alternatively, you can set [Entity.inheritSuperIndices]
* to `true`.
*/
public const val INDEX_FROM_PARENT_IS_DROPPED: String =
"ROOM_PARENT_INDEX_IS_DROPPED"
/**
* Reported when an [Entity] inherits a field from its super class and the field has a
* [ColumnInfo] annotation with `index = true`.
*
* These indices are dropped for the [Entity] and you would need to re-declare them if
* you want to keep them. Alternatively, you can set [Entity.inheritSuperIndices]
* to `true`.
*/
public const val INDEX_FROM_PARENT_FIELD_IS_DROPPED: String =
"ROOM_PARENT_FIELD_INDEX_IS_DROPPED"
/**
* Reported when a [Relation] [Entity]'s SQLite column type does not match the type
* in the parent. Room will still do the matching using `String` representations.
*/
public const val RELATION_TYPE_MISMATCH: String = "ROOM_RELATION_TYPE_MISMATCH"
/**
* Reported when a `room.schemaLocation` argument is not provided into the annotation
* processor.
* You can either set [Database.exportSchema] to `false` or provide
* `room.schemaLocation` to the annotation processor. You are strongly advised to provide it
* and also commit them into your version control system.
*/
public const val MISSING_SCHEMA_LOCATION: String = "ROOM_MISSING_SCHEMA_LOCATION"
/**
* When there is a foreign key from Entity A to Entity B, it is a good idea to index the
* reference columns in B, otherwise, each modification on Entity A will trigger a full table
* scan on Entity B.
*
* If Room cannot find a proper index in the child entity (Entity B in this case), Room will
* print this warning.
*/
public const val MISSING_INDEX_ON_FOREIGN_KEY_CHILD: String =
"ROOM_MISSING_FOREIGN_KEY_CHILD_INDEX"
/**
* Reported when a junction entity whose column is used in a `@Relation` field with a
* `@Junction` does not contain an index. If the column is not covered by any index then a
* full table scan might be performed when resolving the relationship.
*
* It is recommended that columns on entities used as junctions contain indices, otherwise Room
* will print this warning.
*/
public const val MISSING_INDEX_ON_JUNCTION: String = "MISSING_INDEX_ON_JUNCTION"
/**
* Reported when a POJO has multiple constructors, one of which is a no-arg constructor. Room
* will pick that one by default but will print this warning in case the constructor choice is
* important. You can always guide Room to use the right constructor using the @Ignore
* annotation.
*/
public const val DEFAULT_CONSTRUCTOR: String = "ROOM_DEFAULT_CONSTRUCTOR"
/**
* Reported when a @Query method returns a POJO that has relations but the method is not
* annotated with @Transaction. Relations are run as separate queries and if the query is not
* run inside a transaction, it might return inconsistent results from the database.
*/
public const val RELATION_QUERY_WITHOUT_TRANSACTION: String =
"ROOM_RELATION_QUERY_WITHOUT_TRANSACTION"
/**
* Reported when an `@Entity` field's type do not exactly match the getter type.
* For instance, in the following class:
*
* ```
* @Entity
* class Foo {
* ...
* private val value: Boolean
* public fun getValue(): Boolean {
* return value == null ? false : value
* }
* }
* ```
*
* Trying to insert this entity into database will always set `value` column to
* `false` when `Foo.value` is `null` since Room will use the `getValue`
* method to read the value. So even thought the database column is nullable, it will never
* be inserted as `null` if inserted as a `Foo` instance.
*/
public const val MISMATCHED_GETTER: String = "ROOM_MISMATCHED_GETTER_TYPE"
/**
* Reported when an `@Entity` field's type do not exactly match the setter type.
* For instance, in the following class:
*
* ```
* @Entity
* class Foo {
* ...
* private val value: Boolean
* public fun setValue(value: Boolean) {
* this.value = value
* }
* }
* ```
*
* If Room reads this entity from the database, it will always set `Foo.value` to
* `false` when the column value is `null` since Room will use the `setValue`
* method to write the value.
*/
public const val MISMATCHED_SETTER: String = "ROOM_MISMATCHED_SETTER_TYPE"
/**
* Reported when there is an ambiguous column on the result of a multimap query.
*/
public const val AMBIGUOUS_COLUMN_IN_RESULT: String = "ROOM_AMBIGUOUS_COLUMN_IN_RESULT"
}
@Deprecated("This type should not be instantiated as it contains only static methods. ")
@SuppressWarnings("PrivateConstructorForUtilityClass")
public constructor()
}
| apache-2.0 | 75a2d5dadda7cb457cb8a69a00e569dc | 43.289855 | 103 | 0.628163 | 4.665649 | false | false | false | false |
yuncheolkim/gitmt | src/main/kotlin/com/joyouskim/http/HttpExtension.kt | 1 | 1210 | package com.joyouskim.http
import com.joyouskim.git.VertOutputStream
import java.io.IOException
import java.io.OutputStream
/**
* Created by jinyunzhe on 16/4/6.
*/
fun HttpRequest.consumeBody() {
val header = this.getHeader(CONTENT_LENGTH)
if ( 0 < this.getContentLength() || this.isChunked()) {
val inputStream = this.getInputStream()
try {
while (0 < inputStream.skip(2048) || 0 <= inputStream.read()) {
}
} catch(e: IOException) {
} finally {
try {
inputStream.close()
} catch(e: IOException) {
}
}
}
}
fun HttpRequest.isChunked(): Boolean {
return "chunked" == this.getHeader(TRANSFER_ENCODING)
}
fun HttpRequest.getRemoteHost(): String {
return this.remoteAddress().host()
}
fun HttpRequest.getContentType(): String {
return this.getHeader(CONTENT_TYPE)
}
fun HttpResponse.setContentType(str: String) {
this.putHeader(CONTENT_TYPE, str)
}
fun HttpRequest.getContentLength(): Int {
return this.getHeader(CONTENT_LENGTH)?.toInt() ?: 0
}
fun HttpResponse.getOut(): OutputStream {
return VertOutputStream(this)
}
fun HttpResponse.reset(){
}
| mit | f195a8840ca2632027f560dfb8c52f69 | 20.607143 | 75 | 0.639669 | 3.865815 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/data/converter/DatabaseConverterController.kt | 1 | 6358 | /*
* Copyright (c) 2013 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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 MyDatabaseConverterExecutor 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.andstatus.app.data.converter
import android.app.Activity
import org.andstatus.app.backup.ProgressLogger
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.Taggable
import java.util.concurrent.TimeUnit
object DatabaseConverterController {
val TAG: String = DatabaseConverterController::class.simpleName!!
// TODO: Should be one object for atomic updates. start ---
internal val upgradeLock: Any = Any()
@Volatile
internal var shouldTriggerDatabaseUpgrade = false
/** Semaphore enabling uninterrupted system upgrade */
internal var upgradeEndTime = 0L
internal var upgradeStarted = false
private var upgradeEnded = false
internal var upgradeEndedSuccessfully = false
@Volatile
internal var mProgressLogger: ProgressLogger = ProgressLogger.getEmpty(TAG)
// end ---
private const val SECONDS_BEFORE_UPGRADE_TRIGGERED = 5L
private const val UPGRADE_LENGTH_SECONDS_MAX = 90
fun onUpgrade(upgradeParams: DatabaseUpgradeParams) {
if (!shouldTriggerDatabaseUpgrade) {
MyLog.v(this, "onUpgrade - Trigger not set yet")
throw IllegalStateException("onUpgrade - Trigger not set yet")
}
synchronized(upgradeLock) {
shouldTriggerDatabaseUpgrade = false
stillUpgrading()
}
MyContextHolder.myContextHolder.getNow().isInForeground = true
val databaseConverter = DatabaseConverter(mProgressLogger)
val success = databaseConverter.execute(upgradeParams)
synchronized(upgradeLock) {
upgradeEnded = true
upgradeEndedSuccessfully = success
}
if (!success) {
throw ApplicationUpgradeException(databaseConverter.converterError)
}
}
fun attemptToTriggerDatabaseUpgrade(upgradeRequestorIn: Activity) {
val requestorName: String = Taggable.anyToTag(upgradeRequestorIn)
var skip = false
if (isUpgrading()) {
MyLog.v(
TAG, "Attempt to trigger database upgrade by " + requestorName
+ ": already upgrading"
)
skip = true
}
if (!skip && !MyContextHolder.myContextHolder.getNow().initialized) {
MyLog.v(
TAG, "Attempt to trigger database upgrade by " + requestorName
+ ": not initialized yet"
)
skip = true
}
if (!skip && acquireUpgradeLock(requestorName)) {
val asyncUpgrade = AsyncUpgrade(upgradeRequestorIn, MyContextHolder.myContextHolder.isOnRestore())
if (MyContextHolder.myContextHolder.isOnRestore()) {
asyncUpgrade.syncUpgrade()
} else {
asyncUpgrade.execute(TAG, Unit)
}
}
}
private fun acquireUpgradeLock(requestorName: String?): Boolean {
var skip = false
synchronized(upgradeLock) {
if (isUpgrading()) {
MyLog.v(
TAG, "Attempt to trigger database upgrade by " + requestorName
+ ": already upgrading"
)
skip = true
}
if (!skip && upgradeEnded) {
MyLog.v(
TAG, "Attempt to trigger database upgrade by " + requestorName
+ ": already completed " + if (upgradeEndedSuccessfully) " successfully" else "(failed)"
)
skip = true
if (!upgradeEndedSuccessfully) {
upgradeEnded = false
}
}
if (!skip) {
MyLog.v(TAG, "Upgrade lock acquired for $requestorName")
val startTime = System.currentTimeMillis()
upgradeEndTime = startTime + TimeUnit.SECONDS.toMillis(SECONDS_BEFORE_UPGRADE_TRIGGERED)
shouldTriggerDatabaseUpgrade = true
}
}
return !skip
}
fun stillUpgrading() {
var wasStarted: Boolean
synchronized(upgradeLock) {
wasStarted = upgradeStarted
upgradeStarted = true
upgradeEndTime =
System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(UPGRADE_LENGTH_SECONDS_MAX.toLong())
}
MyLog.w(
TAG,
(if (wasStarted) "Still upgrading" else "Upgrade started") + ". Wait " + UPGRADE_LENGTH_SECONDS_MAX + " seconds"
)
}
fun isUpgradeError(): Boolean {
synchronized(upgradeLock) {
if (upgradeEnded && !upgradeEndedSuccessfully) {
return true
}
}
return false
}
fun isUpgrading(): Boolean {
synchronized(upgradeLock) {
if (upgradeEndTime == 0L) {
return false
}
val currentTime = System.currentTimeMillis()
if (currentTime > upgradeEndTime) {
MyLog.v(TAG, "Upgrade end time came")
upgradeEndTime = 0L
return false
}
}
return true
}
}
| apache-2.0 | 6c69ff177f1327d559f9b3fa497d2f59 | 38.246914 | 128 | 0.553161 | 5.738267 | false | false | false | false |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/ui/docviewer/documents/DocumentsFragment.kt | 1 | 3635 | package at.ac.tuwien.caa.docscan.ui.docviewer.documents
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import at.ac.tuwien.caa.docscan.databinding.FragmentDocumentsBinding
import at.ac.tuwien.caa.docscan.logic.ConsumableEvent
import at.ac.tuwien.caa.docscan.logic.DocumentPage
import at.ac.tuwien.caa.docscan.logic.extractDocWithPages
import at.ac.tuwien.caa.docscan.ui.base.BaseFragment
import at.ac.tuwien.caa.docscan.ui.dialog.ADialog
import at.ac.tuwien.caa.docscan.ui.dialog.DialogViewModel
import at.ac.tuwien.caa.docscan.ui.dialog.isPositive
import at.ac.tuwien.caa.docscan.ui.docviewer.DocumentViewerViewModel
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class DocumentsFragment : BaseFragment() {
private var scroll = true
private lateinit var adapter: DocumentAdapter
private lateinit var binding: FragmentDocumentsBinding
private val viewModel: DocumentsViewModel by viewModel()
private val dialogViewModel: DialogViewModel by viewModel()
private val sharedViewModel: DocumentViewerViewModel by sharedViewModel()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentDocumentsBinding.inflate(inflater, container, false)
adapter = DocumentAdapter({
findNavController().navigate(
DocumentsFragmentDirections.actionViewerDocumentsToViewerImages(
DocumentPage(
it.document.id,
null
)
)
)
}, {
sharedViewModel.initDocumentOptions(it)
})
binding.documentsList.adapter = adapter
binding.documentsList.layoutManager = LinearLayoutManager(context)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observe()
}
private fun observe() {
viewModel.observableDocuments.observe(viewLifecycleOwner) {
adapter.submitList(it)
if (it.isEmpty()) {
binding.documentsEmptyLayout.visibility = View.VISIBLE
binding.documentsList.visibility = View.INVISIBLE
} else {
binding.documentsList.visibility = View.VISIBLE
binding.documentsEmptyLayout.visibility = View.INVISIBLE
}
if (scroll) {
val position = (it.indexOfFirst { doc -> doc.document.isActive })
if (position != -1) {
binding.documentsList.smoothScrollToPosition(position)
}
scroll = false
}
}
dialogViewModel.observableDialogAction.observe(
viewLifecycleOwner,
ConsumableEvent { result ->
when (result.dialogAction) {
ADialog.DialogAction.CONFIRM_DELETE_DOCUMENT -> {
if (result.isPositive()) {
result.arguments.extractDocWithPages()?.let { doc ->
viewModel.deleteDocument(doc)
}
}
}
else -> {
// ignore
}
}
})
}
}
| lgpl-3.0 | 5df431cddfd31b2146ecad9bcb588c24 | 37.670213 | 81 | 0.628336 | 5.361357 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/android/upnp/cds/MsControlPoint.kt | 1 | 7010 | /*
* Copyright (c) 2016 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.android.upnp.cds
import net.mm2d.android.upnp.ControlPointWrapper
import net.mm2d.upnp.Adapter.discoveryListener
import net.mm2d.upnp.Adapter.eventListener
import net.mm2d.upnp.ControlPoint
import net.mm2d.upnp.Device
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
/**
* MediaServerのControlPoint機能。
*
* ControlPointは継承しておらず、MediaServerとしてのインターフェースのみを提供する。
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class MsControlPoint : ControlPointWrapper {
private val discoveryListener = discoveryListener(
{ discoverDevice(it) },
{ lostDevice(it) }
)
private val eventListener = eventListener { service, _, properties ->
val udn = service.device.udn
val server = getDevice(udn)
if (server == null || service.serviceId != Cds.CDS_SERVICE_ID) {
return@eventListener
}
properties.forEach {
if (it.first == Cds.CONTAINER_UPDATE_IDS) {
onNotifyContainerUpdateIds(server, it.second)
} else if (it.first == Cds.SYSTEM_UPDATE_ID) {
onNotifySystemUpdateId(server, it.second)
}
}
}
private val initialized = AtomicBoolean()
private val mediaServerMap: MutableMap<String, MediaServer> =
Collections.synchronizedMap(LinkedHashMap())
private var msDiscoveryListener: MsDiscoveryListener? = null
private var containerUpdateIdsListener: ContainerUpdateIdsListener? = null
private var systemUpdateIdListener: SystemUpdateIdListener? = null
/**
* 保持しているMediaServerの個数を返す。
*
* @return MediaServerの個数
*/
override val deviceListSize: Int
get() = mediaServerMap.size
/**
* MediaServerのリストを返す。
*
* 内部Mapのコピーを返すため使用注意。
*
* @return MediaServerのリスト。
*/
override val deviceList: List<MediaServer>
get() = synchronized(mediaServerMap) {
mediaServerMap.values.toList()
}
/**
* 機器発見のイベントを通知するリスナー。
*/
interface MsDiscoveryListener {
/**
* 機器発見時に通知される。
*
* @param server 発見したMediaServer
*/
fun onDiscover(server: MediaServer)
/**
* 機器喪失時に通知される。
*
* @param server 喪失したMediaServer
*/
fun onLost(server: MediaServer)
}
/**
* ContainerUpdateIDsのsubscribeイベントを通知するリスナー。
*/
interface ContainerUpdateIdsListener {
/**
* ContainerUpdateIDsが通知されたときにコールされる。
*
* @param server イベントを発行したMediaServer
* @param ids 更新のあったID
*/
fun onContainerUpdateIds(
server: MediaServer,
ids: List<String>
)
}
/**
* SystemUpdateIDのsubscribeイベントを通知するリスナー。
*/
interface SystemUpdateIdListener {
/**
* SystemUpdateIDが通知されたときにコールされる。
*
* @param server イベントを発行したMediaServer
* @param id UpdateID
*/
fun onSystemUpdateId(
server: MediaServer,
id: String
)
}
private fun onNotifyContainerUpdateIds(
server: MediaServer,
value: String
) {
containerUpdateIdsListener?.let { it ->
val values = value.split(',')
if (values.isEmpty() || values.size % 2 != 0) {
return
}
it.onContainerUpdateIds(server, values.chunked(2) { it[0] })
}
}
private fun onNotifySystemUpdateId(
server: MediaServer,
value: String
) {
systemUpdateIdListener?.onSystemUpdateId(server, value)
}
/**
* MediaServerのファクトリーメソッド。
*
* @param device Device
* @return MediaServer
*/
private fun createMediaServer(device: Device): MediaServer = MediaServer(device)
private fun discoverDevice(device: Device) {
if (device.deviceType.startsWith(Cds.MS_DEVICE_TYPE)) {
discoverMsDevice(device)
return
}
for (embeddedDevice in device.deviceList) {
discoverMsDevice(embeddedDevice)
}
}
private fun discoverMsDevice(device: Device) {
val server: MediaServer
try {
server = createMediaServer(device)
} catch (ignored: IllegalArgumentException) {
return
}
mediaServerMap[server.udn] = server
msDiscoveryListener?.onDiscover(server)
}
private fun lostDevice(device: Device) {
val server = mediaServerMap.remove(device.udn) ?: return
msDiscoveryListener?.onLost(server)
}
/**
* 機器発見の通知リスナーを登録する。
*
* @param listener リスナー
*/
fun setMsDiscoveryListener(listener: MsDiscoveryListener?) {
msDiscoveryListener = listener
}
/**
* ContainerUpdateIdsの通知リスナーを登録する。
*
* @param listener リスナー
*/
fun setContainerUpdateIdsListener(listener: ContainerUpdateIdsListener?) {
containerUpdateIdsListener = listener
}
/**
* SystemUpdateIdの通知リスナーを登録する。
*
* @param listener リスナー
*/
fun setSystemUpdateIdListener(listener: SystemUpdateIdListener) {
systemUpdateIdListener = listener
}
/**
* 指定UDNに対応したMediaServerを返す。
*
* @param udn UDN
* @return MediaServer、見つからない場合null
*/
override fun getDevice(udn: String?): MediaServer? {
return mediaServerMap[udn]
}
/**
* 初期化する。
*
* @param controlPoint ControlPoint
*/
override fun initialize(controlPoint: ControlPoint) {
if (initialized.get()) {
terminate(controlPoint)
}
initialized.set(true)
mediaServerMap.clear()
controlPoint.addDiscoveryListener(discoveryListener)
controlPoint.addEventListener(eventListener)
}
/**
* 終了する。
*
* @param controlPoint ControlPoint
*/
override fun terminate(controlPoint: ControlPoint) {
if (!initialized.getAndSet(false)) {
return
}
controlPoint.removeDiscoveryListener(discoveryListener)
controlPoint.removeEventListener(eventListener)
mediaServerMap.clear()
}
}
| mit | 554057291990ceaec426561a7de0e68b | 25.098361 | 84 | 0.610396 | 4.497175 | false | false | false | false |
elect86/jAssimp | src/main/kotlin/assimp/postProcess/TriangulateProcess.kt | 2 | 19127 | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
package assimp.postProcess
import assimp.*
import glm_.glm
import glm_.max
import glm_.vec2.Vec2
import glm_.vec3.Vec3
import kotlin.math.abs
import kotlin.math.acos
/** @file Defines a post processing step to triangulate all faces
with more than three vertices.
*/
/** The TriangulateProcess splits up all faces with more than three indices
* into triangles. You usually want this to happen because the graphics cards
* need their data as triangles.
*/
class TriangulateProcess : BaseProcess() {
/** Returns whether the processing step is present in the given flag field.
* @param flags The processing flags the importer was called with. A bitwise combination of AiPostProcessStep.
* @return true if the process is present in this flag fields, false if not. */
override fun isActive(flags: AiPostProcessStepsFlags): Boolean = flags has AiPostProcessStep.Triangulate
/** Executes the post processing step on the given imported data.
* At the moment a process is not supposed to fail.
* @param scene The imported data to work at. */
override fun execute(scene: AiScene) {
logger.debug("TriangulateProcess begin")
var has = false
for (a in 0 until scene.numMeshes)
if (triangulateMesh(scene.meshes[a]))
has = true
if (has)
logger.info("TriangulateProcess finished. All polygons have been triangulated.")
else
logger.debug("TriangulateProcess finished. There was nothing to be done.")
}
/** Triangulates the given mesh.
* @param mesh The mesh to triangulate. */
fun triangulateMesh(mesh: AiMesh): Boolean { // TODO bug
// Now we have aiMesh::mPrimitiveTypes, so this is only here for test cases
if (mesh.primitiveTypes == 0) {
var need = false
for (a in 0 until mesh.numFaces)
if (mesh.faces[a].size != 3)
need = true
if (!need)
return false
} else if (mesh.primitiveTypes hasnt AiPrimitiveType.POLYGON)
return false
// Find out how many output faces we'll get
var numOut = 0
var maxOut = 0
var getNormals = true
for (a in 0 until mesh.numFaces) {
val face = mesh.faces[a]
if (face.size <= 4)
getNormals = false
if (face.size <= 3)
numOut++
else {
numOut += face.size - 2
maxOut = maxOut max face.size
}
}
// Just another check whether aiMesh::mPrimitiveTypes is correct
assert(numOut != mesh.numFaces)
var norOut: Array<Vec3>? = null
// if we don't have normals yet, but expect them to be a cheap side product of triangulation anyway, allocate storage for them.
if (!mesh.normals.isNotEmpty() && getNormals) {
// XXX need a mechanism to inform the GenVertexNormals process to treat these normals as preprocessed per-face normals
norOut = Array(mesh.numVertices) { Vec3(0) }
mesh.normals = norOut.toMutableList()
}
// the output mesh will contain triangles, but no polys anymore
mesh.primitiveTypes = mesh.primitiveTypes or AiPrimitiveType.TRIANGLE
mesh.primitiveTypes = mesh.primitiveTypes wo AiPrimitiveType.POLYGON
val out: Array<AiFace> = Array(numOut) { mutableListOf<Int>() }
var curOut = 0
val tempVerts3d = Array(maxOut + 2) { Vec3() } /* temporary storage for vertices */
val tempVerts = Array(maxOut + 2) { Vec2() }
// Apply vertex colors to represent the face winding?
// #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING TODO
// if (!pMesh->mColors[0])
// pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices]
// else
// new(pMesh->mColors[0]) aiColor4D[pMesh->mNumVertices]
//
// aiColor4D * clr = pMesh->mColors[0]
// #endif
//
// #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
// FILE * fout = fopen(POLY_OUTPUT_FILE, "a")
// #endif
val verts = mesh.vertices
// use std::unique_ptr to avoid slow std::vector<bool> specialiations
val done = BooleanArray(maxOut)
for (a in 0 until mesh.numFaces) {
val face = mesh.faces[a]
val idx = face
var num = face.size
var next = 0
var tmp = 0
var prev = num - 1
val max = num
// Apply vertex colors to represent the face winding?
// #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING
// for (unsigned int i = 0; i < face.mNumIndices; ++i) {
// aiColor4D& c = clr[idx[i]]
// c.r = (i + 1) / (float) max
// c.b = 1.f - c.r
// }
// #endif
val lastFace = curOut
// if it's a simple point,line or triangle: just copy it
if (face.size <= 3) {
val nFace = out[curOut++]
nFace.clear()
nFace += face
face.clear()
continue
}
// optimized code for quadrilaterals
else if (face.size == 4) {
/* quads can have at maximum one concave vertex.
Determine this vertex (if it exists) and start tri-fanning from it. */
var startVertex = 0
for (i in 0..3) {
val v0 = verts[face[(i + 3) % 4]]
val v1 = verts[face[(i + 2) % 4]]
val v2 = verts[face[(i + 1) % 4]]
val v = verts[face[i]]
val left = v0 - v
val diag = v1 - v
val right = v2 - v
left.normalizeAssign()
diag.normalizeAssign()
right.normalizeAssign()
val angle = acos(left dot diag) + acos(right dot diag)
if (angle > glm.PIf) {
// this is the concave point
startVertex = i
break
}
}
val temp = IntArray(4) { face[it] }
val nFace = out[curOut++]
nFace.clear()
nFace += temp[startVertex]
nFace += temp[(startVertex + 1) % 4]
nFace += temp[(startVertex + 2) % 4]
val sFace = out[curOut++]
sFace.clear()
sFace += temp[startVertex]
sFace += temp[(startVertex + 2) % 4]
sFace += temp[(startVertex + 3) % 4]
// prevent double deletion of the indices field
face.clear()
continue
}
else {
/* A polygon with more than 3 vertices can be either concave or convex.
Usually everything we're getting is convex and we could easily triangulate by tri-fanning.
However, LightWave is probably the only modeling suite to make extensive use of highly concave,
monster polygons ...
so we need to apply the full 'ear cutting' algorithm to get it right.
REQUIREMENT: polygon is expected to be simple and *nearly* planar.
We project it onto a plane to get a 2d triangle. */
// Collect all vertices of of the polygon.
tmp = 0
while (tmp < max)
tempVerts3d[tmp] = verts[idx[tmp++]]
// Get newell normal of the polygon. Store it for future use if it's a polygon-only mesh
val n = Vec3()
newellNormal(n, max, tempVerts3d)
norOut?.let {
tmp = 0
while (tmp < max)
it[idx[tmp++]] = n
}
// Select largest normal coordinate to ignore for projection
val aX = if (n.x > 0) n.x else -n.x
val aY = if (n.y > 0) n.y else -n.y
val aZ = if (n.z > 0) n.z else -n.z
var ac = 0
var bc = 1 /* no z coord. projection to xy */
var inv = n.z
if (aX > aY) {
if (aX > aZ) { /* no x coord. projection to yz */
ac = 1; bc = 2
inv = n.x
}
} else if (aY > aZ) { /* no y coord. projection to zy */
ac = 2; bc = 0
inv = n.y
}
// Swap projection axes to take the negated projection vector into account
if (inv < 0f) {
val t = ac
ac = bc
bc = t
}
tmp = 0
while (tmp < max) {
tempVerts[tmp][0] = verts[idx[tmp]][ac]
tempVerts[tmp][1] = verts[idx[tmp]][bc]
done[tmp++] = false
}
// #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
// // plot the plane onto which we mapped the polygon to a 2D ASCII pic
// aiVector2D bmin, bmax
// ArrayBounds(& temp_verts [0], max, bmin, bmax)
//
// char grid [POLY_GRID_Y][POLY_GRID_X + POLY_GRID_XPAD]
// std::fill_n((char *) grid, POLY_GRID_Y * (POLY_GRID_X + POLY_GRID_XPAD), ' ')
//
// for (int i = 0; i < max; ++i) {
// const aiVector2D & v =(tempVerts[i] - bmin) / (bmax - bmin)
// const size_t x = static_cast<size_t>(v.x * (POLY_GRID_X - 1)), y = static_cast<size_t>(v.y*(POLY_GRID_Y-1))
// char * loc = grid[y] + x
// if (grid[y][x] != ' ') {
// for (;* loc != ' '; ++loc)
// *loc++ = '_'
// }
// *(loc + ::ai_snprintf(loc, POLY_GRID_XPAD, "%i", i)) = ' '
// }
//
//
// for (size_t y = 0; y < POLY_GRID_Y; ++y) {
// grid[y][POLY_GRID_X + POLY_GRID_XPAD - 1] = '\0'
// fprintf(fout, "%s\n", grid[y])
// }
//
// fprintf(fout, "\ntriangulation sequence: ")
// #endif
// FIXME: currently this is the slow O(kn) variant with a worst case
// complexity of O(n^2) (I think). Can be done in O(n).
while (num > 3) {
// Find the next ear of the polygon
var numFound = 0
var ear = next
while (true) {
// break after we looped two times without a positive match
next = ear + 1
while (done[if (next >= max) 0.also { next = 0 } else next])
++next
if (next < ear)
if (++numFound == 2)
break
val pnt1 = tempVerts[ear]
val pnt0 = tempVerts[prev]
val pnt2 = tempVerts[next]
// Must be a convex point. Assuming ccw winding, it must be on the right of the line between p-1 and p+1.
if (onLeftSideOfLine2D(pnt0, pnt2, pnt1)) {
prev = ear
ear = next
continue
}
// and no other point may be contained in this triangle
tmp = 0
while (tmp < max) {
/* We need to compare the actual values because it's possible that multiple indexes in
the polygon are referring to the same position. concave_polygon.obj is a sample
FIXME: Use 'epsiloned' comparisons instead? Due to numeric inaccuracies in
PointInTriangle() I'm guessing that it's actually possible to construct
input data that would cause us to end up with no ears. The problem is,
which epsilon? If we chose a too large value, we'd get wrong results */
val vtmp = tempVerts[tmp]
if (vtmp !== pnt1 && vtmp !== pnt2 && vtmp !== pnt0 && pointInTriangle2D(pnt0, pnt1, pnt2, vtmp))
break
++tmp
}
if (tmp != max) {
prev = ear
ear = next
continue
}
// this vertex is an ear
break
}
if (numFound == 2) {
/* Due to the 'two ear theorem', every simple polygon with more than three points must
have 2 'ears'. Here's definitely something wrong ... but we don't give up yet.
Instead we're continuing with the standard tri-fanning algorithm which we'd
use if we had only convex polygons. That's life. */
logger.error("Failed to triangulate polygon (no ear found). Probably not a simple polygon?")
// #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
// fprintf(fout, "critical error here, no ear found! ")
// #endif
num = 0
break
// TODO unreachable
// curOut -= (max - num) /* undo all previous work */
// for (tmp = 0; tmp < max - 2; ++tmp) {
// aiFace& nface = *curOut++
//
// nface.mNumIndices = 3
// if (!nface.mIndices)
// nface.mIndices = new unsigned int[3]
//
// nface.mIndices[0] = 0
// nface.mIndices[1] = tmp + 1
// nface.mIndices[2] = tmp + 2
//
// }
// num = 0
// break
}
val nFace = out[curOut++]
if (nFace.isEmpty())
for (i in 0..2)
nFace += 0
// setup indices for the new triangle ...
nFace[0] = prev
nFace[1] = ear
nFace[2] = next
// exclude the ear from most further processing
done[ear] = true
--num
}
if (num > 0) {
// We have three indices forming the last 'ear' remaining. Collect them.
val nFace = out[curOut++]
if (nFace.isEmpty())
for (i in 0..2)
nFace += 0
tmp = 0
while (done[tmp]) ++tmp
nFace[0] = tmp
++tmp
while (done[tmp]) ++tmp
nFace[1] = tmp
++tmp
while (done[tmp]) ++tmp
nFace[2] = tmp
}
}
// #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS
//
// for (aiFace* f = lastFace; f != curOut; ++f) {
// unsigned int * i = f->mIndices
// fprintf(fout, " (%i %i %i)", i[0], i[1], i[2])
// }
//
// fprintf(fout, "\n*********************************************************************\n")
// fflush(fout)
//
// #endif
var f = lastFace
while (f != curOut) {
val i = out[f]
// drop dumb 0-area triangles
val abs = abs(getArea2D(tempVerts[i[0]], tempVerts[i[1]], tempVerts[i[2]]))
if (abs < 1e-5f) {
logger.debug("Dropping triangle with area 0")
--curOut
out[f].clear()
var ff = f
while (ff != curOut) {
out[ff].clear()
out[ff].addAll(out[ff + 1])
out[ff + 1].clear()
++ff
}
continue
}
i[0] = idx[i[0]]
i[1] = idx[i[1]]
i[2] = idx[i[2]]
++f
}
face.clear()
}
// #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS TODO
// fclose(fout)
// #endif
// kill the old faces
mesh.faces.clear()
// ... and store the new ones
mesh.faces.addAll(out)
mesh.numFaces = curOut /* not necessarily equal to numOut */
return true
}
} | mit | 4aeaf6d079c808fe52212c430cd8f61e | 37.799189 | 135 | 0.468552 | 4.684546 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/lang/Language.kt | 1 | 2334 | /*
* Copyright (C) 2019-2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.core.lang
import com.intellij.lang.Language
import com.intellij.lang.LanguageParserDefinitions
import com.intellij.lang.ParserDefinition
import com.intellij.openapi.fileTypes.FileNameMatcher
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.util.Key
interface LanguageData {
companion object {
val KEY: Key<LanguageData> = Key.create("uk.co.reecedunn.intellij.plugin.key.languageData")
}
val associations: List<FileNameMatcher>
val mimeTypes: Array<String>
}
fun Language.getAssociations(): List<FileNameMatcher> {
val associations = associatedFileType?.let { FileTypeManager.getInstance().getAssociations(it) } ?: listOf()
return if (associations.isEmpty())
this.getUserData(LanguageData.KEY)?.associations ?: listOf()
else
associations
}
fun Array<out Language>.getAssociations(): List<FileNameMatcher> {
return asSequence().flatMap { language -> language.getAssociations().asSequence() }.toList()
}
fun Array<out Language>.findByAssociations(path: String): Language? = find { language ->
language.getAssociations().find { association -> association.acceptsCharSequence(path) } != null
}
fun Language.getLanguageMimeTypes(): Array<String> {
val mimeTypes = mimeTypes
return if (mimeTypes.isEmpty())
this.getUserData(LanguageData.KEY)?.mimeTypes ?: mimeTypes
else
mimeTypes
}
fun Array<out Language>.findByMimeType(predicate: (String) -> Boolean): Language? = find { language ->
language.getLanguageMimeTypes().find { predicate(it) } != null
}
val Language.parserDefinition: ParserDefinition
get() = LanguageParserDefinitions.INSTANCE.forLanguage(this)
| apache-2.0 | d2eb5f92db97d274ee99a35eb9af2888 | 35.46875 | 112 | 0.74593 | 4.420455 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/course_reviews/ui/dialog/ComposeCourseReviewDialogFragment.kt | 2 | 7342 | package org.stepik.android.view.course_reviews.ui.dialog
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.dialog_compose_course_review.*
import kotlinx.android.synthetic.main.view_centered_toolbar.*
import org.stepic.droid.R
import org.stepic.droid.base.App
import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment
import org.stepic.droid.ui.util.setTintedNavigationIcon
import org.stepic.droid.ui.util.snackbar
import org.stepic.droid.util.ProgressHelper
import org.stepik.android.domain.course_reviews.model.CourseReview
import org.stepik.android.presentation.course_reviews.ComposeCourseReviewPresenter
import org.stepik.android.presentation.course_reviews.ComposeCourseReviewView
import ru.nobird.android.view.base.ui.extension.argument
import ru.nobird.android.view.base.ui.extension.hideKeyboard
import javax.inject.Inject
class ComposeCourseReviewDialogFragment : DialogFragment(), ComposeCourseReviewView {
companion object {
const val TAG = "ComposeCourseReviewDialogFragment"
const val CREATE_REVIEW_REQUEST_CODE = 3412
const val EDIT_REVIEW_REQUEST_CODE = CREATE_REVIEW_REQUEST_CODE + 1
const val ARG_COURSE_REVIEW = "course_review"
fun newInstance(courseId: Long, courseReviewViewSource: String, courseReview: CourseReview?, courseRating: Float = -1f): DialogFragment =
ComposeCourseReviewDialogFragment().apply {
this.arguments = Bundle(2)
.also {
it.putParcelable(ARG_COURSE_REVIEW, courseReview)
}
this.courseId = courseId
this.courseReviewViewSource = courseReviewViewSource
this.courseRating = courseRating
}
}
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
private val composeCourseReviewPresenter: ComposeCourseReviewPresenter by viewModels { viewModelFactory }
private var courseId: Long by argument()
private var courseReviewViewSource: String by argument()
private val courseReview: CourseReview? by lazy { arguments?.getParcelable<CourseReview>(ARG_COURSE_REVIEW) }
private var courseRating: Float by argument()
private val progressDialogFragment: DialogFragment =
LoadingProgressDialogFragment.newInstance()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setCanceledOnTouchOutside(false)
dialog.setCancelable(false)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
return dialog
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NO_TITLE, R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen)
injectComponent()
}
private fun injectComponent() {
App.component()
.composeCourseReviewComponentBuilder()
.build()
.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.dialog_compose_course_review, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
centeredToolbarTitle.setText(R.string.course_reviews_compose_title)
centeredToolbar.setNavigationOnClickListener { dismiss() }
centeredToolbar.setTintedNavigationIcon(R.drawable.ic_close_dark)
centeredToolbar.inflateMenu(R.menu.compose_course_review_menu)
centeredToolbar.setOnMenuItemClickListener { menuItem ->
if (menuItem.itemId == R.id.course_review_submit) {
submitCourseReview()
true
} else {
false
}
}
if (savedInstanceState == null) {
courseRating
.takeIf { it > -1 }
?.let {
courseReviewRating.rating = courseRating
}
courseReview?.let {
courseReviewEditText.setText(it.text)
courseReviewRating.rating = it.score.toFloat()
}
}
invalidateMenuState()
courseReviewEditText.doAfterTextChanged { invalidateMenuState() }
courseReviewRating.setOnRatingBarChangeListener { _, _, _ -> invalidateMenuState() }
}
override fun onStart() {
super.onStart()
dialog
?.window
?.let { window ->
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
window.setWindowAnimations(R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen)
}
composeCourseReviewPresenter.attachView(this)
}
override fun onStop() {
composeCourseReviewPresenter.detachView(this)
super.onStop()
}
private fun submitCourseReview() {
courseReviewEditText.hideKeyboard()
val oldCourseReview = courseReview
val text = courseReviewEditText.text?.toString()
val score = courseReviewRating.rating.toInt()
if (oldCourseReview == null) {
val courseReview = CourseReview(
course = courseId,
text = text,
score = score
)
composeCourseReviewPresenter.createCourseReview(courseReview, courseReviewViewSource)
} else {
val courseReview = oldCourseReview
.copy(
text = text,
score = score
)
composeCourseReviewPresenter.updateCourseReview(oldCourseReview, courseReview, courseReviewViewSource)
}
}
private fun invalidateMenuState() {
centeredToolbar.menu.findItem(R.id.course_review_submit)?.isEnabled =
!courseReviewEditText.text.isNullOrEmpty() && courseReviewRating.rating > 0
}
override fun setState(state: ComposeCourseReviewView.State) {
when (state) {
ComposeCourseReviewView.State.Idle ->
ProgressHelper.dismiss(childFragmentManager, LoadingProgressDialogFragment.TAG)
ComposeCourseReviewView.State.Loading ->
ProgressHelper.activate(progressDialogFragment, childFragmentManager, LoadingProgressDialogFragment.TAG)
is ComposeCourseReviewView.State.Complete -> {
ProgressHelper.dismiss(childFragmentManager, LoadingProgressDialogFragment.TAG)
targetFragment
?.onActivityResult(
targetRequestCode,
Activity.RESULT_OK,
Intent().putExtra(ARG_COURSE_REVIEW, state.courseReview)
)
dismiss()
}
}
}
override fun showNetworkError() {
view?.snackbar(messageRes = R.string.connectionProblems)
}
} | apache-2.0 | 21f61564350ab273932074e77065f6d7 | 37.851852 | 145 | 0.670934 | 5.516153 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/step_quiz_sorting/ui/fragment/SortingStepQuizFragment.kt | 1 | 1246 | package org.stepik.android.view.step_quiz_sorting.ui.fragment
import android.view.View
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.layout_step_quiz_sorting.*
import org.stepic.droid.R
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate
import org.stepik.android.view.step_quiz.ui.fragment.DefaultStepQuizFragment
import org.stepik.android.view.step_quiz_sorting.ui.delegate.SortingStepQuizFormDelegate
import ru.nobird.android.presentation.redux.container.ReduxView
class SortingStepQuizFragment :
DefaultStepQuizFragment(),
ReduxView<StepQuizFeature.State, StepQuizFeature.Action.ViewAction> {
companion object {
fun newInstance(stepId: Long): Fragment =
SortingStepQuizFragment()
.apply {
this.stepId = stepId
}
}
override val quizLayoutRes: Int =
R.layout.layout_step_quiz_sorting
override val quizViews: Array<View>
get() = arrayOf(sortingRecycler)
override fun createStepQuizFormDelegate(view: View): StepQuizFormDelegate =
SortingStepQuizFormDelegate(view, onQuizChanged = ::syncReplyState)
} | apache-2.0 | 50325f2b59634fdb09ce9ee713fab62b | 37.96875 | 88 | 0.752006 | 4.482014 | false | false | false | false |
EvidentSolutions/dalesbred-idea-plugin | src/main/kotlin/fi/evident/dalesbred/plugin/idea/utils/DalesbredPatterns.kt | 1 | 4890 | /*
* Copyright (c) 2017 Evident Solutions Oy
*
* 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 fi.evident.dalesbred.plugin.idea.utils
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PsiJavaPatterns.psiClass
import com.intellij.patterns.PsiJavaPatterns.psiMethod
import com.intellij.patterns.PsiMethodPattern
import com.intellij.patterns.StandardPatterns
import com.intellij.patterns.StandardPatterns.or
import com.intellij.patterns.StandardPatterns.string
import com.intellij.psi.PsiMethod
private object ClassNames {
val CLASS = "java.lang.Class"
val STRING = "java.lang.String"
val OBJECT_ARGS = "java.lang.Object..."
val DATABASE = "org.dalesbred.Database"
val SQL_QUERY = "org.dalesbred.query.SqlQuery"
val ROW_MAPPER = "org.dalesbred.result.RowMapper"
val RESULT_SET_PROCESSOR = "org.dalesbred.result.ResultSetProcessor"
}
private val QUERY_AND_ARGS = arrayOf(ClassNames.STRING, ClassNames.OBJECT_ARGS)
private val databaseClass = psiClass().withQualifiedName(ClassNames.DATABASE)
private val sqlQueryClass = psiClass().withQualifiedName(ClassNames.SQL_QUERY)
val findMethod: ElementPattern<PsiMethod> by lazy {
val generalName = string().oneOf("findUnique", "findUniqueOrNull", "findOptional", "findAll")
val withoutRowMapperName = string().oneOf("findUniqueInt", "findUniqueLong", "findUniqueBoolean", "findTable")
or(
databaseMethod(generalName).withParameters(ClassNames.CLASS, *QUERY_AND_ARGS),
databaseMethod(generalName).withParameters(ClassNames.CLASS, ClassNames.SQL_QUERY),
databaseMethod(generalName).withParameters(ClassNames.ROW_MAPPER, *QUERY_AND_ARGS),
databaseMethod(generalName).withParameters(ClassNames.ROW_MAPPER, ClassNames.SQL_QUERY),
databaseMethod(withoutRowMapperName).withParameters(*QUERY_AND_ARGS),
databaseMethod(withoutRowMapperName).withParameters(ClassNames.SQL_QUERY),
databaseMethod("findMap").withParameters(ClassNames.CLASS, ClassNames.CLASS, *QUERY_AND_ARGS),
databaseMethod("findMap").withParameters(ClassNames.CLASS, ClassNames.CLASS, ClassNames.SQL_QUERY))
}
val sqlQueryMethod: ElementPattern<PsiMethod> =
psiMethod().definedInClass(sqlQueryClass).withName("query").withParameters(*QUERY_AND_ARGS)
val executeQueryMethod: ElementPattern<PsiMethod> = or(
databaseMethod("executeQuery").withParameters(ClassNames.RESULT_SET_PROCESSOR, *QUERY_AND_ARGS),
databaseMethod("executeQuery").withParameters(ClassNames.RESULT_SET_PROCESSOR, ClassNames.SQL_QUERY))
val updateMethod: ElementPattern<PsiMethod> =
databaseMethod("update").withParameters(*QUERY_AND_ARGS)
val updateAndProcessGeneratedKeysMethod: ElementPattern<PsiMethod> = or(
databaseMethod("updateAndProcessGeneratedKeys").withParameters(ClassNames.RESULT_SET_PROCESSOR, *QUERY_AND_ARGS),
databaseMethod("updateAndProcessGeneratedKeys").withParameters(ClassNames.RESULT_SET_PROCESSOR, ClassNames.SQL_QUERY))
private fun findMethodGeneral(): ElementPattern<PsiMethod> {
val namePattern = string().oneOf("findUnique", "findUniqueOrNull", "findOptional", "findAll")
return or(
databaseMethod(namePattern).withParameters(ClassNames.CLASS, *QUERY_AND_ARGS),
databaseMethod(namePattern).withParameters(ClassNames.CLASS, ClassNames.SQL_QUERY),
databaseMethod(namePattern).withParameters(ClassNames.ROW_MAPPER, *QUERY_AND_ARGS),
databaseMethod(namePattern).withParameters(ClassNames.ROW_MAPPER, ClassNames.SQL_QUERY))
}
private fun databaseMethod(name: String): PsiMethodPattern =
databaseMethod(StandardPatterns.`object`(name))
private fun databaseMethod(name: ElementPattern<String>): PsiMethodPattern =
psiMethod().definedInClass(databaseClass).withName(name)
| mit | e40ed2192c65b24f1bdd96b7abb0e752 | 51.580645 | 126 | 0.766462 | 4.679426 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/SourcesFilterController.kt | 1 | 1021 | package eu.kanade.tachiyomi.ui.browse.source
import androidx.compose.runtime.Composable
import eu.kanade.domain.source.model.Source
import eu.kanade.presentation.browse.SourcesFilterScreen
import eu.kanade.tachiyomi.ui.base.controller.FullComposeController
class SourceFilterController : FullComposeController<SourcesFilterPresenter>() {
override fun createPresenter(): SourcesFilterPresenter = SourcesFilterPresenter()
@Composable
override fun ComposeContent() {
SourcesFilterScreen(
navigateUp = router::popCurrentController,
presenter = presenter,
onClickLang = { language ->
presenter.toggleLanguage(language)
},
onClickSource = { source ->
presenter.toggleSource(source)
},
)
}
}
sealed class FilterUiModel {
data class Header(val language: String, val enabled: Boolean) : FilterUiModel()
data class Item(val source: Source, val enabled: Boolean) : FilterUiModel()
}
| apache-2.0 | 58d56f96a3774e019a7ebc64192086b8 | 33.033333 | 85 | 0.697356 | 4.908654 | false | false | false | false |
apollostack/apollo-android | composite/integration-tests/src/testShared/kotlin/com/apollographql/apollo3/FaultyHttpCacheStore.kt | 1 | 3555 | package com.apollographql.apollo3
import com.apollographql.apollo3.api.cache.http.HttpCacheRecord
import com.apollographql.apollo3.api.cache.http.HttpCacheRecordEditor
import com.apollographql.apollo3.api.cache.http.HttpCacheStore
import com.apollographql.apollo3.cache.http.internal.DiskLruCache
import com.apollographql.apollo3.cache.http.internal.FileSystem
import okio.Buffer
import okio.Sink
import okio.Source
import okio.Timeout
import java.io.File
import java.io.IOException
class FaultyHttpCacheStore(fileSystem: FileSystem) : HttpCacheStore {
private val cache: DiskLruCache
val faultySource = FaultySource()
val faultySink = FaultySink()
var failStrategy: FailStrategy? = null
@Throws(IOException::class)
override fun cacheRecord(cacheKey: String): HttpCacheRecord? {
val snapshot = cache[cacheKey] ?: return null
return object : HttpCacheRecord {
override fun headerSource(): Source {
return if (failStrategy == FailStrategy.FAIL_HEADER_READ) {
faultySource
} else {
snapshot.getSource(ENTRY_HEADERS)
}
}
override fun bodySource(): Source {
return if (failStrategy == FailStrategy.FAIL_BODY_READ) {
faultySource
} else {
snapshot.getSource(ENTRY_BODY)
}
}
override fun close() {
snapshot.close()
}
}
}
@Throws(IOException::class)
override fun cacheRecordEditor(cacheKey: String): HttpCacheRecordEditor? {
val editor = cache.edit(cacheKey) ?: return null
return object : HttpCacheRecordEditor {
override fun headerSink(): Sink {
return if (failStrategy == FailStrategy.FAIL_HEADER_WRITE) {
faultySink
} else {
editor.newSink(ENTRY_HEADERS)
}
}
override fun bodySink(): Sink {
return if (failStrategy == FailStrategy.FAIL_BODY_WRITE) {
faultySink
} else {
editor.newSink(ENTRY_BODY)
}
}
@Throws(IOException::class)
override fun abort() {
editor.abort()
}
@Throws(IOException::class)
override fun commit() {
editor.commit()
}
}
}
@Throws(IOException::class)
override fun delete() {
cache.delete()
}
@Throws(IOException::class)
override fun remove(cacheKey: String) {
cache.remove(cacheKey)
}
fun failStrategy(failStrategy: FailStrategy?) {
this.failStrategy = failStrategy
}
enum class FailStrategy {
FAIL_HEADER_READ, FAIL_BODY_READ, FAIL_HEADER_WRITE, FAIL_BODY_WRITE
}
class FaultySource : Source {
@Throws(IOException::class)
override fun read(sink: Buffer, byteCount: Long): Long {
throw IOException("failed to read")
}
override fun timeout(): Timeout {
return Timeout()
}
@Throws(IOException::class)
override fun close() {
}
}
class FaultySink : Sink {
@Throws(IOException::class)
override fun write(source: Buffer, byteCount: Long) {
throw IOException("failed to write")
}
@Throws(IOException::class)
override fun flush() {
}
override fun timeout(): Timeout {
return Timeout()
}
@Throws(IOException::class)
override fun close() {
}
}
companion object {
private const val VERSION = 99991
private const val ENTRY_HEADERS = 0
private const val ENTRY_BODY = 1
private const val ENTRY_COUNT = 2
}
init {
cache = DiskLruCache.create(fileSystem, File("/cache/"), VERSION, ENTRY_COUNT, Int.MAX_VALUE.toLong())
}
} | mit | 85e12ac6a657f04ed6c86692c0c7f797 | 24.219858 | 106 | 0.655977 | 4.351285 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FlattenWhenIntention.kt | 2 | 2756 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class FlattenWhenIntention : SelfTargetingIntention<KtWhenExpression>(
KtWhenExpression::class.java,
KotlinBundle.lazyMessage("flatten.when.expression")
) {
override fun isApplicableTo(element: KtWhenExpression, caretOffset: Int): Boolean {
val subject = element.subjectExpression
if (subject != null && subject !is KtNameReferenceExpression) return false
if (!KtPsiUtil.checkWhenExpressionHasSingleElse(element)) return false
val elseEntry = element.entries.singleOrNull { it.isElse } ?: return false
val innerWhen = elseEntry.expression as? KtWhenExpression ?: return false
if (!subject.matches(innerWhen.subjectExpression)) return false
if (!KtPsiUtil.checkWhenExpressionHasSingleElse(innerWhen)) return false
return elseEntry.startOffset <= caretOffset && caretOffset <= innerWhen.whenKeyword.endOffset
}
override fun applyTo(element: KtWhenExpression, editor: Editor?) {
val subjectExpression = element.subjectExpression
val nestedWhen = element.elseExpression as KtWhenExpression
val outerEntries = element.entries
val innerEntries = nestedWhen.entries
val whenExpression = KtPsiFactory(element).buildExpression {
appendFixedText("when")
if (subjectExpression != null) {
appendFixedText("(").appendExpression(subjectExpression).appendFixedText(")")
}
appendFixedText("{\n")
for (entry in outerEntries) {
if (entry.isElse) continue
appendNonFormattedText(entry.text)
appendFixedText("\n")
}
for (entry in innerEntries) {
appendNonFormattedText(entry.text)
appendFixedText("\n")
}
appendFixedText("}")
} as KtWhenExpression
val newWhen = element.replaced(whenExpression)
val firstNewEntry = newWhen.entries[outerEntries.size - 1]
editor?.moveCaret(firstNewEntry.textOffset)
}
}
| apache-2.0 | 6006ab9fa8d8fbb4867b84b82a7ae032 | 40.134328 | 158 | 0.707184 | 5.170732 | false | false | false | false |
Maccimo/intellij-community | tools/intellij.ide.starter/src/com/intellij/ide/starter/runner/TestContainer.kt | 1 | 3436 | package com.intellij.ide.starter.runner
import com.intellij.ide.starter.ci.CIServer
import com.intellij.ide.starter.di.di
import com.intellij.ide.starter.ide.*
import com.intellij.ide.starter.models.IdeInfo
import com.intellij.ide.starter.models.IdeProduct
import com.intellij.ide.starter.models.TestCase
import com.intellij.ide.starter.path.GlobalPaths
import com.intellij.ide.starter.path.IDEDataPaths
import com.intellij.ide.starter.utils.catchAll
import com.intellij.ide.starter.utils.logOutput
import org.kodein.di.direct
import org.kodein.di.factory
import org.kodein.di.instance
import java.io.Closeable
import kotlin.io.path.div
/**
* [ciServer] - use [NoCIServer] for only local run. Otherwise - pass implementation of CIServer
*/
interface TestContainer<T> : Closeable {
val ciServer: CIServer
var useLatestDownloadedIdeBuild: Boolean
val allContexts: MutableList<IDETestContext>
val setupHooks: MutableList<IDETestContext.() -> IDETestContext>
override fun close() {
for (context in allContexts) {
catchAll { context.paths.close() }
}
}
/**
* Allows to apply the common configuration to all created IDETestContext instances
*/
fun withSetupHook(hook: IDETestContext.() -> IDETestContext): T = apply {
setupHooks += hook
} as T
/**
* Makes the test use the latest available locally IDE build for testing.
*/
fun useLatestDownloadedIdeBuild(): T = apply {
assert(!ciServer.isBuildRunningOnCI)
useLatestDownloadedIdeBuild = true
} as T
fun resolveIDE(ideInfo: IdeInfo): Pair<String, InstalledIDE> {
return di.direct.factory<IdeInfo, IdeInstallator>().invoke(ideInfo).install(ideInfo)
}
/** Starting point to run your test */
fun initializeTestRunner(testName: String, testCase: TestCase): IDETestContext {
check(allContexts.none { it.testName == testName }) { "Test $testName is already initialized. Use another name." }
logOutput("Resolving IDE build for $testName...")
val (buildNumber, ide) = resolveIDE(testCase.ideInfo)
require(ide.productCode == testCase.ideInfo.productCode) { "Product code of $ide must be the same as for $testCase" }
val testDirectory = (di.direct.instance<GlobalPaths>().testsDirectory / "${testCase.ideInfo.productCode}-$buildNumber") / testName
val paths = IDEDataPaths.createPaths(testName, testDirectory, testCase.useInMemoryFileSystem)
logOutput("Using IDE paths for $testName: $paths")
logOutput("IDE to run for $testName: $ide")
val projectHome = testCase.projectInfo?.resolveProjectHome()
val context = IDETestContext(paths, ide, testCase, testName, projectHome, patchVMOptions = { this }, ciServer = ciServer)
allContexts += context
val baseContext = when (testCase.ideInfo == IdeProduct.AI.ideInfo) {
true -> context
.addVMOptionsPatch {
overrideDirectories(paths)
.withEnv("STUDIO_VM_OPTIONS", ide.patchedVMOptionsFile.toString())
}
false -> context
.disableInstantIdeShutdown()
.disableFusSendingOnIdeClose()
.disableJcef()
.disableLinuxNativeMenuForce()
.withGtk2OnLinux()
.disableGitLogIndexing()
.enableSlowOperationsInEdtInTests()
.collectOpenTelemetry()
.addVMOptionsPatch {
overrideDirectories(paths)
}
}
return setupHooks.fold(baseContext.updateGeneralSettings()) { acc, hook -> acc.hook() }
}
} | apache-2.0 | 69d4ab19342028c11c60f224379a43ac | 35.956989 | 134 | 0.722934 | 4.263027 | false | true | false | false |
Maccimo/intellij-community | platform/lang-impl/src/com/intellij/ide/actions/navbar/NavBarLocationAction.kt | 1 | 1749 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.actions.navbar
import com.intellij.ide.ui.NavBarLocation
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.project.DumbAware
import com.intellij.ui.ExperimentalUI
abstract class NavBarLocationAction(private val location: NavBarLocation) : ToggleAction(), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
val settings = UISettings.getInstance()
return settings.showNavigationBar && settings.navBarLocation == location
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
UISettings.getInstance().let {
it.navBarLocation = location
it.showNavigationBar = true
it.fireUISettingsChanged()
}
}
override fun update(e: AnActionEvent) {
if (!ExperimentalUI.isNewUI()) {
e.presentation.isEnabledAndVisible = false
return
}
super.update(e)
}
}
class NavBarTopLocationAction : NavBarLocationAction(NavBarLocation.TOP)
class NavBarBottomLocationAction : NavBarLocationAction(NavBarLocation.BOTTOM)
class HideNavBarAction : ToggleAction(), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean = !UISettings.getInstance().showNavigationBar
override fun setSelected(e: AnActionEvent, state: Boolean) {
UISettings.getInstance().let {
it.showNavigationBar = false
it.fireUISettingsChanged()
}
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
}
| apache-2.0 | b134e68e79596734a31bbd42a7bc7ea5 | 33.98 | 120 | 0.769011 | 4.804945 | false | false | false | false |
android/android-test | espresso/device/java/androidx/test/espresso/device/dagger/DeviceControllerModule.kt | 1 | 4029 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.test.espresso.device.dagger
import androidx.test.espresso.device.context.ActionContext
import androidx.test.espresso.device.context.InstrumentationTestActionContext
import androidx.test.espresso.device.controller.DeviceControllerOperationException
import androidx.test.espresso.device.controller.emulator.EmulatorController
import androidx.test.espresso.device.controller.PhysicalDeviceController
import androidx.test.espresso.device.controller.emulator.EmulatorGrpcConn
import androidx.test.espresso.device.controller.emulator.EmulatorGrpcConnImpl
import androidx.test.espresso.device.util.isTestDeviceAnEmulator
import androidx.test.internal.platform.ServiceLoaderWrapper
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.platform.device.DeviceController
import dagger.Module
import dagger.Provides
import java.lang.reflect.Method
import javax.inject.Singleton
/** Dagger module for DeviceController. */
@Module
internal class DeviceControllerModule {
@Provides
@Singleton
fun provideActionContext(): ActionContext {
return InstrumentationTestActionContext()
}
@Provides
@Singleton
fun provideDeviceController(): DeviceController {
val platformDeviceController: androidx.test.platform.device.DeviceController? =
ServiceLoaderWrapper.loadSingleServiceOrNull(
androidx.test.platform.device.DeviceController::class.java
)
if (platformDeviceController == null) {
if (isTestDeviceAnEmulator()) {
val connection = getEmulatorConnection()
return EmulatorController(connection.emulatorController())
} else {
return PhysicalDeviceController()
}
} else {
return EspressoDeviceControllerAdpater(platformDeviceController)
}
}
private fun getEmulatorConnection(): EmulatorGrpcConn {
val args = InstrumentationRegistry.getArguments()
var grpcPortString = args.getString(EmulatorGrpcConn.ARGS_GRPC_PORT)
var grpcPort = if (grpcPortString != null && grpcPortString.toInt() > 0) {
grpcPortString.toInt()
} else {
getEmulatorGRPCPort()
}
return EmulatorGrpcConnImpl(
EmulatorGrpcConn.EMULATOR_ADDRESS,
grpcPort,
args.getString(EmulatorGrpcConn.ARGS_GRPC_TOKEN, ""),
args.getString(EmulatorGrpcConn.ARGS_GRPC_CER, ""),
args.getString(EmulatorGrpcConn.ARGS_GRPC_KEY, ""),
args.getString(EmulatorGrpcConn.ARGS_GRPC_CA, "")
)
}
/* Gets the emulator gRPC port for emulators running in g3 */
private fun getEmulatorGRPCPort(): Int {
val clazz = Class.forName("android.os.SystemProperties")
val getter: Method = clazz.getMethod("get", String::class.java)
var gRpcPort = getter.invoke(clazz, "mdevx.grpc_guest_port") as String
if (gRpcPort.isBlank()) {
throw DeviceControllerOperationException(
"Unable to connect to Emulator gRPC port. Please make sure the controller gRPC service is" +
" enabled on the emulator."
)
}
return gRpcPort.toInt()
}
private class EspressoDeviceControllerAdpater(
val deviceController: androidx.test.platform.device.DeviceController
) : DeviceController {
override fun setDeviceMode(deviceMode: Int) {
deviceController.setDeviceMode(deviceMode)
}
override fun setScreenOrientation(screenOrientation: Int) {
deviceController.setScreenOrientation(screenOrientation)
}
}
}
| apache-2.0 | 3fe4792ebde53fd193382368f4fc9eef | 36.654206 | 100 | 0.757012 | 4.679443 | false | true | false | false |
danvratil/FBEventSync | app/src/main/java/cz/dvratil/fbeventsync/AccountAdapter.kt | 1 | 4306 | /*
Copyright (C) 2018 Daniel Vrátil <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.dvratil.fbeventsync
import android.accounts.Account
import android.accounts.AccountManager
import android.accounts.OnAccountsUpdateListener
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.provider.CalendarContract
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.view.LayoutInflater
import android.widget.Button
import android.widget.ImageView
import android.widget.ProgressBar
class AccountAdapter(private var mContext: Context) : RecyclerView.Adapter<AccountAdapter.ViewHolder>()
, OnAccountsUpdateListener {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var name = view.findViewById<TextView>(R.id.account_card_name)
var syncBtn = view.findViewById<Button>(R.id.account_card_sync_btn)
var removeBtn = view.findViewById<Button>(R.id.account_card_remove_btn)
var syncIndicator = view.findViewById<ProgressBar>(R.id.account_card_sync_progress)
var avatarView = view.findViewById<ImageView>(R.id.account_card_avatar)
}
data class AccountData(var account: Account, var isSyncing: Boolean) {
fun id() = account.name.hashCode().toLong()
}
private val mAccountManager = AccountManager.get(mContext)
private var mAccounts: MutableList<AccountData>
init {
setHasStableIds(true)
ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE) {
// FIXME: Is this safe?
(mContext as Activity).runOnUiThread(Runnable { checkSyncStatus() })
}
mAccounts = mutableListOf()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.account_card, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val account = mAccounts[position]
holder.name.text = account.account.name
holder.syncBtn.isEnabled = !account.isSyncing
holder.syncIndicator.visibility = if (account.isSyncing) View.VISIBLE else View.GONE
/*AvatarProvider.getAvatar(mContext, account.account, {
holder.avatarView.setImageDrawable(it)
})*/
holder.syncBtn.setOnClickListener {
CalendarSyncAdapter.requestSync(mContext, account.account)
}
holder.removeBtn.setOnClickListener{
Authenticator.removeAccount(mContext, account.account)
}
}
override fun getItemCount(): Int = mAccounts.count()
// OnAccountUpdateListener interface
override fun onAccountsUpdated(accounts: Array<out Account>) {
val accountType = mContext.getString(R.string.account_type)
mAccounts.clear()
for (account in accounts.filter { it.type == accountType }) {
mAccounts.add(AccountData(account, ContentResolver.isSyncActive(account, CalendarContract.AUTHORITY)))
}
notifyDataSetChanged()
}
private fun checkSyncStatus() {
for (i in 0..(mAccounts.count() - 1)) {
val syncing = ContentResolver.isSyncActive(mAccounts[i].account, CalendarContract.AUTHORITY)
if (mAccounts[i].isSyncing != syncing) {
mAccounts[i].isSyncing = syncing
notifyItemChanged(i)
}
}
}
override fun getItemId(position: Int): Long = mAccounts[position].id()
}
| gpl-3.0 | 207751077afa3f36b429ca74b409fb88 | 38.136364 | 114 | 0.702207 | 4.704918 | false | false | false | false |
android/nowinandroid | core/network/src/main/java/com/google/samples/apps/nowinandroid/core/network/model/NetworkTopic.kt | 1 | 1093 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.network.model
import com.google.samples.apps.nowinandroid.core.model.data.Topic
import kotlinx.serialization.Serializable
/**
* Network representation of [Topic]
*/
@Serializable
data class NetworkTopic(
val id: String,
val name: String = "",
val shortDescription: String = "",
val longDescription: String = "",
val url: String = "",
val imageUrl: String = "",
val followed: Boolean = false,
)
| apache-2.0 | 0c44f76dc524800992b2448171c721c8 | 31.147059 | 75 | 0.724611 | 4.171756 | false | false | false | false |
GunoH/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/AttachToProcessDialogFactory.kt | 2 | 1736 | package com.intellij.xdebugger.impl.ui.attach.dialog
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.project.Project
import com.intellij.util.application
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.attach.XAttachDebuggerProvider
import com.intellij.xdebugger.attach.XAttachHost
import com.intellij.xdebugger.attach.XAttachHostProvider
import com.intellij.xdebugger.impl.util.isAlive
import com.intellij.xdebugger.impl.util.onTermination
class AttachToProcessDialogFactory(private val project: Project) {
companion object {
val IS_LOCAL_VIEW_DEFAULT_KEY = DataKey.create<Boolean>("ATTACH_DIALOG_VIEW_TYPE")
private fun isLocalViewDefault(dataContext: DataContext): Boolean = dataContext.getData(IS_LOCAL_VIEW_DEFAULT_KEY) ?: true
}
private var currentDialog: AttachToProcessDialog? = null
fun showDialog(attachDebuggerProviders: List<XAttachDebuggerProvider>,
attachHosts: List<XAttachHostProvider<XAttachHost>>,
context: DataContext) {
application.assertIsDispatchThread()
val isLocalViewDefault = isLocalViewDefault(context)
val currentDialogInstance = currentDialog
if (currentDialogInstance != null && currentDialogInstance.isShowing && currentDialogInstance.disposable.isAlive) {
currentDialogInstance.setShowLocalView(isLocalViewDefault)
return
}
val dialog = AttachToProcessDialog(project, attachDebuggerProviders, attachHosts, isLocalViewDefault, null)
dialog.disposable.onTermination {
UIUtil.invokeLaterIfNeeded { if (currentDialog == dialog) currentDialog = null }
}
currentDialog = dialog
dialog.show()
}
} | apache-2.0 | 7024e5e91c469f50f81668037a6b0f25 | 41.365854 | 126 | 0.787442 | 4.876404 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUParameter.kt | 4 | 2138 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UParameter
import org.jetbrains.uast.UParameterEx
@ApiStatus.Internal
open class KotlinUParameter(
psi: PsiParameter,
final override val sourcePsi: KtElement?,
givenParent: UElement?
) : AbstractKotlinUVariable(givenParent), UParameterEx, PsiParameter by psi {
final override val javaPsi = unwrap<UParameter, PsiParameter>(psi)
override val psi = javaPsi
private val isLightConstructorParam by lz { psi.getParentOfType<PsiMethod>(true)?.isConstructor }
private val isKtConstructorParam by lz { sourcePsi?.getParentOfType<KtCallableDeclaration>(true)?.let { it is KtConstructor<*> } }
override fun acceptsAnnotationTarget(target: AnnotationUseSiteTarget?): Boolean {
if (sourcePsi !is KtParameter) return false
if (isKtConstructorParam == isLightConstructorParam && target == null) return true
if (sourcePsi.parent.parent is KtCatchClause && target == null) return true
when (target) {
AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER -> return isLightConstructorParam == true
AnnotationUseSiteTarget.SETTER_PARAMETER -> return isLightConstructorParam != true
else -> return false
}
}
override fun getInitializer(): PsiExpression? {
return super<AbstractKotlinUVariable>.getInitializer()
}
override fun getOriginalElement(): PsiElement? {
return super<AbstractKotlinUVariable>.getOriginalElement()
}
override fun getNameIdentifier(): PsiIdentifier {
return super.getNameIdentifier()
}
override fun getContainingFile(): PsiFile {
return super.getContainingFile()
}
}
| apache-2.0 | 9a0594039b197870ad8f3dbf42b1b281 | 38.592593 | 158 | 0.744621 | 5.279012 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/index/ui/GitStageCommitPanel.kt | 2 | 5404 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.index.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.DisposableWrapperList
import com.intellij.util.ui.JBUI.Borders.empty
import com.intellij.vcs.commit.CommitProgressPanel
import com.intellij.vcs.commit.EditedCommitDetails
import com.intellij.vcs.commit.NonModalCommitPanel
import git4idea.i18n.GitBundle
import git4idea.index.ContentVersion
import git4idea.index.GitFileStatus
import git4idea.index.GitStageTracker
import git4idea.index.createChange
import org.jetbrains.concurrency.resolvedPromise
import kotlin.properties.Delegates.observable
private fun GitStageTracker.State.getStaged(): Set<GitFileStatus> =
rootStates.values.flatMapTo(mutableSetOf()) { it.getStaged() }
private fun GitStageTracker.RootState.getStaged(): Set<GitFileStatus> =
statuses.values.filterTo(mutableSetOf()) { it.getStagedStatus() != null }
private fun GitStageTracker.RootState.getStagedChanges(project: Project): List<Change> =
getStaged().mapNotNull { createChange(project, root, it, ContentVersion.HEAD, ContentVersion.STAGED) }
class GitStageCommitPanel(project: Project) : NonModalCommitPanel(project) {
private val progressPanel = GitStageCommitProgressPanel()
override val commitProgressUi: GitStageCommitProgressPanel get() = progressPanel
@Volatile
private var state: InclusionState = InclusionState(emptySet(), GitStageTracker.State.EMPTY)
val rootsToCommit get() = state.rootsToCommit
val includedRoots get() = state.includedRoots
val conflictedRoots get() = state.conflictedRoots
private val editedCommitListeners = DisposableWrapperList<() -> Unit>()
override var editedCommit: EditedCommitDetails? by observable(null) { _, _, _ ->
editedCommitListeners.forEach { it() }
}
init {
Disposer.register(this, commitMessage)
commitMessage.setChangesSupplier { state.stagedChanges }
progressPanel.setup(this, commitMessage.editorField, empty(6))
bottomPanel.add(progressPanel.component)
bottomPanel.add(commitAuthorComponent.apply { border = empty(0, 5, 4, 0) })
bottomPanel.add(commitActionsPanel)
}
fun setIncludedRoots(includedRoots: Collection<VirtualFile>) {
setState(includedRoots, state.trackerState)
}
fun setTrackerState(trackerState: GitStageTracker.State) {
setState(state.includedRoots, trackerState)
}
private fun setState(includedRoots: Collection<VirtualFile>, trackerState: GitStageTracker.State) {
val newState = InclusionState(includedRoots, trackerState)
if (state != newState) {
state = newState
fireInclusionChanged()
}
}
fun addEditedCommitListener(listener: () -> Unit, parent: Disposable) {
editedCommitListeners.add(listener, parent)
}
override fun activate(): Boolean = true
override fun refreshData() = resolvedPromise<Unit>()
override fun getDisplayedChanges(): List<Change> = emptyList()
override fun getIncludedChanges(): List<Change> = state.stagedChanges
override fun getDisplayedUnversionedFiles(): List<FilePath> = emptyList()
override fun getIncludedUnversionedFiles(): List<FilePath> = emptyList()
private inner class InclusionState(val includedRoots: Collection<VirtualFile>, val trackerState: GitStageTracker.State) {
private val stagedStatuses: Set<GitFileStatus> = trackerState.getStaged()
val conflictedRoots: Set<VirtualFile> = trackerState.rootStates.filter { it.value.hasConflictedFiles() }.keys
val stagedChanges by lazy {
trackerState.rootStates.filterKeys {
includedRoots.contains(it)
}.values.flatMap { it.getStagedChanges(project) }
}
val rootsToCommit get() = trackerState.stagedRoots.intersect(includedRoots)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as InclusionState
if (includedRoots != other.includedRoots) return false
if (stagedStatuses != other.stagedStatuses) return false
if (conflictedRoots != other.conflictedRoots) return false
return true
}
override fun hashCode(): Int {
var result = includedRoots.hashCode()
result = 31 * result + stagedStatuses.hashCode()
result = 31 * result + conflictedRoots.hashCode()
return result
}
}
}
class GitStageCommitProgressPanel : CommitProgressPanel() {
var isEmptyRoots by stateFlag()
var isUnmerged by stateFlag()
override fun clearError() {
super.clearError()
isEmptyRoots = false
isUnmerged = false
}
override fun buildErrorText(): String? =
when {
isEmptyRoots -> GitBundle.message("error.no.selected.roots.to.commit")
isUnmerged -> GitBundle.message("error.unresolved.conflicts")
isEmptyChanges && isEmptyMessage -> GitBundle.message("error.no.staged.changes.no.commit.message")
isEmptyChanges -> GitBundle.message("error.no.staged.changes.to.commit")
isEmptyMessage -> VcsBundle.message("error.no.commit.message")
else -> null
}
}
| apache-2.0 | 9e5987f134816d712443a7cf9231464a | 37.877698 | 140 | 0.758142 | 4.70322 | false | false | false | false |
GunoH/intellij-community | platform/util/ui/src/com/intellij/ui/scale/JBUIScale.kt | 2 | 13416 | // 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.ui.scale
import com.intellij.diagnostic.runActivity
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.ui.JreHiDpiUtil
import com.intellij.util.concurrency.SynchronizedClearableLazy
import com.intellij.util.ui.JBScalableIcon
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import java.awt.*
import java.beans.PropertyChangeListener
import java.beans.PropertyChangeSupport
import java.util.function.Supplier
import javax.swing.UIDefaults
import javax.swing.UIManager
import kotlin.math.abs
import kotlin.math.roundToInt
/**
* @author tav
*/
object JBUIScale {
@JvmField
@Internal
val SCALE_VERBOSE = java.lang.Boolean.getBoolean("ide.ui.scale.verbose")
private const val USER_SCALE_FACTOR_PROPERTY = "JBUIScale.userScaleFactor"
/**
* The user scale factor, see [ScaleType.USR_SCALE].
*/
private val userScaleFactor: SynchronizedClearableLazy<Float> = SynchronizedClearableLazy {
DEBUG_USER_SCALE_FACTOR.value ?: computeUserScaleFactor(if (JreHiDpiUtil.isJreHiDPIEnabled()) 1f else systemScaleFactor.value)
}
@Internal
fun preload(uiDefaults: Supplier<UIDefaults?>) {
if (!systemScaleFactor.isInitialized()) {
runActivity("system scale factor computation") {
computeSystemScaleFactor(uiDefaults).let {
systemScaleFactor.value = it
}
}
}
runActivity("user scale factor computation") {
userScaleFactor.value
}
getSystemFontData(uiDefaults)
}
private val systemScaleFactor: SynchronizedClearableLazy<Float> = SynchronizedClearableLazy {
computeSystemScaleFactor(uiDefaults = null)
}
private val PROPERTY_CHANGE_SUPPORT = PropertyChangeSupport(JBUIScale)
private const val DISCRETE_SCALE_RESOLUTION = 0.25f
@JvmField
var DEF_SYSTEM_FONT_SIZE = 12f
@JvmStatic
fun addUserScaleChangeListener(listener: PropertyChangeListener) {
PROPERTY_CHANGE_SUPPORT.addPropertyChangeListener(USER_SCALE_FACTOR_PROPERTY, listener)
}
@JvmStatic
fun removeUserScaleChangeListener(listener: PropertyChangeListener) {
PROPERTY_CHANGE_SUPPORT.removePropertyChangeListener(USER_SCALE_FACTOR_PROPERTY, listener)
}
private var systemFontData = SynchronizedClearableLazy<Pair<String?, Int>> {
runActivity("system font data computation") {
computeSystemFontData(null)
}
}
private fun computeSystemFontData(uiDefaults: Supplier<UIDefaults?>?): Pair<String, Int> {
if (GraphicsEnvironment.isHeadless()) {
return Pair("Dialog", 12)
}
// with JB Linux JDK the label font comes properly scaled based on Xft.dpi settings.
var font: Font
if (SystemInfoRt.isMac) {
// see AquaFonts.getControlTextFont() - lucida13Pt is hardcoded
// text family should be used for relatively small sizes (<20pt), don't change to Display
// see more about SF https://medium.com/@mach/the-secret-of-san-francisco-fonts-4b5295d9a745#.2ndr50z2v
font = Font(".SF NS Text", Font.PLAIN, 13)
DEF_SYSTEM_FONT_SIZE = font.size.toFloat()
}
else {
font = if (uiDefaults == null) UIManager.getFont("Label.font") else uiDefaults.get()!!.getFont("Label.font")
}
val log = thisLogger()
val isScaleVerbose = SCALE_VERBOSE
if (isScaleVerbose) {
log.info(String.format("Label font: %s, %d", font.fontName, font.size))
}
if (SystemInfoRt.isLinux) {
val value = Toolkit.getDefaultToolkit().getDesktopProperty("gnome.Xft/DPI")
if (isScaleVerbose) {
log.info(String.format("gnome.Xft/DPI: %s", value))
}
if (value is Int) { // defined by JB JDK when the resource is available in the system
// If the property is defined, then:
// 1) it provides correct system scale
// 2) the label font size is scaled
var dpi = value / 1024
if (dpi < 50) dpi = 50
val scale = if (JreHiDpiUtil.isJreHiDPIEnabled()) 1f else discreteScale(dpi / 96f) // no scaling in JRE-HiDPI mode
// derive actual system base font size
DEF_SYSTEM_FONT_SIZE = font.size / scale
if (isScaleVerbose) {
log.info(String.format("DEF_SYSTEM_FONT_SIZE: %.2f", DEF_SYSTEM_FONT_SIZE))
}
}
else if (!SystemInfo.isJetBrainsJvm) {
// With Oracle JDK: derive scale from X server DPI, do not change DEF_SYSTEM_FONT_SIZE
val size = DEF_SYSTEM_FONT_SIZE * screenScale
font = font.deriveFont(size)
if (isScaleVerbose) {
log.info(String.format("(Not-JB JRE) reset font size: %.2f", size))
}
}
}
else if (SystemInfoRt.isWindows) {
val winFont = Toolkit.getDefaultToolkit().getDesktopProperty("win.messagebox.font") as Font?
if (winFont != null) {
font = winFont // comes scaled
if (isScaleVerbose) {
log.info(String.format("Windows sys font: %s, %d", winFont.fontName, winFont.size))
}
}
}
val result = Pair(font.name, font.size)
if (isScaleVerbose) {
log.info(String.format("systemFontData: %s, %d", result.first, result.second))
}
return result
}
@Internal
@JvmField
val DEBUG_USER_SCALE_FACTOR: SynchronizedClearableLazy<Float?> = SynchronizedClearableLazy {
val prop = System.getProperty("ide.ui.scale")
when {
prop != null -> {
try {
return@SynchronizedClearableLazy prop.toFloat()
}
catch (e: NumberFormatException) {
thisLogger().error("ide.ui.scale system property is not a float value: $prop")
null
}
}
java.lang.Boolean.getBoolean("ide.ui.scale.override") -> 1f
else -> null
}
}
private fun computeSystemScaleFactor(uiDefaults: Supplier<UIDefaults?>?): Float {
if (!java.lang.Boolean.parseBoolean(System.getProperty("hidpi", "true"))) {
return 1f
}
if (JreHiDpiUtil.isJreHiDPIEnabled()) {
val gd = try {
GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice
}
catch (ignore: HeadlessException) {
null
}
val gc = gd?.defaultConfiguration
if (gc == null || gc.device.type == GraphicsDevice.TYPE_PRINTER) {
return 1f
}
else {
return gc.defaultTransform.scaleX.toFloat()
}
}
val result = getFontScale(getSystemFontData(uiDefaults).second.toFloat())
thisLogger().info("System scale factor: $result (${if (JreHiDpiUtil.isJreHiDPIEnabled()) "JRE" else "IDE"}-managed HiDPI)")
return result
}
@TestOnly
@JvmStatic
fun setSystemScaleFactor(sysScale: Float) {
systemScaleFactor.value = sysScale
}
@TestOnly
@JvmStatic
fun setUserScaleFactorForTest(value: Float) {
setUserScaleFactorProperty(value)
}
private fun setUserScaleFactorProperty(value: Float) {
val oldValue = userScaleFactor.valueIfInitialized
if (oldValue == value) {
return
}
userScaleFactor.value = value
thisLogger().info("User scale factor: $value")
PROPERTY_CHANGE_SUPPORT.firePropertyChange(USER_SCALE_FACTOR_PROPERTY, oldValue, value)
}
/**
* @return the scale factor of `fontSize` relative to the standard font size (currently 12pt)
*/
@JvmStatic
fun getFontScale(fontSize: Float): Float {
return fontSize / DEF_SYSTEM_FONT_SIZE
}
/**
* Sets the user scale factor.
* The method is used by the IDE, it's not recommended to call the method directly from the client code.
* For debugging purposes, the following JVM system property can be used:
* ide.ui.scale=float
* or the IDE registry keys (for backward compatibility):
* ide.ui.scale.override=boolean
* ide.ui.scale=float
*
* @return the result
*/
@Internal
@JvmStatic
fun setUserScaleFactor(value: Float): Float {
var scale = value
val factor = DEBUG_USER_SCALE_FACTOR.value
if (factor != null) {
if (scale == factor) {
// set the debug value as is, or otherwise ignore
setUserScaleFactorProperty(factor)
}
return factor
}
scale = computeUserScaleFactor(scale)
setUserScaleFactorProperty(scale)
return scale
}
private fun computeUserScaleFactor(value: Float): Float {
var scale = value
if (!java.lang.Boolean.parseBoolean(System.getProperty("hidpi", "true"))) {
return 1f
}
scale = discreteScale(scale)
// downgrading user scale below 1.0 may be uncomfortable (tiny icons),
// whereas some users prefer font size slightly below normal which is ok
if (scale < 1 && systemScaleFactor.value >= 1) {
scale = 1f
}
// ignore the correction when UIUtil.DEF_SYSTEM_FONT_SIZE is overridden, see UIUtil.initSystemFontData
if (SystemInfoRt.isLinux && scale == 1.25f && DEF_SYSTEM_FONT_SIZE == 12f) {
// Default UI font size for Unity and Gnome is 15. Scaling factor 1.25f works badly on Linux.
return 1f
}
else {
return scale
}
}
private fun discreteScale(scale: Float): Float {
return (scale / DISCRETE_SCALE_RESOLUTION).roundToInt() * DISCRETE_SCALE_RESOLUTION
}
/**
* The system scale factor, corresponding to the default monitor device.
*/
@JvmStatic
fun sysScale(): Float = systemScaleFactor.value
/**
* Returns the system scale factor, corresponding to the device the component is tied to.
* In the IDE-managed HiDPI mode defaults to [.sysScale]
*/
@JvmStatic
fun sysScale(component: Component?): Float {
return if (component == null) sysScale() else sysScale(component.graphicsConfiguration)
}
/**
* Returns the system scale factor, corresponding to the graphics configuration.
* In the IDE-managed HiDPI mode defaults to [.sysScale]
*/
@JvmStatic
fun sysScale(gc: GraphicsConfiguration?): Float {
if (JreHiDpiUtil.isJreHiDPIEnabled() && gc != null && gc.device.type != GraphicsDevice.TYPE_PRINTER) {
return gc.defaultTransform.scaleX.toFloat()
}
else {
return systemScaleFactor.value
}
}
/**
* @return 'f' scaled by the user scale factor
*/
@JvmStatic
fun scale(f: Float): Float {
return f * userScaleFactor.value
}
/**
* @return 'i' scaled by the user scale factor
*/
@JvmStatic
fun scale(i: Int): Int {
return (userScaleFactor.value * i).roundToInt()
}
/**
* Scales the passed `icon` according to the user scale factor.
*
* @see ScaleType.USR_SCALE
*/
@JvmStatic
fun <T : JBScalableIcon> scaleIcon(icon: T): T {
@Suppress("UNCHECKED_CAST")
return icon.withIconPreScaled(false) as T
}
@JvmStatic
fun scaleFontSize(fontSize: Float): Int {
return scaleFontSize(fontSize, userScaleFactor.value)
}
@Internal
@JvmStatic
fun scaleFontSize(fontSize: Float, userScaleFactor: Float): Int {
return when (userScaleFactor) {
1.25f -> fontSize * 1.34f
1.75f -> fontSize * 1.67f
else -> fontSize * userScaleFactor
}.toInt()
}
private val screenScale: Float
get() {
val dpi = try {
Toolkit.getDefaultToolkit().screenResolution
}
catch (ignored: HeadlessException) {
96
}
return discreteScale(dpi / 96f)
}
@JvmStatic
fun getSystemFontData(uiDefaults: Supplier<UIDefaults?>?): Pair<String?, Int> {
if (uiDefaults == null) {
return systemFontData.value
}
systemFontData.valueIfInitialized?.let {
return it
}
return computeSystemFontData(uiDefaults).also { systemFontData.value = it }
}
/**
* Returns the system scale factor, corresponding to the graphics.
* This is a convenience method allowing to avoid casting to `Graphics2D`
* on the calling side.
*/
@JvmStatic
fun sysScale(g: Graphics?): Float = sysScale(g as? Graphics2D?)
/**
* Returns the system scale factor, corresponding to the graphics.
* For BufferedImage's graphics, the scale is taken from the graphics itself.
* In the IDE-managed HiDPI mode defaults to [.sysScale]
*/
@JvmStatic
fun sysScale(g: Graphics2D?): Float {
if (g == null || !JreHiDpiUtil.isJreHiDPIEnabled()) {
return sysScale()
}
val gc = g.deviceConfiguration
if (gc == null || gc.device.type == GraphicsDevice.TYPE_IMAGE_BUFFER || gc.device.type == GraphicsDevice.TYPE_PRINTER) {
// in this case gc doesn't provide a valid scale
return abs(g.transform.scaleX.toFloat())
}
else {
return sysScale(gc)
}
}
@JvmStatic
fun sysScale(context: ScaleContext?): Double {
return context?.getScale(ScaleType.SYS_SCALE) ?: sysScale().toDouble()
}
/**
* Returns whether the provided scale assumes HiDPI-awareness.
*/
@JvmStatic
fun isHiDPI(scale: Double): Boolean {
// Scale below 1.0 is impractical, it's rather accepted for debug purpose.
// Treat it as "hidpi" to correctly manage images which have different user and real size
// (for scale below 1.0 the real size will be smaller).
return scale != 1.0
}
/**
* Returns whether the [ScaleType.USR_SCALE] scale factor assumes HiDPI-awareness. An equivalent of `isHiDPI(scale(1f))`
*/
@JvmStatic
val isUsrHiDPI: Boolean
get() = isHiDPI(scale(1f).toDouble())
} | apache-2.0 | c971c7b4068361a0119613ae81a6cbd7 | 30.275058 | 130 | 0.677102 | 4.248258 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantElvisReturnNullInspection.kt | 5 | 2926 | // 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.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class RedundantElvisReturnNullInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return returnExpressionVisitor(fun(returnExpression: KtReturnExpression) {
if ((returnExpression.returnedExpression?.deparenthesize() as? KtConstantExpression)?.text != KtTokens.NULL_KEYWORD.value) return
val binaryExpression = returnExpression.getStrictParentOfType<KtBinaryExpression>()?.takeIf {
it == it.getStrictParentOfType<KtReturnExpression>()?.returnedExpression?.deparenthesize()
} ?: return
val right = binaryExpression.right?.deparenthesize()?.takeIf { it == returnExpression } ?: return
if (binaryExpression.operationToken == KtTokens.ELSE_KEYWORD) return
if (binaryExpression.left?.resolveToCall()?.resultingDescriptor?.returnType?.isMarkedNullable != true) return
holder.registerProblem(
binaryExpression,
KotlinBundle.message("inspection.redundant.elvis.return.null.descriptor"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
TextRange(binaryExpression.operationReference.startOffset, right.endOffset).shiftLeft(binaryExpression.startOffset),
RemoveRedundantElvisReturnNull()
)
})
}
private fun KtExpression.deparenthesize() = KtPsiUtil.deparenthesize(this)
private class RemoveRedundantElvisReturnNull : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.elvis.return.null.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val binaryExpression = descriptor.psiElement as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
binaryExpression.replace(left)
}
}
}
| apache-2.0 | 5b2edd3e2ddd094438d5a9fd7bbf79dc | 50.333333 | 141 | 0.752221 | 5.573333 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinCallerChooser.kt | 5 | 5532 | // 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.refactoring.changeSignature.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiClassOwner
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiReference
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.changeSignature.CallerChooserBase
import com.intellij.refactoring.changeSignature.MemberNodeBase
import com.intellij.ui.ColoredTreeCellRenderer
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.Consumer
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor
import org.jetbrains.kotlin.idea.hierarchy.calls.CalleeReferenceProcessor
import org.jetbrains.kotlin.idea.hierarchy.calls.KotlinCallHierarchyNodeDescriptor
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
class KotlinCallerChooser(
declaration: PsiElement,
project: Project,
@NlsContexts.DialogTitle title: String,
previousTree: Tree?,
callback: Consumer<in Set<PsiElement>>
) : CallerChooserBase<PsiElement>(declaration, project, title, previousTree, "dummy." + KotlinFileType.EXTENSION, callback) {
override fun createTreeNodeFor(method: PsiElement?, called: HashSet<PsiElement>?, cancelCallback: Runnable?) =
KotlinMethodNode(method, called ?: HashSet(), myProject, cancelCallback ?: Runnable {})
override fun findDeepestSuperMethods(method: PsiElement) = method.toLightMethods().singleOrNull()?.findDeepestSuperMethods()
override fun getEmptyCallerText() = KotlinBundle.message("text.caller.text.with.highlighted.callee.call.would.be.shown.here")
override fun getEmptyCalleeText() = KotlinBundle.message("text.callee.text.would.be.shown.here")
}
class KotlinMethodNode(
method: PsiElement?,
called: HashSet<PsiElement>,
project: Project,
cancelCallback: Runnable
) : MemberNodeBase<PsiElement>(method?.namedUnwrappedElement ?: method, called, project, cancelCallback) {
override fun createNode(caller: PsiElement, called: HashSet<PsiElement>) = KotlinMethodNode(caller, called, myProject, myCancelCallback)
override fun customizeRendererText(renderer: ColoredTreeCellRenderer) {
val method = myMethod
val descriptor = when (method) {
is KtFunction -> method.unsafeResolveToDescriptor() as FunctionDescriptor
is KtClass -> (method.unsafeResolveToDescriptor() as ClassDescriptor).unsubstitutedPrimaryConstructor ?: return
is PsiMethod -> method.getJavaMethodDescriptor() ?: return
else -> throw AssertionError("Invalid declaration: ${method.getElementTextWithContext()}")
}
val containerName = generateSequence<DeclarationDescriptor>(descriptor) { it.containingDeclaration }
.firstOrNull { it is ClassDescriptor }
?.name
val renderedFunction = KotlinCallHierarchyNodeDescriptor.renderNamedFunction(descriptor)
val renderedFunctionWithContainer = containerName?.let {
@NlsSafe
val name = "${if (it.isSpecial) KotlinBundle.message("text.anonymous") else it.asString()}.$renderedFunction"
name
} ?: renderedFunction
val attributes = if (isEnabled)
SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, UIUtil.getTreeForeground())
else
SimpleTextAttributes.EXCLUDED_ATTRIBUTES
renderer.append(renderedFunctionWithContainer, attributes)
val packageName = (method.containingFile as? PsiClassOwner)?.packageName ?: ""
renderer.append(" ($packageName)", SimpleTextAttributes(SimpleTextAttributes.STYLE_ITALIC, JBColor.GRAY))
}
override fun computeCallers(): List<PsiElement> {
if (myMethod == null) return emptyList()
val callers = LinkedHashSet<PsiElement>()
val processor = object : CalleeReferenceProcessor(false) {
override fun onAccept(ref: PsiReference, element: PsiElement) {
if ((element is KtFunction || element is KtClass || element is PsiMethod) && element !in myCalled) {
callers.add(element)
}
}
}
val query = myMethod.getRepresentativeLightMethod()
?.let { MethodReferencesSearch.search(it, it.useScope(), true) }
?: ReferencesSearch.search(myMethod, myMethod.useScope())
query.forEach { processor.process(it) }
return callers.toList()
}
} | apache-2.0 | c138ab804549632a8e31b346336ade14 | 47.964602 | 140 | 0.756688 | 5.038251 | false | false | false | false |
ftomassetti/kolasu | emf/src/main/kotlin/com/strumenta/kolasu/emf/MetamodelBuilder.kt | 1 | 13252 | package com.strumenta.kolasu.emf
import com.strumenta.kolasu.model.PropertyTypeDescription
import com.strumenta.kolasu.model.processProperties
import org.eclipse.emf.ecore.*
import org.eclipse.emf.ecore.resource.Resource
import java.util.*
import kotlin.reflect.*
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.superclasses
import kotlin.reflect.full.withNullability
private val KClass<*>.packageName: String?
get() {
val qname = this.qualifiedName ?: throw IllegalStateException("The class has no qualified name: $this")
return if (qname == this.simpleName) {
null
} else {
require(qname.endsWith(".${this.simpleName}"))
qname.removeSuffix(".${this.simpleName}")
}
}
/**
* When building multiple related EPackages use MetamodelsBuilder instead.
*/
class MetamodelBuilder(packageName: String, nsURI: String, nsPrefix: String, resource: Resource? = null) :
ClassifiersProvider {
private val ePackage: EPackage = EcoreFactory.eINSTANCE.createEPackage()
private val eClasses = HashMap<KClass<*>, EClass>()
private val dataTypes = HashMap<KType, EDataType>()
private val eclassTypeHandlers = LinkedList<EClassTypeHandler>()
private val dataTypeHandlers = LinkedList<EDataTypeHandler>()
internal var container: MetamodelsBuilder? = null
init {
ePackage.name = packageName
ePackage.nsURI = nsURI
ePackage.nsPrefix = nsPrefix
if (resource == null) {
ePackage.setResourceURI(nsURI)
} else {
resource.contents.add(ePackage)
eclassTypeHandlers.add(ResourceClassTypeHandler(resource, ePackage))
}
dataTypeHandlers.add(StringHandler)
dataTypeHandlers.add(CharHandler)
dataTypeHandlers.add(BooleanHandler)
dataTypeHandlers.add(IntHandler)
dataTypeHandlers.add(IntegerHandler)
dataTypeHandlers.add(FloatHandler)
dataTypeHandlers.add(DoubleHandler)
dataTypeHandlers.add(LongHandler)
dataTypeHandlers.add(BigIntegerHandler)
dataTypeHandlers.add(BigDecimalHandler)
eclassTypeHandlers.add(LocalDateHandler)
eclassTypeHandlers.add(LocalTimeHandler)
eclassTypeHandlers.add(LocalDateTimeHandler)
eclassTypeHandlers.add(NodeHandler)
eclassTypeHandlers.add(NamedHandler)
eclassTypeHandlers.add(PositionHandler)
eclassTypeHandlers.add(PossiblyNamedHandler)
eclassTypeHandlers.add(ReferenceByNameHandler)
eclassTypeHandlers.add(ResultHandler)
eclassTypeHandlers.add(StatementHandler)
eclassTypeHandlers.add(ExpressionHandler)
eclassTypeHandlers.add(EntityDeclarationHandler)
}
/**
* Normally a class is not treated as a DataType, so we need specific DataTypeHandlers
* to recognize it as such
*/
fun addDataTypeHandler(eDataTypeHandler: EDataTypeHandler) {
dataTypeHandlers.add(eDataTypeHandler)
}
/**
* This should be needed only to customize how we want to deal with a class when translating
* it to an EClass
*/
fun addEClassTypeHandler(eClassTypeHandler: EClassTypeHandler) {
eclassTypeHandlers.add(eClassTypeHandler)
}
private fun createEEnum(kClass: KClass<out Enum<*>>): EEnum {
val eEnum = EcoreFactory.eINSTANCE.createEEnum()
eEnum.name = kClass.eClassifierName
kClass.java.enumConstants.forEach {
val eLiteral = EcoreFactory.eINSTANCE.createEEnumLiteral()
eLiteral.name = it.name
eLiteral.value = it.ordinal
eEnum.eLiterals.add(eLiteral)
}
return eEnum
}
override fun provideDataType(ktype: KType): EDataType? {
if (!dataTypes.containsKey(ktype)) {
val eDataType: EDataType
var external = false
when {
(ktype.classifier as? KClass<*>)?.isSubclassOf(Enum::class) == true -> {
eDataType = createEEnum(ktype.classifier as KClass<out Enum<*>>)
}
else -> {
val handler = dataTypeHandlers.find { it.canHandle(ktype) }
if (handler == null) {
// throw RuntimeException("Unable to handle data type $ktype, with classifier ${ktype.classifier}")\
return null
} else {
external = handler.external()
eDataType = handler.toDataType(ktype)
}
}
}
if (!external) {
ensureClassifierNameIsNotUsed(eDataType)
ePackage.eClassifiers.add(eDataType)
}
dataTypes[ktype] = eDataType
}
return dataTypes[ktype]!!
}
private fun classToEClass(kClass: KClass<*>): EClass {
if (kClass == Any::class) {
return EcoreFactory.eINSTANCE.ecorePackage.eObject
}
if (kClass.packageName != this.ePackage.name) {
if (container != null) {
for (sibling in container!!.singleMetamodelsBuilders) {
if (sibling.canProvideClass(kClass)) {
return sibling.provideClass(kClass)
}
}
}
throw Error(
"This class does not belong to this EPackage: ${kClass.qualifiedName}. " +
"This EPackage: ${this.ePackage.name}"
)
}
val eClass = EcoreFactory.eINSTANCE.createEClass()
// This is necessary because some classes refer to themselves
registerKClassForEClass(kClass, eClass)
kClass.superclasses.forEach {
if (it != Any::class) {
eClass.eSuperTypes.add(provideClass(it))
}
}
eClass.name = kClass.eClassifierName
eClass.isAbstract = kClass.isAbstract || kClass.isSealed
eClass.isInterface = kClass.java.isInterface
kClass.typeParameters.forEach { kTypeParameter: KTypeParameter ->
eClass.eTypeParameters.add(
EcoreFactory.eINSTANCE.createETypeParameter().apply {
// TODO consider bounds, taking in account that in Kotlin we have variance (in/out)
// which may not exactly correspond to how bounds work in EMF
name = kTypeParameter.name
}
)
}
kClass.processProperties { prop ->
try {
if (eClass.eAllStructuralFeatures.any { sf -> sf.name == prop.name }) {
// skip
} else {
// do not process inherited properties
val valueType = prop.valueType
if (prop.provideNodes) {
registerReference(prop, valueType, eClass)
} else {
val nullable = prop.valueType.isMarkedNullable
val dataType = provideDataType(prop.valueType.withNullability(false))
if (dataType == null) {
// We can treat it like a class
registerReference(prop, valueType, eClass)
} else {
val ea = EcoreFactory.eINSTANCE.createEAttribute()
ea.name = prop.name
if (prop.multiple) {
ea.lowerBound = 0
ea.upperBound = -1
} else {
ea.lowerBound = if (nullable) 0 else 1
ea.upperBound = 1
}
ea.eType = dataType
eClass.eStructuralFeatures.add(ea)
}
}
}
} catch (e: Exception) {
throw RuntimeException("Issue processing property $prop in class $kClass", e)
}
}
return eClass
}
private fun registerReference(
prop: PropertyTypeDescription,
valueType: KType,
eClass: EClass
) {
val ec = EcoreFactory.eINSTANCE.createEReference()
ec.name = prop.name
if (prop.multiple) {
ec.lowerBound = 0
ec.upperBound = -1
} else {
ec.lowerBound = 0
ec.upperBound = 1
}
ec.isContainment = true
// No type parameters on methods should be allowed elsewhere and only the type parameters
// on the class should be visible. We are not expecting containing classes to expose
// type parameters
val visibleTypeParameters = eClass.eTypeParameters.associateBy { it.name }
setType(ec, valueType, visibleTypeParameters)
eClass.eStructuralFeatures.add(ec)
}
private fun provideType(valueType: KTypeProjection): EGenericType {
when (valueType.variance) {
KVariance.INVARIANT -> {
return provideType(valueType.type!!)
}
else -> TODO("Variance ${valueType.variance} not yet sypported")
}
}
private fun provideType(valueType: KType): EGenericType {
val dataType = provideDataType(valueType.withNullability(false))
if (dataType != null) {
return EcoreFactory.eINSTANCE.createEGenericType().apply {
eClassifier = dataType
}
}
if (valueType.arguments.isNotEmpty()) {
TODO("Not yet supported: type arguments in $valueType")
}
if (valueType.classifier is KClass<*>) {
return EcoreFactory.eINSTANCE.createEGenericType().apply {
eClassifier = provideClass(valueType.classifier as KClass<*>)
}
} else {
TODO("Not yet supported: ${valueType.classifier}")
}
}
private fun setType(
element: ETypedElement,
valueType: KType,
visibleTypeParameters: Map<String, ETypeParameter>
) {
when (val classifier = valueType.classifier) {
is KClass<*> -> {
if (classifier.typeParameters.isEmpty()) {
element.eType = provideClass(classifier)
} else {
element.eGenericType = EcoreFactory.eINSTANCE.createEGenericType().apply {
eClassifier = provideClass(classifier)
require(classifier.typeParameters.size == valueType.arguments.size)
eTypeArguments.addAll(
valueType.arguments.map {
provideType(it)
}
)
}
}
}
is KTypeParameter -> {
element.eGenericType = EcoreFactory.eINSTANCE.createEGenericType().apply {
eTypeParameter = visibleTypeParameters[classifier.name]
?: throw IllegalStateException("Type parameter not found")
}
}
else -> throw Error("Not a valid classifier: $classifier")
}
}
private fun ensureClassifierNameIsNotUsed(classifier: EClassifier) {
if (ePackage.hasClassifierNamed(classifier.name)) {
throw IllegalStateException(
"There is already a Classifier named ${classifier.name}: ${ePackage.classifierByName(classifier.name)}"
)
}
}
private fun registerKClassForEClass(kClass: KClass<*>, eClass: EClass) {
if (eClasses.containsKey(kClass)) {
require(eClasses[kClass] == eClass)
} else {
eClasses[kClass] = eClass
}
}
fun canProvideClass(kClass: KClass<*>): Boolean {
if (eClasses.containsKey(kClass)) {
return true
}
if (eclassTypeHandlers.any { it.canHandle(kClass) }) {
return true
}
if (kClass == Any::class) {
return true
}
return kClass.packageName == this.ePackage.name
}
override fun provideClass(kClass: KClass<*>): EClass {
if (!eClasses.containsKey(kClass)) {
val ch = eclassTypeHandlers.find { it.canHandle(kClass) }
val eClass = ch?.toEClass(kClass, this) ?: classToEClass(kClass)
if (kClass.packageName != this.ePackage.name) {
return eClass
}
if (ch == null || !ch.external()) {
ensureClassifierNameIsNotUsed(eClass)
ePackage.eClassifiers.add(eClass)
}
registerKClassForEClass(kClass, eClass)
if (kClass.isSealed) {
kClass.sealedSubclasses.forEach {
queue.add(it)
}
}
}
while (queue.isNotEmpty()) {
provideClass(queue.removeFirst())
}
return eClasses[kClass]!!
}
private val queue = LinkedList<KClass<*>>()
fun generate(): EPackage {
return ePackage
}
}
| apache-2.0 | 8271e20697de6ce69f6e53008e646317 | 36.647727 | 124 | 0.567009 | 5.352181 | false | false | false | false |
BlueHuskyStudios/BHToolbox | BHToolbox/src/org/bh/tools/ui/LookAndFeelChanger.kt | 1 | 4646 | package org.bh.tools.ui
import com.sun.java.swing.plaf.motif.MotifLookAndFeel
import org.bh.tools.ui.LafChangeErrorType.*
import org.bh.tools.util.MutableArrayPP
import java.awt.Window
import java.awt.event.ActionListener
import javax.swing.UIManager
import javax.swing.UnsupportedLookAndFeelException
import javax.swing.plaf.metal.MetalLookAndFeel
import javax.swing.plaf.nimbus.NimbusLookAndFeel
/**
* Copyright BHStudios ©2016 BH-1-PS. Made for BH Tic Tac Toe IntelliJ Project.
*
* A convenience class for changing the Java Look-And-Feel.
*
* @author Ben Leggiero
* @since 2016-10-01
* @version 2.0.0
*/
class LookAndFeelChanger {
companion object {
private var _changeListeners = MutableArrayPP<LafChangeListener>()
internal val _defaultLaf = UIManager.getLookAndFeel()
fun setLookAndFeel(lafEnum: LookAndFeelEnum,
force: Boolean = false,
errorHandler: LafChangeErrorHandler = NullLafChangeErrorHandler) {
setLookAndFeel(className = lafEnum.lafClassName, force = force, errorHandler = errorHandler)
}
@Throws(UnsupportedLookAndFeelException::class, ClassNotFoundException::class, InstantiationException::class, IllegalAccessException::class)
fun setLookAndFeel(className: CharSequence, force: Boolean = false, errorHandler: LafChangeErrorHandler) {
if (!force && UIManager.getLookAndFeel().javaClass.name == className) {
return
}
val previousLaf = UIManager.getLookAndFeel()
try {
UIManager.setLookAndFeel(className.toString())
val windows = Window.getWindows()
var isFrame: Boolean
var state: Int
for (i in windows.indices) {
val r = java.awt.Rectangle(windows[i].bounds)//Changed to new rather than assignment {Feb 22, 2012 (1.1.1) for Marian}
isFrame = windows[i] is java.awt.Frame
state = if (isFrame) (windows[i] as java.awt.Frame).state else java.awt.Frame.NORMAL
// windows[i].pack();//Commented out Feb 27, 2012 (1.1.1) for Marian - Though it makes the window look better in the end, it introduces unneeded lag and interfered with CompAction animations
javax.swing.SwingUtilities.updateComponentTreeUI(windows[i])
if (isFrame) {
(windows[i] as java.awt.Frame).state = state
}
if (!isFrame || state != java.awt.Frame.MAXIMIZED_BOTH) {
windows[i].bounds = r
}
}
} catch (ex: UnsupportedLookAndFeelException) {
UIManager.setLookAndFeel(previousLaf)
} catch (t: Throwable) {
try {
UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName())
} catch (t2: ClassNotFoundException) {
errorHandler(NotALaf)
} catch (t2: InstantiationException) {
errorHandler(CouldNotCreateLaf)
} catch (t2: IllegalAccessException) {
errorHandler(InaccessibleLafConstructor)
} catch (t2: UnsupportedLookAndFeelException) {
errorHandler(UnsupportedLaf)
} catch (t2: Throwable) {
errorHandler(UnknownError)
}
}
val evt = LafChangeEvent()
for (changeListener in _changeListeners)
changeListener?.lafChanged(evt)
}
// val _systemLaf: LookAndFeel by lazy { Class.forName(UIManager.getSystemLookAndFeelClassName()).newInstance() as LookAndFeel }
}
}
enum class LookAndFeelEnum(val lafClassName: CharSequence) {
Default(LookAndFeelChanger._defaultLaf.javaClass.name),
System(UIManager.getSystemLookAndFeelClassName()),
Metal(MetalLookAndFeel::class.java.name),
Nimbus(NimbusLookAndFeel::class.java.name),
Motif(MotifLookAndFeel::class.java.name),
}
typealias LafChangeErrorHandler = (type: LafChangeErrorType) -> Unit
val NullLafChangeErrorHandler: LafChangeErrorHandler = { x -> }
enum class LafChangeErrorType {
NotALaf,
CouldNotCreateLaf,
InaccessibleLafConstructor,
UnsupportedLaf,
UnknownError
}
class LafChangeEvent() {
}
interface LafChangeListener : ActionListener {
fun lafChanged(event: LafChangeEvent)
}
| gpl-3.0 | 4fab45794552a54c040361d671ea058a | 40.227273 | 217 | 0.620022 | 4.889474 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/ui/offlinebasemap/OfflineAreasFragment.kt | 1 | 2617 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.offlinebasemap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.ground.MainActivity
import com.google.android.ground.databinding.OfflineBaseMapsFragBinding
import com.google.android.ground.ui.common.AbstractFragment
import com.google.android.ground.ui.common.Navigator
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* Fragment containing a list of downloaded areas on the device. An area is a set of offline raster
* tiles. Users can manage their areas within this fragment. They can delete areas they no longer
* need or access the UI used to select and download a new area to the device.
*/
@AndroidEntryPoint
class OfflineAreasFragment : AbstractFragment() {
@Inject lateinit var navigator: Navigator
private lateinit var offlineAreaListAdapter: OfflineAreaListAdapter
private lateinit var viewModel: OfflineAreasViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = getViewModel(OfflineAreasViewModel::class.java)
offlineAreaListAdapter = OfflineAreaListAdapter(navigator)
viewModel.offlineAreas.observe(this) { offlineAreaListAdapter.update(it) }
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
super.onCreateView(inflater, container, savedInstanceState)
val binding = OfflineBaseMapsFragBinding.inflate(inflater, container, false)
binding.viewModel = viewModel
binding.lifecycleOwner = this
(requireActivity() as MainActivity).setActionBar(binding.offlineAreasToolbar, true)
val recyclerView = binding.offlineAreasList
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = offlineAreaListAdapter
return binding.root
}
}
| apache-2.0 | 81a1a294fbfdb286d1e346f8ad31b239 | 37.485294 | 99 | 0.788307 | 4.766849 | false | false | false | false |
Frederikam/FredBoat | FredBoat/src/main/java/fredboat/event/MessageEventHandler.kt | 1 | 7722 | /*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* 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 fredboat.event
import com.fredboat.sentinel.entities.MessageReceivedEvent
import com.google.common.cache.CacheBuilder
import fredboat.command.info.HelpCommand
import fredboat.command.info.ShardsCommand
import fredboat.command.info.StatsCommand
import fredboat.commandmeta.CommandContextParser
import fredboat.commandmeta.CommandInitializer
import fredboat.commandmeta.CommandManager
import fredboat.commandmeta.abs.CommandContext
import fredboat.config.property.AppConfigProperties
import fredboat.definitions.PermissionLevel
import fredboat.feature.metrics.Metrics
import fredboat.perms.Permission.MESSAGE_READ
import fredboat.perms.Permission.MESSAGE_WRITE
import fredboat.perms.PermissionSet
import fredboat.perms.PermsUtil
import fredboat.sentinel.InternalGuild
import fredboat.sentinel.Sentinel
import fredboat.sentinel.User
import fredboat.sentinel.getGuild
import fredboat.util.ratelimit.Ratelimiter
import io.prometheus.client.guava.cache.CacheMetricsCollector
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit
@Component
class MessageEventHandler(
private val sentinel: Sentinel,
private val ratelimiter: Ratelimiter,
private val commandContextParser: CommandContextParser,
private val commandManager: CommandManager,
private val appConfig: AppConfigProperties,
cacheMetrics: CacheMetricsCollector
) : SentinelEventHandler() {
companion object {
private val log: Logger = LoggerFactory.getLogger(MessageEventHandler::class.java)
// messageId <-> messageId
val messagesToDeleteIfIdDeleted = CacheBuilder.newBuilder()
.recordStats()
.expireAfterWrite(6, TimeUnit.HOURS)
.build<Long, Long>()!!
}
init {
cacheMetrics.addCache("messagesToDeleteIfIdDeleted", messagesToDeleteIfIdDeleted)
}
override fun onGuildMessage(event: MessageReceivedEvent) {
if (ratelimiter.isBlacklisted(event.author)) {
Metrics.blacklistedMessagesReceived.inc()
return
}
if (sentinel.selfUser.id == event.author) log.info(if(event.content.isBlank()) "<empty>" else event.content)
if (event.fromBot) return
//Preliminary permission filter to avoid a ton of parsing
//Let messages pass on to parsing that contain "help" since we want to answer help requests even from channels
// where we can't talk in
val permissions = PermissionSet(event.channelPermissions)
if (permissions hasNot (MESSAGE_READ + MESSAGE_WRITE)
&& !event.content.contains(CommandInitializer.HELP_COMM_NAME)) return
GlobalScope.launch {
val context = commandContextParser.parse(event) ?: return@launch
// Renew the time to prevent invalidation
(context.guild as InternalGuild).lastUsed = System.currentTimeMillis()
log.info(event.content)
//ignore all commands in channels where we can't write, except for the help command
if (permissions hasNot (MESSAGE_READ + MESSAGE_WRITE) && context.command !is HelpCommand) {
log.info("Ignoring command {} because this bot cannot write in that channel", context.command.name)
return@launch
}
Metrics.commandsReceived.labels(context.command.javaClass.simpleName).inc()
//ignore commands of disabled modules for plebs
//BOT_ADMINs can always use all commands everywhere
val module = context.command.module
if (module != null
&& !context.enabledModules.contains(module)
&& !PermsUtil.checkPerms(PermissionLevel.BOT_ADMIN, context.member)) {
log.debug("Ignoring command {} because its module {} is disabled",
context.command.name, module.name)
return@launch
}
limitOrExecuteCommand(context)
}
}
/**
* Check the rate limit of the user and execute the command if everything is fine.
* @param context Command context of the command to be invoked.
*/
private suspend fun limitOrExecuteCommand(context: CommandContext) {
if (ratelimiter.isRatelimited(context, context.command)) {
return
}
Metrics.executionTime.labels(context.command.javaClass.simpleName).startTimer().use {
commandManager.prefixCalled(context)
}
//NOTE: Some commands, like ;;mal, run async and will not reflect the real performance of FredBoat
// their performance should be judged by the totalResponseTime metric instead
}
override fun onPrivateMessage(author: User, content: String) {
if (ratelimiter.isBlacklisted(author.id)) {
Metrics.blacklistedMessagesReceived.inc()
return
}
//Technically not possible anymore to receive private messages from bots but better safe than sorry
//Also ignores our own messages since we're a bot
if (author.isBot) {
return
}
//quick n dirty bot admin / owner check
if (appConfig.adminIds.contains(author.id) || sentinel.applicationInfo.ownerId == author.id) {
//hack in / hardcode some commands; this is not meant to look clean
val lowered = content.toLowerCase()
if (lowered.contains("shard")) {
GlobalScope.launch {
for (message in ShardsCommand.getShardStatus(author.sentinel, content)) {
author.sendPrivate(message).subscribe()
}
}
return
} else if (lowered.contains("stats")) {
GlobalScope.launch {
author.sendPrivate(StatsCommand.getStats(null)).subscribe()
}
return
}
}
HelpCommand.sendGeneralHelp(author, content)
}
override fun onGuildMessageDelete(guildId: Long, channelId: Long, messageId: Long) {
val toDelete = messagesToDeleteIfIdDeleted.getIfPresent(messageId) ?: return
messagesToDeleteIfIdDeleted.invalidate(toDelete)
getGuild(guildId) { guild ->
val channel = guild.getTextChannel(channelId) ?: return@getGuild
sentinel.deleteMessages(channel, listOf(toDelete)).subscribe()
}
}
} | mit | 7bb2aa5ccd59d02b9182c4d5c0444107 | 40.299465 | 118 | 0.686739 | 5.001295 | false | false | false | false |
Kerooker/rpg-npc-generator | app/src/main/java/me/kerooker/rpgnpcgenerator/view/random/npc/RandomNpcListView.kt | 1 | 5311 | package me.kerooker.rpgnpcgenerator.view.random.npc
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import kotlinx.android.synthetic.main.randomnpc_element_list_view.view.add_item_button
import kotlinx.android.synthetic.main.randomnpc_element_list_view.view.add_item_text
import kotlinx.android.synthetic.main.randomnpc_element_list_view.view.list
import me.kerooker.rpgnpcgenerator.R
interface OnPositionedRandomizeClick {
fun onRandomClick(index: Int)
}
interface OnPositionedDeleteClick {
fun onDeleteClick(index: Int)
}
interface IndexedManualInputListener {
fun onManualInput(index: Int, text: String)
}
class RandomNpcListView(
context: Context,
attrs: AttributeSet
) : ConstraintLayout(context, attrs) {
private val listView by lazy { list }
private val adapter by lazy { RandomNpcListAdapter(listView) }
init {
View.inflate(context, R.layout.randomnpc_element_list_view, this)
val attributes = context.obtainStyledAttributes(attrs, R.styleable.RandomNpcListView)
adapter.hint = attributes.getString(R.styleable.RandomNpcListView_list_hint)!!
attributes.recycle()
add_item_button.setOnClickListener { addItem() }
add_item_text.setOnClickListener { addItem() }
}
private fun addItem() {
val nextIndex = listView.childCount
adapter.onPositionedRandomizeClick.onRandomClick(nextIndex)
scrollToAddButton()
}
@Suppress("MagicNumber")
private fun scrollToAddButton() {
postDelayed(
{
val addButton = add_item_button
val rect = Rect(0, 0, addButton.width, addButton.height)
addButton.requestRectangleOnScreen(rect, false)
}, 100
)
}
fun setElements(elements: List<String>) {
adapter.elements = elements
}
fun setOnPositionedRandomizeClick(onPositionedRandomizeClick: OnPositionedRandomizeClick) {
adapter.onPositionedRandomizeClick = onPositionedRandomizeClick
}
fun setOnPositionedDeleteClick(onPositionedDeleteClick: OnPositionedDeleteClick) {
adapter.onPositionedDeleteClick = onPositionedDeleteClick
}
fun setOnIndexedManualInputListener(indexedManualInputListener: IndexedManualInputListener) {
adapter.indexedManualInputListener = indexedManualInputListener
}
}
class RandomNpcListAdapter(
private val listView: LinearLayout
) {
lateinit var onPositionedRandomizeClick: OnPositionedRandomizeClick
lateinit var onPositionedDeleteClick: OnPositionedDeleteClick
lateinit var indexedManualInputListener: IndexedManualInputListener
var hint: String = ""
var elements: List<String> = emptyList()
set(value) {
field = value
updateElements()
}
private fun updateElements() {
elements.forEachIndexed { index, s ->
updateOrCreate(index, s)
}
removeRemainingViews()
}
private fun updateOrCreate(index: Int, string: String) {
val currentPosition = listView.getChildAt(index)
if(currentPosition == null) create(index, string) else update(index, string)
}
private fun create(index: Int, string: String) {
val view = createView(string)
listView.addView(view, index)
}
private fun createView(string: String): View {
val inflater = LayoutInflater.from(listView.context)
val view =
inflater.inflate(R.layout.randomnpc_element_list_view_item, listView, false) as RandomNpcElementListview
view.prepareTexts(string)
view.prepareListeners()
return view
}
private fun update(index: Int, text: String) {
val view = listView.getChildAt(index) as RandomNpcElementListview
view.prepareTexts(text)
}
private fun RandomNpcElementListview.prepareTexts(text: String) {
setText(text)
setHint(hint)
}
private fun RandomNpcElementListview.prepareListeners() {
onRandomClick = {
val index = listView.indexOfChild(this)
onPositionedRandomizeClick.onRandomClick(index)
}
onDeleteClick = {
val index = listView.indexOfChild(this)
listView.removeViewAt(index)
onPositionedDeleteClick.onDeleteClick(index)
}
onManualInput = object : ManualInputListener {
override fun onManualInput(text: String) {
val index = listView.indexOfChild(this@prepareListeners)
indexedManualInputListener.onManualInput(index, text)
}
}
}
private fun removeRemainingViews() {
val elementsSize = elements.size
val childrenSize = listView.childCount
val difference = childrenSize - elementsSize
if(difference <= 0) return
repeat(difference) {
val lastIndex = listView.childCount - 1
listView.removeViewAt(lastIndex)
}
}
}
| apache-2.0 | 82fc3e5891c480fb4d9e8252fe5b8744 | 30.426036 | 116 | 0.674449 | 5.043685 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stackFrame/InlineStackTraceCalculator.kt | 2 | 18584 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stackFrame
import com.intellij.debugger.impl.DebuggerUtilsEx
import com.intellij.debugger.jdi.LocalVariableProxyImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.xdebugger.frame.XStackFrame
import com.sun.jdi.LocalVariable
import com.sun.jdi.Location
import com.sun.jdi.Method
import com.sun.jdi.StackFrame
import org.jetbrains.kotlin.idea.debugger.*
import org.jetbrains.kotlin.load.java.JvmAbi
object InlineStackTraceCalculator {
fun calculateInlineStackTrace(frameProxy: StackFrameProxyImpl): List<XStackFrame> =
frameProxy.stackFrame.computeKotlinStackFrameInfos().map {
it.toXStackFrame(frameProxy)
}.reversed()
// Calculate the variables that are visible in the top stack frame.
fun calculateVisibleVariables(frameProxy: StackFrameProxyImpl): List<LocalVariableProxyImpl> =
frameProxy.stackFrame.computeKotlinStackFrameInfos().last().visibleVariableProxies(frameProxy)
}
private val INLINE_LAMBDA_REGEX =
"${JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT.replace("$", "\\$")}-(.+)-[^\$]+\\$([^\$]+)\\$.*"
.toRegex()
class KotlinStackFrameInfo(
// The scope introduction variable for an inline stack frame, i.e., $i$f$function
// or $i$a$lambda. The name of this variable determines the label for an inline
// stack frame. This is null for non-inline stack frames.
val scopeVariable: VariableWithLocation?,
// For inline lambda stack frames we need to include the visible variables from the
// enclosing stack frame.
private val enclosingStackFrame: KotlinStackFrameInfo?,
// All variables that were added in this stack frame.
val visibleVariablesWithLocations: MutableList<VariableWithLocation>,
// For an inline stack frame, the number of calls from the nearest non-inline function.
// TODO: Remove. This is only used in the evaluator, to look up variables, but the depth
// is not sufficient to determine which frame a variable is in.
val depth: Int,
) {
// The location for this stack frame, i.e., the current location of the StackFrame for the
// most recent frame or the location of an inline function call for any enclosing frame.
// This depends on the next stack frame info and is initialized after the KotlinStackFrameInfo.
var callLocation: Location? = null
val displayName: String?
get() {
val scopeVariableName = scopeVariable?.name
?: return null
if (scopeVariableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)) {
return scopeVariableName.substringAfter(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)
}
val groupValues = INLINE_LAMBDA_REGEX.matchEntire(scopeVariableName)?.groupValues
if (groupValues != null) {
val lambdaName = groupValues.getOrNull(1)
val declarationFunctionName = groupValues.getOrNull(2)
return "lambda '$lambdaName' in '$declarationFunctionName'"
} else {
return scopeVariableName
}
}
val visibleVariables: List<LocalVariable>
get() = filterRepeatedVariables(
visibleVariablesWithLocations
.mapTo(enclosingStackFrame?.visibleVariables?.toMutableList() ?: mutableListOf()) {
it.variable
}
)
fun visibleVariableProxies(frameProxy: StackFrameProxyImpl): List<LocalVariableProxyImpl> =
visibleVariables.map { LocalVariableProxyImpl(frameProxy, it) }
fun toXStackFrame(frameProxy: StackFrameProxyImpl): XStackFrame {
val variables = visibleVariableProxies(frameProxy)
displayName?.let { name ->
return InlineStackFrame(callLocation, name, frameProxy, depth, variables)
}
return KotlinStackFrame(safeInlineStackFrameProxy(callLocation, 0, frameProxy), variables)
}
}
fun StackFrame.computeKotlinStackFrameInfos(): List<KotlinStackFrameInfo> {
val location = location()
val method = location.safeMethod() ?: return emptyList()
val allVisibleVariables = method.sortedVariablesWithLocation().filter {
it.variable.isVisible(this)
}
return computeStackFrameInfos(allVisibleVariables).also {
fetchCallLocations(method, it, location)
}
}
// Constructs a list of inline stack frames from a list of currently visible variables
// in introduction order.
//
// In order to construct the inline stack frame we need to associate each variable with
// a call to an inline function and keep track of the currently active inline function.
// Consider the following code.
//
// fun f() {
// val x = 0
// g {
// h(2)
// }
// }
//
// inline fun g(block: () -> Unit) {
// var y = 1
// block()
// }
//
// inline fun h(a: Int) {
// var z = 3
// /* breakpoint */ ...
// }
//
// When stopped at the breakpoint in `h`, we have the following visible variables.
//
// | Variable | Depth | Scope | Frames | Pending |
// |-------------------|-------|-------|-----------------------|----------|
// | x | 0 | f | f:[x] | |
// | $i$f$g | 1 | g | f:[x], g:[] | |
// | y$iv | 1 | g | f:[x], g:[y$iv] | |
// | $i$a$-g-Class$f$1 | 0 | f$1 | f:[x] | |
// | a$iv | 1 | h | f:[x] | 1:[a$iv] |
// | $i$f$h | 1 | h | f:[x], h:[a$iv] | |
// | z$iv | 1 | h | f:[x], h:[a$iv, z$iv] | |
//
// There are two kinds of variables. Scope introduction variables are prefixed with
// $i$f or $i$a and represent calls to inline functions or calls to function arguments
// of inline functions respectively. All remaining variables represent source code
// variables along with an inline depth represented by the number of `$iv` suffixes.
//
// This function works by simulating the current active call stack while iterating
// over the variables in introduction order. New frames are introduced or removed
// when encountering scope introduction variables. Each variable encountered
// is either associated to the currently active stack frame or to the next
// stack frame at its depth (since arguments of inline functions appear before the
// corresponding scope introduction variable).
private fun computeStackFrameInfos(sortedVariables: List<VariableWithLocation>): List<KotlinStackFrameInfo> {
// List of all stack frames in introduction order. We always start with a non-inline stack frame.
val stackFrameInfos = mutableListOf(KotlinStackFrameInfo(null, null, mutableListOf(), 0))
// Variables which should appear in a future stack frame. On the jvm these are arguments
// to the next inline function call. On dex there are also variables which were moved
// before or after their stack frame.
val pendingVariables = mutableMapOf<Int, MutableList<VariableWithLocation>>()
// The current call stack, as a list of active frame indices into stackFrameInfos. This is always non-empty.
var activeFrames = mutableListOf(0)
for (variable in sortedVariables) {
// When we encounter a call to an inline function, we start a new stack frame
// without any enclosing frame.
if (variable.name.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)) {
val depth = activeFrames.size
stackFrameInfos += KotlinStackFrameInfo(
variable,
null,
pendingVariables[depth] ?: mutableListOf(),
depth
)
pendingVariables.remove(depth)
activeFrames += stackFrameInfos.size - 1
continue
}
val depth = getInlineDepth(variable.name)
when {
// When we encounter a call to an inline function argument, we are
// moving up the call stack to the depth of the function argument.
variable.name.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT) -> {
// for lambda arguments to inline only functions the depth doesn't change,
// i.e., we would have depth + 1 == activeFrames.size.
if (depth + 1 < activeFrames.size) {
activeFrames = activeFrames.subList(0, depth + 1)
}
// TODO: If we get unlucky, we may encounter an inline lambda before its enclosing frame.
// There's no good workaround in this case, since we can't distinguish between
// inline function calls inside such a lambda and the calls corresponding to the
// enclosing frame. We should communicate this situation somehow.
if (depth < activeFrames.size) {
stackFrameInfos += KotlinStackFrameInfo(
variable,
stackFrameInfos[activeFrames[depth]],
pendingVariables[depth] ?: mutableListOf(),
depth
)
pendingVariables.remove(depth)
activeFrames[depth] = stackFrameInfos.size - 1
}
}
// Process variables in the current frame.
depth == activeFrames.size - 1 -> {
stackFrameInfos[activeFrames[depth]].visibleVariablesWithLocations += variable
}
// Process arguments to the next inline function call or variables that were
// moved to the wrong location on dex.
else -> {
pendingVariables.getOrPut(depth) { mutableListOf() } += variable
}
}
}
// For valid debug information there should be no pending variables at this point,
// except possibly when we are stopped while evaluating default arguments to an inline
// function.
for ((depth, variables) in pendingVariables.entries) {
if (depth < activeFrames.size) {
stackFrameInfos[activeFrames[depth]].visibleVariablesWithLocations += variables
} else {
// This can happen in two cases: Either we are stopped right before an inline call
// when some arguments are already in variables or the debug information is invalid
// and some variables were moved after a call to an inline lambda.
// Instead of throwing them away we'll add these variables to the last call stack at
// the desired depth (there probably won't be one in the first case).
stackFrameInfos.lastOrNull {
it.depth == depth
}?.visibleVariablesWithLocations?.addAll(variables)
}
}
return stackFrameInfos
}
// Heuristic to guess inline call locations based on the variables in a `KotlinStackFrameInfo`
// and the `KotlinDebug` SMAP stratum.
//
// There is currently no way of reliably computing inline call locations using the Kotlin
// debug information. We can try to compute the call location based on the locations of the
// local variables in an inline stack frame or based on the KotlinDebug stratum for the
// one case where this will work.
//
// ---
//
// On the JVM it seems reasonable to determine the call location using the location
// immediately preceding a scope introduction variable.
//
// The JVM IR backend generates a line number before every inline call. For inline
// functions without default arguments the scope introduction variable starts at the first
// line of an inline function. In this particular case, the previous location corresponds
// to the call location. This is not true for the old JVM backend or for inline functions
// with default arguments.
//
// There is not much we can do for the old JVM backend, since there are cases where we simply
// do not have a line number for an inline call. We're ignoring this issue since the old
// backend is already deprecated.
//
// In order to handle inline functions with default arguments we could take the location
// immediately preceding all variables in the inline stack frame. This would include the function
// arguments. However, there still wouldn't be any guarantee that this corresponds to the call
// location, since the inliner does not introduce a new variable for inline function arguments
// if the argument at the call site is already in a variable. This is an optimization that
// always leads to invalid debug information and this case is not an exception.
//
// Finally, it is also not clear how to reliably determine whether we are in an inline default
// stub, so all in all it is probably better to just use the scope introduction variable and accept
// that the call location will be incorrect in inline default stubs.
//
// Finally, of course, on dex the situation is worse since we cannot rely on the locations
// of local variables due to spilling.
//
// ---
//
// The KotlinDebug stratum records the location of the first inline call in a function and
// can thus be used to determine the call location of the first inline stack frame. This
// information is produced by the inliner itself and should be correct.
//
// The only heuristic step is an issue with the API: We need to produce a JDI [Location],
// but the KotlinDebug SMAP only provides us with a file and line pair. This means that
// we actually don't know the code index of the call. OTOH, there is no real reason why
// the UI would need the code index at all and this is something we could fix by moving
// away from using JDI data structures for the UI representation.
//
// Note though, that the KotlinDebug stratum only records the location of the first call to
// an inline *function*, so it is useless for nested calls or calls to inline only functions.
// The latter result in calls to lambda arguments which don't appear in the KotlinDebug stratum.
//
// Moreover, the KotlinDebug stratum only applies to remapped line numbers, so it cannot be
// used in top-level inline lambda arguments.
private fun fetchCallLocations(
method: Method,
kotlinStackFrameInfos: List<KotlinStackFrameInfo>,
defaultLocation: Location,
) {
kotlinStackFrameInfos.lastOrNull()?.callLocation = defaultLocation
// If there are no inline calls we don't need to fetch the line locations.
// It's important to exit early here, since fetching line locations might involve
// a round-trip to the debuggee vm.
if (kotlinStackFrameInfos.size <= 1)
return
val allLocations = DebuggerUtilsEx.allLineLocations(method)
if (allLocations == null) {
// In case of broken debug information we use the same location for all stack frames.
kotlinStackFrameInfos.forEach { it.callLocation = defaultLocation }
return
}
// If the current location is covered by the KotlinDebug stratum then we can use it to
// look up the location of the first call to an inline function (but not to an inline
// lambda argument).
var startIndex = 1
kotlinStackFrameInfos[1].scopeVariable?.takeIf {
it.name.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION)
}?.let { firstInlineScopeVariable ->
// We cannot use the current location to look up the location in the KotlinDebug
// stratum, since it might be in a top-level inline lambda and hence not covered
// by KotlinDebug.
//
// The scope introduction variable on the other hand should start inside an
// inline function.
val startOffset = firstInlineScopeVariable.location
val callLineNumber = startOffset.safeLineNumber("KotlinDebug")
val callSourceName = startOffset.safeSourceName("KotlinDebug")
if (callLineNumber != -1 && callSourceName != null) {
// Find the closest location to startOffset with the correct line number and source name.
val callLocation = allLocations.lastOrNull { location ->
location < startOffset &&
location.safeLineNumber() == callLineNumber &&
location.safeSourceName() == callSourceName
}
if (callLocation != null) {
kotlinStackFrameInfos[0].callLocation = callLocation
startIndex++
}
}
}
for (index in startIndex until kotlinStackFrameInfos.size) {
// Find the index of the location closest to the start of the scope variable.
// NOTE: [Method.allLineLocations] returns locations ordered by codeIndex.
val scopeIndex =
kotlinStackFrameInfos[index]
.scopeVariable
?.location
?.let(allLocations::binarySearch)
// If there is no scope introduction variable, or if it effectively starts on the first
// location we use the default location. The latter case can only happen if the user
// called a Kotlin inline function directly from Java. We will incorrectly present
// an inline stack frame in this case, but this is not a supported use case anyway.
val prev = kotlinStackFrameInfos[index - 1]
if (scopeIndex == null || scopeIndex in -1..0) {
prev.callLocation = defaultLocation
continue
}
var locationIndex = if (scopeIndex > 0) {
// If the scope variable starts on a line we take the previous line.
scopeIndex - 1
} else /* if (scopeIndex <= -2) */ {
// If the returned location is < 0, then the element should be inserted at position
// `-locationIndex - 1` to preserve the sorting order and the element at position
// `-locationIndex - 2` contains the previous line number.
-scopeIndex - 2
}
// Skip to the previous location if the call location lands on a synthetic fake.kt:1 line.
// These lines are inserted by the compiler to force new line numbers for single line lambdas.
if (DebuggerUtils.isKotlinFakeLineNumber(allLocations[locationIndex])) {
locationIndex = (locationIndex - 1).coerceAtLeast(0)
}
prev.callLocation = allLocations[locationIndex]
}
}
| apache-2.0 | e762fa7091057675658f46e57cecddf6 | 48.823056 | 158 | 0.661591 | 4.96235 | false | false | false | false |
jcsantosbr/suadeome-backendjvm | src/main/kotlin/com/jcs/suadeome/professionals/ProfessionalRepository.kt | 1 | 1972 | package com.jcs.suadeome.professionals
import com.jcs.suadeome.services.Service
import com.jcs.suadeome.types.Id
import org.skife.jdbi.v2.Handle
import java.util.*
class ProfessionalRepository(val openHandle: Handle) {
fun professionalsByService(services: List<Service>): List<Professional> {
if (services.isEmpty()) return Collections.emptyList()
val placeHolders = services.mapIndexed { i, service -> ":id$i" }.joinToString(",")
val whereClause = if (placeHolders.isBlank()) "" else "WHERE service_id IN ( $placeHolders )"
val query = openHandle.createQuery("""
SELECT id, name, phone, service_id
FROM professionals
$whereClause
ORDER BY name
""")
services.forEachIndexed { i, service ->
query.bind("id$i", service.id.value)
}
val rows = query.list()
val professionals = rows.map { rowToProfessional(it) }
return professionals
}
private fun rowToProfessional(row: Map<String, Any>): Professional {
val id = Id(row["id"].toString())
val name = row["name"].toString()
val phone = PhoneNumber(row["phone"].toString())
val serviceId = Id(row["service_id"].toString())
return Professional(id, name, phone, serviceId)
}
fun createProfessional(professional: Professional) {
val query = """
INSERT INTO professionals (id, name, phone, service_id, created_by, created_at)
VALUES (:id, :name, :phone, :serviceId, :user, :now)
"""
openHandle.createStatement(query)
.bind("id", professional.id.value)
.bind("name", professional.name)
.bind("phone", professional.phone.number)
.bind("serviceId", professional.serviceId.value)
.bind("user", 1)
.bind("now", Date())
.execute()
}
}
| mit | acaed822da57b20b6c6ae5b9f1752d21 | 31.327869 | 101 | 0.589249 | 4.401786 | false | false | false | false |
SirWellington/alchemy-arguments | src/main/java/tech/sirwellington/alchemy/arguments/assertions/NumberAssertions.kt | 1 | 10847 | /*
* Copyright © 2019. Sir Wellington.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("NumberAssertions")
package tech.sirwellington.alchemy.arguments.assertions
import tech.sirwellington.alchemy.arguments.AlchemyAssertion
import tech.sirwellington.alchemy.arguments.FailedAssertionException
import tech.sirwellington.alchemy.arguments.checkThat
import java.lang.Math.abs
/**
* @author SirWellington
*/
/**
* Asserts that an integer is `>` the supplied value.
* @param exclusiveLowerBound The argument must be `> exclusiveLowerBound`.
*
*
* @return
*/
fun greaterThan(exclusiveLowerBound: Int): AlchemyAssertion<Int>
{
checkThat(exclusiveLowerBound != Integer.MAX_VALUE, "Integers cannot exceed ${Int.MAX_VALUE}")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number > exclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be > $exclusiveLowerBound")
}
}
}
/**
* Asserts that a long is `> exclusiveLowerBound`.
* @param exclusiveLowerBound The argument must be `>` this value.
*
*
* @return
*/
fun greaterThan(exclusiveLowerBound: Long): AlchemyAssertion<Long>
{
checkThat(exclusiveLowerBound != Long.MAX_VALUE, "Longs cannot exceed ${Long.MAX_VALUE}")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number > exclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be > $exclusiveLowerBound")
}
}
}
/**
* Asserts that a double is `> exclusiveLowerBound` within `delta` margin of error.
* @param exclusiveLowerBound The argument is expected to be `>` this value.
*
* @param delta The allowable margin of error for the `>` operation.
*
*
* @return
*/
@JvmOverloads
fun greaterThan(exclusiveLowerBound: Double, delta: Double = 0.0): AlchemyAssertion<Double>
{
checkThat(exclusiveLowerBound < Double.MAX_VALUE, "Doubles cannot exceed ${Double.MAX_VALUE}")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number!! + abs(delta) > exclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be > $exclusiveLowerBound +- $delta")
}
}
}
/**
* Asserts that an integer is `>=` the supplied value.
*
* @param inclusiveLowerBound The argument integer must be `>= inclusiveLowerBound`
*
*
* @return
*/
fun greaterThanOrEqualTo(inclusiveLowerBound: Int): AlchemyAssertion<Int>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number >= inclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be greater than or equal to $inclusiveLowerBound")
}
}
}
/**
* Asserts that a long is `>= inclusiveLowerBound`.
* @param inclusiveLowerBound The argument integer must be `>= inclusiveUpperBound`
*
*
* @return
*/
fun greaterThanOrEqualTo(inclusiveLowerBound: Long): AlchemyAssertion<Long>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number >= inclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be greater than or equal to $inclusiveLowerBound")
}
}
}
/**
* Asserts that a double is `>= inclusiveLowerBound` within `delta` margin-of-error.
* @param inclusiveLowerBound The argument double must be `>= inclusiveLowerBound` within the margin of error.
* @param delta The allowable margin-of-error for the `>= ` comparison.
*
*
* @return
*/
@JvmOverloads
fun greaterThanOrEqualTo(inclusiveLowerBound: Double, delta: Double = 0.0): AlchemyAssertion<Double>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number + abs(delta) >= inclusiveLowerBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be >= $inclusiveLowerBound +- $delta")
}
}
}
/**
* Asserts that an integer is positive, or `> 0`
* @return
*/
fun positiveInteger(): AlchemyAssertion<Int>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
if (number <= 0)
{
throw FailedAssertionException("Expected positive integer: $number")
}
}
}
/**
* Asserts that an integer is negative, or `< 0`.
* @return
*/
fun negativeInteger(): AlchemyAssertion<Int>
{
return lessThan(0)
}
/**
* Asserts that an integer is `<=` the supplied value.
* @param inclusiveUpperBound The argument must be `<= inclusiveUpperBound`.
*
*
* @return
*/
fun lessThanOrEqualTo(inclusiveUpperBound: Int): AlchemyAssertion<Int>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number <= inclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be less than or equal to $inclusiveUpperBound")
}
}
}
/**
* Asserts that a long is `<=` the supplied value.
* @param inclusiveUpperBound The argument must be `<= inclusiveUpperBound`.
*
*
* @return
*/
fun lessThanOrEqualTo(inclusiveUpperBound: Long): AlchemyAssertion<Long>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number <= inclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be less than or equal to $inclusiveUpperBound")
}
}
}
/**
* Asserts that a double is `<=` the supplied value, within a `delta` margin-of-error.
* @param inclusiveUpperBound
*
* @param delta The allowable margin-of-error in the `<= ` comparison
*
*
* @return
*/
@JvmOverloads fun lessThanOrEqualTo(inclusiveUpperBound: Double, delta: Double = 0.0): AlchemyAssertion<Double>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number!! - abs(delta) <= inclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be <= $inclusiveUpperBound +- $delta")
}
}
}
/**
* Asserts that a Long is positive, or `> 0`
* @return
*/
fun positiveLong(): AlchemyAssertion<Long>
{
return AlchemyAssertion { number ->
notNull<Any>().check(number)
if (number <= 0)
{
throw FailedAssertionException("Expected positive long: $number")
}
}
}
/**
* Asserts that a Long is negative, or `< 0`.
* @return
*/
fun negativeLong(): AlchemyAssertion<Long>
{
return lessThan(0L)
}
/**
* Asserts than an integer is `<` the supplied value.
* @param exclusiveUpperBound The argument must be `< exclusiveUpperBound`.
*
*
* @return
*/
fun lessThan(exclusiveUpperBound: Int): AlchemyAssertion<Int>
{
checkThat(exclusiveUpperBound != Integer.MIN_VALUE, "Ints cannot be less than ${Int.MIN_VALUE}")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number < exclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be < " + exclusiveUpperBound)
}
}
}
/**
* Asserts than a long is `<` the supplied value.
* @param exclusiveUpperBound The argument must be `< exclusiveUpperBound`.
*
*
* @return
*/
fun lessThan(exclusiveUpperBound: Long): AlchemyAssertion<Long>
{
checkThat(exclusiveUpperBound != java.lang.Long.MIN_VALUE, "Longs cannot be less than " + java.lang.Long.MIN_VALUE)
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number < exclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be < " + exclusiveUpperBound)
}
}
}
/**
* Asserts that a double is `<` the supplied value, within `delta` margin-of-error.
*
* @param exclusiveUpperBound The argument must be `< exclusiveUpperBound`.
* @param delta The allowable margin-of-error.
*
*
* @return
*/
@JvmOverloads
fun lessThan(exclusiveUpperBound: Double, delta: Double = 0.0): AlchemyAssertion<Double>
{
checkThat(exclusiveUpperBound > -java.lang.Double.MAX_VALUE, "Doubles cannot be less than " + -java.lang.Double.MAX_VALUE)
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinBounds = number - abs(delta) < exclusiveUpperBound
if (!isWithinBounds)
{
throw FailedAssertionException("Number must be < $exclusiveUpperBound")
}
}
}
/**
* Asserts that an integer argument is in the specified (inclusive) range.
*
* @param min The lower bound for the range, inclusive
* @param max The upper bound for the range, inclusive
*
* @return
*
* @throws IllegalArgumentException If `min >= max`. `min` should always be less than `max`.
*/
@Throws(IllegalArgumentException::class)
fun numberBetween(min: Int, max: Int): AlchemyAssertion<Int>
{
checkThat(min < max, "Minimum must be less than Max.")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinRange = number in min..max
if (!isWithinRange)
{
throw FailedAssertionException("Expected a number between $min and $max but got $number instead")
}
}
}
/**
* Asserts that a long argument is in the specified (inclusive) range.
* @param min The lower bound for the range, inclusive
*
* @param max The upper bound for the range, inclusive
*
*
* @return
*
*
* @throws IllegalArgumentException If `min >= max`. `min` should always be less
*/
@Throws(IllegalArgumentException::class)
fun numberBetween(min: Long, max: Long): AlchemyAssertion<Long>
{
checkThat(min < max, "Minimum must be less than Max.")
return AlchemyAssertion { number ->
notNull<Any>().check(number)
val isWithinRange = number in min..max
if (!isWithinRange)
{
throw FailedAssertionException("Expected a number between $min and $max but got $number instead")
}
}
}
| apache-2.0 | 171537a5c596cebc2f7f020b8b891cd4 | 23.65 | 126 | 0.66596 | 4.611395 | false | false | false | false |
openium/auvergne-webcams-droid | app/src/main/java/fr/openium/auvergnewebcams/utils/LoadWebCamUtils.kt | 1 | 920 | package fr.openium.auvergnewebcams.utils
import timber.log.Timber
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
/**
* Created by Openium on 19/02/2019.
*/
object LoadWebCamUtils {
fun getMediaViewSurf(urlBase: String?): String {
var media = ""
if (!urlBase.isNullOrEmpty()) {
try {
val urlLD = String.format("%s/last", urlBase)
val url = URL(urlLD)
val bufferedReader = BufferedReader(InputStreamReader(url.openStream()))
var line = bufferedReader.readLine()
while (line != null && line.isNotBlank()) {
media += line
line = bufferedReader.readLine()
}
bufferedReader.close()
} catch (e: Exception) {
Timber.e(e)
}
}
return media
}
} | mit | 35ac40588382b85fbba56c62ff54b73e | 26.088235 | 88 | 0.540217 | 4.717949 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/dialog/ReportForm.kt | 1 | 2846 | package jp.juggler.subwaytooter.dialog
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.view.View
import android.view.WindowManager
import android.widget.CheckBox
import android.widget.EditText
import android.widget.TextView
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.entity.TootAccount
import jp.juggler.subwaytooter.api.entity.TootStatus
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.subwaytooter.util.matchHost
import jp.juggler.util.showToast
object ReportForm {
@SuppressLint("InflateParams")
fun showReportForm(
activity: Activity,
accessInfo: SavedAccount,
who: TootAccount,
status: TootStatus?,
onClickOk: (dialog: Dialog, comment: String, forward: Boolean) -> Unit
) {
val view = activity.layoutInflater.inflate(R.layout.dlg_report_user, null, false)
val tvUser: TextView = view.findViewById(R.id.tvUser)
val tvStatusCaption: TextView = view.findViewById(R.id.tvStatusCaption)
val tvStatus: TextView = view.findViewById(R.id.tvStatus)
val etComment: EditText = view.findViewById(R.id.etComment)
val cbForward: CheckBox = view.findViewById(R.id.cbForward)
val tvForwardDesc: TextView = view.findViewById(R.id.tvForwardDesc)
val canForward = !accessInfo.matchHost(who) && !accessInfo.isMisskey
cbForward.isChecked = false
if (!canForward) {
cbForward.visibility = View.GONE
tvForwardDesc.visibility = View.GONE
} else {
cbForward.visibility = View.VISIBLE
tvForwardDesc.visibility = View.VISIBLE
cbForward.text = activity.getString(R.string.report_forward_to, who.apDomain.pretty)
}
tvUser.text = who.acct.pretty
if (status == null) {
tvStatusCaption.visibility = View.GONE
tvStatus.visibility = View.GONE
} else {
tvStatus.text = status.decoded_content
}
val dialog = Dialog(activity)
dialog.setContentView(view)
view.findViewById<View>(R.id.btnOk).setOnClickListener(View.OnClickListener {
val comment = etComment.text.toString().trim()
if (comment.isEmpty()) {
activity.showToast(true, R.string.comment_empty)
return@OnClickListener
}
onClickOk(dialog, comment, cbForward.isChecked)
})
view.findViewById<View>(R.id.btnCancel).setOnClickListener { dialog.cancel() }
dialog.window?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT
)
dialog.show()
}
}
| apache-2.0 | f1388facc29065285ef06a416d378f09 | 34.487179 | 96 | 0.655657 | 4.474843 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/main/java/de/ph1b/audiobook/features/bookOverview/list/BookOverviewAdapter.kt | 1 | 1164 | package de.ph1b.audiobook.features.bookOverview.list
import de.ph1b.audiobook.data.Book
import de.ph1b.audiobook.features.bookOverview.list.header.BookOverviewHeaderComponent
import de.ph1b.audiobook.features.bookOverview.list.header.OpenCategoryListener
import de.ph1b.audiobook.misc.recyclerComponent.CompositeListAdapter
import java.util.UUID
typealias BookClickListener = (Book, BookOverviewClick) -> Unit
class BookOverviewAdapter(
bookClickListener: BookClickListener,
openCategoryListener: OpenCategoryListener
) : CompositeListAdapter<BookOverviewItem>(BookOverviewDiff()) {
init {
addComponent(GridBookOverviewComponent(bookClickListener))
addComponent(ListBookOverviewComponent(bookClickListener))
addComponent(BookOverviewHeaderComponent(openCategoryListener))
}
fun reloadBookCover(bookId: UUID) {
for (i in 0 until itemCount) {
val item = getItem(i)
if (item is BookOverviewModel && item.book.id == bookId) {
notifyItemChanged(i)
break
}
}
}
fun itemAtPositionIsHeader(position: Int): Boolean {
val item = getItem(position)
return item is BookOverviewHeaderModel
}
}
| lgpl-3.0 | 923b1620147bb2ea34a42d12ab1c3aab | 31.333333 | 86 | 0.776632 | 4.359551 | false | false | false | false |
imageprocessor/cv4j | app/src/main/java/com/cv4j/app/fragment/PixelOperatorFragment.kt | 1 | 2090 | package com.cv4j.app.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cv4j.app.R
import com.cv4j.app.activity.pixels.*
import com.cv4j.app.app.BaseFragment
import kotlinx.android.synthetic.main.fragment_pixel_operator.*
/**
*
* @FileName:
* com.cv4j.app.fragment.PixelOperatorFragment
* @author: Tony Shen
* @date: 2020-05-04 12:57
* @version: V1.0 <描述当前版本功能>
*/
class PixelOperatorFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_pixel_operator, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
text1.setOnClickListener {
val i = Intent(mContext, ArithmeticAndLogicOperationActivity::class.java)
i.putExtra("Title", text1.text.toString())
startActivity(i)
}
text2.setOnClickListener {
val i = Intent(mContext, SubImageActivity::class.java)
i.putExtra("Title", text2.text.toString())
startActivity(i)
}
text3.setOnClickListener {
val i = Intent(mContext, PrincipalColorExtractorActivity::class.java)
i.putExtra("Title", text3.text.toString())
startActivity(i)
}
text4.setOnClickListener {
val i = Intent(mContext, ResizeActivity::class.java)
i.putExtra("Title", text4.text.toString())
startActivity(i)
}
text5.setOnClickListener {
val i = Intent(mContext, FlipActivity::class.java)
i.putExtra("Title", text5.text.toString())
startActivity(i)
}
text6.setOnClickListener {
val i = Intent(mContext, RotateActivity::class.java)
i.putExtra("Title", text6.text.toString())
startActivity(i)
}
}
} | apache-2.0 | 76a6e860336f80af6562de3624d1e6c9 | 31.421875 | 184 | 0.651398 | 4.198381 | false | false | false | false |
dzharkov/intellij-markdown | src/org/intellij/markdown/parser/sequentialparsers/SequentialParserManager.kt | 1 | 991 | package org.intellij.markdown.parser.sequentialparsers
import java.util.ArrayList
public abstract class SequentialParserManager {
abstract fun getParserSequence(): List<SequentialParser>;
public fun runParsingSequence(tokensCache: TokensCache, rangesToParse: Collection<Range<Int>>): Collection<SequentialParser.Node> {
val result = ArrayList<SequentialParser.Node>()
var parsingSpaces = ArrayList<Collection<Range<Int>>>()
parsingSpaces.add(rangesToParse)
for (sequentialParser in getParserSequence()) {
val nextLevelSpaces = ArrayList<Collection<Range<Int>>>()
for (parsingSpace in parsingSpaces) {
val currentResult = sequentialParser.parse(tokensCache, parsingSpace)
result.addAll(currentResult.parsedNodes)
nextLevelSpaces.addAll(currentResult.rangesToProcessFurther)
}
parsingSpaces = nextLevelSpaces
}
return result
}
}
| apache-2.0 | c71cbd68d7b0f5120443d19a3bb040a0 | 34.392857 | 135 | 0.693239 | 5.271277 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeConstructorParameterPropertyFix.kt | 2 | 3219 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinValVar
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.*
class MakeConstructorParameterPropertyFix(
element: KtParameter, private val kotlinValVar: KotlinValVar, className: String?
) : KotlinQuickFixAction<KtParameter>(element) {
override fun getFamilyName() = KotlinBundle.message("make.constructor.parameter.a.property.0", "")
private val suffix = if (className != null) KotlinBundle.message("in.class.0", className) else ""
override fun getText() = KotlinBundle.message("make.constructor.parameter.a.property.0", suffix)
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
val element = element ?: return false
return !element.hasValOrVar()
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
element.addBefore(kotlinValVar.createKeyword(KtPsiFactory(project))!!, element.nameIdentifier)
element.addModifier(KtTokens.PRIVATE_KEYWORD)
element.visibilityModifier()?.let { private ->
editor?.apply {
selectionModel.setSelection(private.startOffset, private.endOffset)
caretModel.moveToOffset(private.endOffset)
}
}
}
companion object Factory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val ktReference = Errors.UNRESOLVED_REFERENCE.cast(diagnostic).a as? KtNameReferenceExpression ?: return emptyList()
val valOrVar = if (ktReference.getAssignmentByLHS() != null) KotlinValVar.Var else KotlinValVar.Val
val ktParameter = ktReference.getPrimaryConstructorParameterWithSameName() ?: return emptyList()
val containingClass = ktParameter.containingClass()!!
val className = if (containingClass != ktReference.containingClass()) containingClass.nameAsSafeName.asString() else null
return listOf(MakeConstructorParameterPropertyFix(ktParameter, valOrVar, className))
}
}
}
fun KtNameReferenceExpression.getPrimaryConstructorParameterWithSameName(): KtParameter? {
return nonStaticOuterClasses()
.mapNotNull { it.primaryConstructor?.valueParameters?.firstOrNull { it.name == getReferencedName() } }
.firstOrNull()
} | apache-2.0 | c8aa2878e4a140b27ac1a92833102389 | 47.787879 | 158 | 0.752408 | 5.117647 | false | false | false | false |
RuneSuite/client | plugins-dev/src/main/java/org/runestar/client/plugins/dev/MouseDebug.kt | 1 | 1129 | package org.runestar.client.plugins.dev
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.Fonts
import org.runestar.client.api.game.live.Canvas
import org.runestar.client.api.game.live.Mouse
import org.runestar.client.api.plugins.PluginSettings
import java.awt.Color
class MouseDebug : DisposablePlugin<PluginSettings>() {
override val defaultSettings = PluginSettings()
override fun onStart() {
add(Canvas.repaints.subscribe { g ->
val x = 5
var y = 40
g.font = Fonts.PLAIN_12
g.color = Color.WHITE
val strings = ArrayList<String>()
strings.apply {
add("mouse")
add("location: ${Mouse.location}")
add("viewportLocation: ${Mouse.viewportLocation}")
add("isInViewport: ${Mouse.isInViewport}")
add("entityCount: ${Mouse.entityCount}")
add("tags:")
}
strings.forEach { s ->
g.drawString(s, x, y)
y += g.font.size + 5
}
})
}
} | mit | 2b056cbcc561340062ac03114403b2e5 | 29.540541 | 66 | 0.575731 | 4.410156 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/IterableNodeDequeDescendingIterator.kt | 1 | 1122 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
@DependsOn(Node::class, IterableNodeDeque::class)
class IterableNodeDequeDescendingIterator : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.interfaces.contains(Iterator::class.type) }
.and { it.instanceFields.count { it.type == type<Node>() } == 2 }
.and { it.instanceFields.count { it.type == type<IterableNodeDeque>() } == 1 }
.and { it.instanceFields.size == 3 }
@DependsOn(IterableNodeDeque::class)
class deque : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<IterableNodeDeque>() }
}
// current
// last
} | mit | 5a08363b382dd635fb271ff1a7dfb0f7 | 40.592593 | 93 | 0.721034 | 4.021505 | false | false | false | false |
square/okhttp | native-image-tests/src/test/kotlin/okhttp3/nativeImage/NativeImageTestsTest.kt | 6 | 1793 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.nativeImage
import okhttp3.SampleTest
import okhttp3.findTests
import okhttp3.testSelectors
import okhttp3.treeListener
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor
import org.junit.platform.engine.discovery.DiscoverySelectors
class NativeImageTestsTest {
@Test
fun testFindsFixedTestsForImage() {
val testSelector = testSelectors()
val x = findTests(testSelector)
x.find { it is ClassBasedTestDescriptor && it.testClass == SampleTest::class.java }
}
@Test
fun testFindsModuleTests() {
val testSelector = DiscoverySelectors.selectPackage("okhttp3")
val x = findTests(listOf(testSelector))
x.find { it is ClassBasedTestDescriptor && it.testClass == SampleTest::class.java }
}
@Test
fun testFindsProjectTests() {
val testSelector = DiscoverySelectors.selectPackage("okhttp3")
val x = findTests(listOf(testSelector))
x.find { it is ClassBasedTestDescriptor && it.testClass == SampleTest::class.java }
}
@Test
fun testTreeListener() {
val listener = treeListener()
assertNotNull(listener)
}
} | apache-2.0 | fcad787a5984c64477430943ee35f087 | 29.931034 | 87 | 0.748466 | 4.084282 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.