repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LachlanMcKee/gsonpath | compiler/base/src/main/java/gsonpath/util/FieldGetterFinder.kt | 1 | 1621 | package gsonpath.util
import java.util.*
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.TypeElement
import javax.lang.model.type.ExecutableType
class FieldGetterFinder(private val typeHandler: TypeHandler) {
/**
* Attempts to find a logical getter method for a variable.
*
* For example, the following getter method names are valid for a variable named 'foo':
* 'foo()', 'isFoo()', 'hasFoo()', 'getFoo()'
*
* If no getter method is found, an exception will be fired.
*
* @param parentElement the parent element of the field.
* @param variableElement the field element we want to find the getter method for.
*/
fun findGetter(parentElement: TypeElement, variableElement: Element): Element? {
return typeHandler.getAllMembers(parentElement)
.asSequence()
.filter { it.kind == ElementKind.METHOD }
.filter { isMethodNameGetter(it, variableElement) }
.find { (it.asType() as ExecutableType).parameterTypes.size == 0 }
}
/**
* Determines if the method name either matches the variable name, or starts with a standard getter prefix.
*/
private fun isMethodNameGetter(methodElement: Element, variableElement: Element): Boolean {
val remainder = methodElement.simpleName.toString()
.toLowerCase(Locale.ENGLISH)
.replace(variableElement.simpleName.toString().toLowerCase(Locale.ENGLISH), "")
return arrayOf("", "is", "has", "get").contains(remainder)
}
} | mit | 8dd7d27f26e1acd5290187f995185ed8 | 41.684211 | 111 | 0.672424 | 4.684971 | false | false | false | false |
arturbosch/detekt | detekt-rules-style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/ForbiddenCommentSpec.kt | 1 | 5627 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
private const val VALUES = "values"
private const val ALLOWED_PATTERNS = "allowedPatterns"
class ForbiddenCommentSpec : Spek({
val todoColon = "// TODO: I need to fix this."
val todo = "// TODO I need to fix this."
val fixmeColon = "// FIXME: I need to fix this."
val fixme = "// FIXME I need to fix this."
val stopShipColon = "// STOPSHIP: I need to fix this."
val stopShip = "// STOPSHIP I need to fix this."
describe("ForbiddenComment rule") {
context("the default values are configured") {
it("should report TODO: usages") {
val findings = ForbiddenComment().compileAndLint(todoColon)
assertThat(findings).hasSize(1)
}
it("should not report TODO usages") {
val findings = ForbiddenComment().compileAndLint(todo)
assertThat(findings).isEmpty()
}
it("should report FIXME: usages") {
val findings = ForbiddenComment().compileAndLint(fixmeColon)
assertThat(findings).hasSize(1)
}
it("should not report FIXME usages") {
val findings = ForbiddenComment().compileAndLint(fixme)
assertThat(findings).isEmpty()
}
it("should report STOPSHIP: usages") {
val findings = ForbiddenComment().compileAndLint(stopShipColon)
assertThat(findings).hasSize(1)
}
it("should not report STOPSHIP usages") {
val findings = ForbiddenComment().compileAndLint(stopShip)
assertThat(findings).isEmpty()
}
it("should report violation in multiline comment") {
val code = """
/*
TODO: I need to fix this.
*/
"""
val findings = ForbiddenComment().compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should report violation in KDoc") {
val code = """
/**
* TODO: I need to fix this.
*/
class A {
/**
* TODO: I need to fix this.
*/
}
"""
val findings = ForbiddenComment().compileAndLint(code)
assertThat(findings).hasSize(2)
}
}
context("custom default values are configured") {
listOf(
TestConfig(mapOf(VALUES to "Banana")),
TestConfig(mapOf(VALUES to listOf("Banana")))
)
.forEach { config ->
val banana = "// Banana."
it("should not report TODO: usages") {
val findings = ForbiddenComment(config).compileAndLint(todoColon)
assertThat(findings).isEmpty()
}
it("should not report FIXME: usages") {
val findings = ForbiddenComment(config).compileAndLint(fixmeColon)
assertThat(findings).isEmpty()
}
it("should not report STOPME: usages") {
val findings = ForbiddenComment(config).compileAndLint(stopShipColon)
assertThat(findings).isEmpty()
}
it("should report Banana usages") {
val findings = ForbiddenComment(config).compileAndLint(banana)
assertThat(findings).hasSize(1)
}
it("should report Banana usages regardless of case sensitive") {
val forbiddenComment = ForbiddenComment(TestConfig(mapOf(VALUES to "bAnAnA")))
val findings = forbiddenComment.compileAndLint(banana)
assertThat(findings).hasSize(1)
}
}
}
context("custom default values with allowed patterns are configured") {
val patternsConfig by memoized {
TestConfig(
mapOf(
VALUES to "Comment",
ALLOWED_PATTERNS to "Ticket|Task"
)
)
}
it("should report Comment usages when regex does not match") {
val comment = "// Comment is added here."
val findings = ForbiddenComment(patternsConfig).compileAndLint(comment)
assertThat(findings).hasSize(1)
}
it("should not report Comment usages when any one pattern is present") {
val comment = "// Comment Ticket:234."
val findings = ForbiddenComment(patternsConfig).compileAndLint(comment)
assertThat(findings).isEmpty()
}
it("should not report Comment usages when all patterns are present") {
val comment = "// Comment Ticket:123 Task:456 comment."
val findings = ForbiddenComment(patternsConfig).compileAndLint(comment)
assertThat(findings).isEmpty()
}
}
}
})
| apache-2.0 | 100d7b7115cee110b81ebc2f0e7e0e5c | 36.513333 | 102 | 0.519993 | 5.735984 | false | true | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/MultipleMoveTask.kt | 1 | 1784 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.tools.places
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.FileParameter
import uk.co.nickthecoder.paratask.parameters.StringParameter
import uk.co.nickthecoder.paratask.util.process.Exec
import uk.co.nickthecoder.paratask.util.process.OSCommand
class MultipleMoveTask : AbstractTask() {
override val taskD = TaskDescription("multipleMove", description =
"""Moves multiple files using wilcard patterns.
Examples
Rename all *.jpeg files to *.jpg:
from=*.jpeg to=#1.jpg
Replace the first occurrence of abc with xyz
from=*abc* to=#1xyz#2
""")
val directoryP = FileParameter("toDirectory", mustExist = true, expectFile = false)
val fromP = StringParameter("from")
val toP = StringParameter("to")
init {
taskD.addParameters(directoryP, fromP, toP)
}
override fun run() {
val command = OSCommand("mmv", "--", fromP.value, toP.value).dir(directoryP.value!!)
Exec(command).start().waitFor()
}
}
| gpl-3.0 | 0c2b138739a5f7baa3da765bca9245f8 | 32.037037 | 92 | 0.741592 | 4.139211 | false | false | false | false |
kozalosev/DeskChan-Launcher | src/main/kotlin/info/deskchan/launcher/util/ByteSizeStringConverter.kt | 1 | 625 | package info.deskchan.launcher.util
// Based on: http://programming.guide/java/formatting-byte-size-to-human-readable-format.html
class ByteSizeStringConverter(val bytes: Long, var si: Boolean = false) {
override fun toString(): String {
val _si = si
val unit = if (_si) 1000 else 1024
if (bytes < unit) return "$this B"
val exp = (Math.log(bytes.toDouble()) / Math.log(unit.toDouble())).toInt()
val pre = (if (_si) "kMGTPE" else "KMGTPE")[exp - 1] + if (_si) "" else "i"
return "%.1f %sB".format(bytes / Math.pow(unit.toDouble(), exp.toDouble()), pre)
}
}
| lgpl-3.0 | 4db97520e4b36b07b9ef4618185ad978 | 38.0625 | 93 | 0.6112 | 3.415301 | false | false | false | false |
arturbosch/detekt | detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/JCommander.kt | 1 | 1650 | package io.gitlab.arturbosch.detekt.cli
import com.beust.jcommander.JCommander
import com.beust.jcommander.ParameterException
import java.nio.file.Files
fun parseArguments(args: Array<out String>): CliArgs {
val cli = CliArgs()
val jCommander = JCommander(cli)
jCommander.programName = "detekt"
@Suppress("SwallowedException") // Stacktrace in jCommander is likely irrelevant.
try {
@Suppress("SpreadOperator")
jCommander.parse(*args)
} catch (ex: ParameterException) {
throw HandledArgumentViolation(ex.message, jCommander.usageAsString())
}
if (cli.help) {
throw HelpRequest(jCommander.usageAsString())
}
return cli.apply { validate(jCommander) }
}
private fun JCommander.usageAsString(): String {
val usage = StringBuilder()
this.usageFormatter.usage(usage)
return usage.toString()
}
private fun CliArgs.validate(jCommander: JCommander) {
val violations = StringBuilder()
val baseline = baseline
if (createBaseline && baseline == null) {
violations.appendLine("Creating a baseline.xml requires the --baseline parameter to specify a path.")
}
if (!createBaseline && baseline != null) {
if (Files.notExists(baseline)) {
violations.appendLine("The file specified by --baseline should exist '$baseline'.")
} else if (!Files.isRegularFile(baseline)) {
violations.appendLine("The path specified by --baseline should be a file '$baseline'.")
}
}
if (violations.isNotEmpty()) {
throw HandledArgumentViolation(violations.toString(), jCommander.usageAsString())
}
}
| apache-2.0 | 728f8355924579174660447d5dd47f1a | 30.132075 | 109 | 0.685455 | 4.471545 | false | false | false | false |
kiruto/kotlin-android-mahjong | app/src/main/java/dev/yuriel/mahjan/actor/SingleTileActor.kt | 1 | 2261 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* 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 dev.yuriel.mahjan.actor
import com.badlogic.gdx.graphics.g2d.Batch
import dev.yuriel.kotmvp.Dev
import dev.yuriel.kotmvp.FURO_TILE_HEIGHT
import dev.yuriel.kotmvp.FURO_TILE_WIDTH
import dev.yuriel.kotmvp.bases.BaseActor
import dev.yuriel.mahjan.enums.TileStatus
import dev.yuriel.mahjan.model.TileWrapper
/**
* Created by yuriel on 8/9/16.
*/
class SingleTileActor(private val tile: TileWrapper): BaseActor() {
private val size = Pair(FURO_TILE_WIDTH * Dev.U, FURO_TILE_HEIGHT * Dev.U)
init {
width = size.first
height = size.second
}
val status = tile.status
var position: Float = 0F
override fun destroy() {
tile.destroy()
}
override fun onDraw(batch: Batch?, parentAlpha: Float) {
if (tile.status == TileStatus.OBVERSE) {
batch?.draw(tile.back, position, 0F, size.first, size.second)
return
} else {
batch?.draw(tile.texture, position, 0F, size.first, size.second)
}
if (tile.status == TileStatus.HORIZONTAL) {
rotation = 90F
}
}
} | mit | e704cde0580509f2d23eb6669bdd3bd2 | 33.8 | 81 | 0.704113 | 3.973638 | false | false | false | false |
soywiz/korge | @old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Folder.kt | 1 | 1709 | package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter
/**
* Represents a folder in a Spriter SCML file.
* A folder has at least an [.id], [.name] and [.files] may be empty.
* An instance of this class holds an array of [File] instances.
* Specific [File] instances can be accessed via the corresponding methods, i.e getFile().
* @author Trixt0r
*/
class Folder(val id: Int, val name: String, files: Int) {
companion object {
val DUMMY = Folder(0, "", 0)
}
val files: Array<File> = Array<File>(files) { File.DUMMY }
private var filePointer = 0
/**
* Adds a [File] instance to this folder.
* @param file the file to add
*/
fun addFile(file: File) {
this.files[filePointer++] = file
}
/**
* Returns a [File] instance with the given index.
* @param index the index of the file
* *
* @return the file with the given name
*/
fun getFile(index: Int): File = files[index]
/**
* Returns a [File] instance with the given name.
* @param name the name of the file
* *
* @return the file with the given name or null if no file with the given name exists
*/
fun getFile(name: String): File? {
val index = getFileIndex(name)
return if (index >= 0) getFile(index) else null
}
/**
* Returns a file index with the given name.
* @param name the name of the file
* *
* @return the file index with the given name or -1 if no file with the given name exists
*/
internal fun getFileIndex(name: String): Int = this.files.firstOrNull { it.name == name }?.id ?: -1
override fun toString(): String {
var toReturn = "" + this::class + "|[id: " + id + ", name: " + name
for (file in files) toReturn += "\n" + file
toReturn += "]"
return toReturn
}
}
| apache-2.0 | 82c94ca0f324f54b30495c9056650a3c | 27.966102 | 100 | 0.654184 | 3.384158 | false | false | false | false |
permissions-dispatcher/PermissionsDispatcher | lint/src/test/java/permissions/dispatcher/CallNeedsPermissionDetectorKtTest.kt | 2 | 5042 | package permissions.dispatcher
import com.android.tools.lint.checks.infrastructure.TestFiles.java
import com.android.tools.lint.checks.infrastructure.TestFiles.kt
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import org.intellij.lang.annotations.Language
import org.junit.Test
import permissions.dispatcher.Utils.onNeedsPermission
import permissions.dispatcher.Utils.runtimePermission
class CallNeedsPermissionDetectorKtTest {
@Test
fun callNeedsPermissionMethod() {
@Language("kotlin") val foo = """
package com.example
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions
@RuntimePermissions
class Foo {
@NeedsPermission("Test")
fun fooBar() {
}
fun hoge() {
fooBar()
}
}
""".trimMargin()
val expectedText = """
|src/com/example/Foo.kt:13: Error: Trying to access permission-protected method directly [CallNeedsPermission]
| fooBar()
| ~~~~~~~~
|1 errors, 0 warnings
""".trimMargin()
lint()
.files(
java(runtimePermission),
java(onNeedsPermission),
kt(foo))
.issues(CallNeedsPermissionDetector.ISSUE)
.run()
.expect(expectedText)
.expectErrorCount(1)
.expectWarningCount(0)
}
@Test
fun callNeedsPermissionMethodNoError() {
@Language("kotlin") val foo = """
package com.example
class Foo {
fun someMethod() {
val baz = Baz()
baz.noFooBar()
}
}
""".trimMargin()
@Language("kotlin") val baz = """
package com.example
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions
@RuntimePermissions
class Baz {
@NeedsPermission("Test")
fun fooBar() {
}
fun noFooBar() {
}
}
""".trimMargin()
lint()
.files(
java(runtimePermission),
java(onNeedsPermission),
kt(foo),
kt(baz))
.issues(CallNeedsPermissionDetector.ISSUE)
.run()
.expectClean()
}
@Test
fun issues502() {
@Language("kotlin") val foo = """
package com.example
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions
@RuntimePermissions
class Foo: AppCompatActivity {
@NeedsPermission(Manifest.permission.READ_SMS)
fun requestOTP() {
PhoneVerificationInputFragment().requestOTP()
}
}
class FooFragment: Fragment {
fun resendOTP() {
requestOTP()
}
private fun requestOTP() {
}
}
""".trimMargin()
lint()
.files(
java(runtimePermission),
java(onNeedsPermission),
kt(foo))
.issues(CallNeedsPermissionDetector.ISSUE)
.run()
.expectClean()
}
@Test
fun `same name methods in different class(issue602)`() {
@Language("kotlin") val foo = """
package com.example
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions
@RuntimePermissions
class FirstActivity : AppCompatActivity() {
@NeedsPermission(Manifest.permission.CAMERA)
fun someFun() {
}
}
@RuntimePermissions
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
someFun()
}
fun someFun() {
}
@NeedsPermission(Manifest.permission.CAMERA)
fun otherFun() {
}
}
""".trimMargin()
lint()
.files(java(runtimePermission), java(onNeedsPermission), kt(foo))
.issues(CallNeedsPermissionDetector.ISSUE)
.run()
.expectClean()
}
}
| apache-2.0 | 29578572d33a11a144816e0cc3db7fb8 | 29.557576 | 122 | 0.476597 | 6.3025 | false | true | false | false |
android/health-samples | health-platform-v1/HealthPlatformSample/app/src/main/java/com/example/healthplatformsample/presentation/MainActivity.kt | 1 | 3477 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.healthplatformsample.presentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.material.Snackbar
import androidx.compose.material.SnackbarHost
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.compose.rememberNavController
import com.example.healthplatformsample.R
import com.example.healthplatformsample.data.HealthPlatformManager
import com.example.healthplatformsample.presentation.components.HealthPlatformBottomNavigation
import com.example.healthplatformsample.presentation.components.HealthPlatformNotSupported
import com.example.healthplatformsample.presentation.navigation.HealthPlatformNavigation
import com.example.healthplatformsample.presentation.theme.HealthPlatformSampleTheme
/**
* The entry point into the sample.
*/
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val healthPlatformManager = (application as BaseApplication).healthPlatformManager
setContent {
HealthPlatformApp(healthPlatformManager = healthPlatformManager)
}
}
}
@Composable
fun HealthPlatformApp(healthPlatformManager: HealthPlatformManager) {
HealthPlatformSampleTheme {
val scaffoldState = rememberScaffoldState()
val navController = rememberNavController()
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.app_name)) }
)
},
bottomBar = { HealthPlatformBottomNavigation(navController = navController) },
snackbarHost = {
SnackbarHost(it) { data -> Snackbar(snackbarData = data) }
}
) { innerPadding ->
Box(
modifier = Modifier.padding(0.dp, 0.dp, 0.dp, innerPadding.calculateBottomPadding())
) {
if (healthPlatformManager.healthPlatformSupported()) {
HealthPlatformNavigation(
navController = navController,
healthPlatformManager = healthPlatformManager,
scaffoldState = scaffoldState
)
} else {
HealthPlatformNotSupported()
}
}
}
}
}
| apache-2.0 | a9148627486b9919ac300b48d6be90bb | 38.511364 | 100 | 0.710958 | 5.244344 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/FeedCoordinatorBase.kt | 1 | 8311 | package org.wikipedia.feed
import android.content.Context
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.feed.accessibility.AccessibilityCard
import org.wikipedia.feed.announcement.AnnouncementClient
import org.wikipedia.feed.becauseyouread.BecauseYouReadClient
import org.wikipedia.feed.dataclient.FeedClient
import org.wikipedia.feed.dayheader.DayHeaderCard
import org.wikipedia.feed.featured.FeaturedArticleCard
import org.wikipedia.feed.image.FeaturedImageCard
import org.wikipedia.feed.model.Card
import org.wikipedia.feed.model.CardType
import org.wikipedia.feed.news.NewsCard
import org.wikipedia.feed.offline.OfflineCard
import org.wikipedia.feed.onthisday.OnThisDayCard
import org.wikipedia.feed.progress.ProgressCard
import org.wikipedia.feed.suggestededits.SuggestedEditsFeedClient
import org.wikipedia.feed.topread.TopReadListCard
import org.wikipedia.settings.Prefs
import org.wikipedia.util.DeviceUtil
import org.wikipedia.util.ThrowableUtil
import org.wikipedia.util.log.L
import java.util.*
abstract class FeedCoordinatorBase(private val context: Context) {
interface FeedUpdateListener {
fun insert(card: Card, pos: Int)
fun remove(card: Card, pos: Int)
fun finished(shouldUpdatePreviousCard: Boolean)
}
private val pendingClients = mutableListOf<FeedClient>()
private val callback = ClientRequestCallback()
private val progressCard = ProgressCard()
private var wiki: WikiSite? = null
private var updateListener: FeedUpdateListener? = null
private var currentDayCardAge = -1
private val hiddenCards =
Collections.newSetFromMap(object : LinkedHashMap<String, Boolean>() {
public override fun removeEldestEntry(eldest: Map.Entry<String, Boolean>): Boolean {
return size > MAX_HIDDEN_CARDS
}
})
val cards = mutableListOf<Card>()
var age = 0
init {
updateHiddenCards()
}
fun updateHiddenCards() {
hiddenCards.clear()
hiddenCards.addAll(Prefs.hiddenCards)
}
fun setFeedUpdateListener(listener: FeedUpdateListener?) {
updateListener = listener
}
open fun reset() {
wiki = null
age = 0
currentDayCardAge = -1
for (client in pendingClients) {
client.cancel()
}
pendingClients.clear()
cards.clear()
}
fun incrementAge() {
age++
}
fun more(wiki: WikiSite) {
this.wiki = wiki
if (cards.size == 0) {
requestProgressCard()
}
if (DeviceUtil.isAccessibilityEnabled) {
removeAccessibilityCard()
}
buildScript(age)
requestCard(wiki)
}
fun finished(): Boolean {
return pendingClients.isEmpty()
}
fun dismissCard(card: Card): Int {
val position = cards.indexOf(card)
when {
card.type() === CardType.RANDOM -> {
FeedContentType.RANDOM.isEnabled = false
FeedContentType.saveState()
}
card.type() === CardType.MAIN_PAGE -> {
FeedContentType.MAIN_PAGE.isEnabled = false
FeedContentType.saveState()
}
else -> {
addHiddenCard(card)
}
}
removeCard(card, position)
card.onDismiss()
return position
}
fun undoDismissCard(card: Card, position: Int) {
when {
card.type() === CardType.RANDOM -> {
FeedContentType.RANDOM.isEnabled = true
FeedContentType.saveState()
}
card.type() === CardType.MAIN_PAGE -> {
FeedContentType.MAIN_PAGE.isEnabled = true
FeedContentType.saveState()
}
else -> unHideCard(card)
}
insertCard(card, position)
card.onRestore()
}
protected abstract fun buildScript(age: Int)
fun addPendingClient(client: FeedClient?) {
if (client != null) {
pendingClients.add(client)
}
}
fun conditionallyAddPendingClient(client: FeedClient?, condition: Boolean) {
if (condition && client != null) {
pendingClients.add(client)
}
}
// Call to kick off the request chain or to retry a failed request. To move to the next pending
// client, call requestNextCard.
private fun requestCard(wiki: WikiSite) {
pendingClients.firstOrNull()?.request(context, wiki, age, callback) ?: removeProgressCard()
}
private fun requestNextCard(wiki: WikiSite) {
if (pendingClients.isNotEmpty()) {
pendingClients.removeAt(0)
}
if (lastCard !is ProgressCard && shouldShowProgressCard(pendingClients[0])) {
requestProgressCard()
}
requestCard(wiki)
}
fun requestOfflineCard() {
if (lastCard !is OfflineCard) {
appendCard(OfflineCard())
}
}
fun removeOfflineCard() {
if (lastCard is OfflineCard) {
dismissCard(lastCard as OfflineCard)
}
}
private val lastCard get() = cards.lastOrNull()
private fun requestProgressCard() {
if (lastCard !is ProgressCard) {
appendCard(progressCard)
}
}
private fun removeProgressCard() {
removeCard(progressCard, cards.indexOf(progressCard))
}
private fun setOfflineState() {
removeProgressCard()
requestOfflineCard()
}
private fun removeAccessibilityCard() {
if (lastCard is AccessibilityCard) {
removeCard(lastCard as AccessibilityCard, cards.indexOf(lastCard))
// TODO: possible on optimization if automatically scroll up to the next card.
}
}
private inner class ClientRequestCallback : FeedClient.Callback {
override fun success(cards: List<Card>) {
var atLeastOneAppended = false
for (card in cards) {
if (!isCardHidden(card)) {
appendCard(card)
atLeastOneAppended = true
}
}
wiki?.let { requestNextCard(it) }
if (pendingClients.isEmpty()) {
updateListener?.finished(!atLeastOneAppended)
}
}
override fun error(caught: Throwable) {
if (ThrowableUtil.isOffline(caught)) {
setOfflineState()
} else {
wiki?.let { requestNextCard(it) }
L.w(caught)
}
}
}
private fun appendCard(card: Card) {
val progressPos = cards.indexOf(progressCard)
var pos = if (progressPos >= 0) progressPos else cards.size
if (isDailyCardType(card) && currentDayCardAge < age) {
currentDayCardAge = age
insertCard(DayHeaderCard(currentDayCardAge), pos++)
}
insertCard(card, pos)
}
private fun insertCard(card: Card, position: Int) {
if (position < 0) {
return
}
cards.add(position, card)
updateListener?.insert(card, position)
}
private fun removeCard(card: Card, position: Int) {
if (position < 0) {
return
}
cards.remove(card)
updateListener?.remove(card, position)
}
private fun addHiddenCard(card: Card) {
hiddenCards.add(card.hideKey)
Prefs.hiddenCards = hiddenCards
}
private fun isCardHidden(card: Card): Boolean {
return hiddenCards.contains(card.hideKey)
}
private fun unHideCard(card: Card) {
hiddenCards.remove(card.hideKey)
Prefs.hiddenCards = hiddenCards
}
private fun isDailyCardType(card: Card): Boolean {
return card is NewsCard || card is OnThisDayCard ||
card is TopReadListCard || card is FeaturedArticleCard ||
card is FeaturedImageCard
}
private fun shouldShowProgressCard(pendingClient: FeedClient): Boolean {
return pendingClient is SuggestedEditsFeedClient ||
pendingClient is AnnouncementClient ||
pendingClient is BecauseYouReadClient
}
companion object {
private const val MAX_HIDDEN_CARDS = 100
}
}
| apache-2.0 | cf701a6a915670ea3a2ee1f3ef5645dc | 29.332117 | 100 | 0.615209 | 4.612098 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/data/local/db/entity/Movie.kt | 1 | 1207 | package tech.salroid.filmy.data.local.db.entity
import androidx.room.Entity
import com.google.gson.annotations.SerializedName
@Entity(tableName = "movies", primaryKeys = ["id", "type"])
data class Movie(
@SerializedName("id")
var id: Int,
@SerializedName("adult")
var adult: Boolean? = null,
@SerializedName("backdrop_path")
var backdropPath: String? = null,
@SerializedName("genre_ids")
var genreIds: ArrayList<Int> = arrayListOf(),
@SerializedName("original_language")
var originalLanguage: String? = null,
@SerializedName("original_title")
var originalTitle: String? = null,
@SerializedName("overview")
var overview: String? = null,
@SerializedName("popularity")
var popularity: Double? = null,
@SerializedName("poster_path")
var posterPath: String? = null,
@SerializedName("release_date")
var releaseDate: String? = null,
@SerializedName("title")
var title: String? = null,
@SerializedName("video")
var video: Boolean? = null,
@SerializedName("vote_average")
var voteAverage: Double? = null,
@SerializedName("vote_count")
var voteCount: Int? = null,
var type: Int = 0,
) | apache-2.0 | 14bc38c10029b7610aa4c121322463f4 | 22.230769 | 59 | 0.666114 | 4.077703 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/MainActivity.kt | 1 | 4913 | package au.com.codeka.warworlds.client
import android.content.Intent
import android.os.Bundle
import android.util.TypedValue
import android.view.MenuItem
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import au.com.codeka.warworlds.client.ctrl.DebugView
import au.com.codeka.warworlds.client.ctrl.drawer.DrawerController
import au.com.codeka.warworlds.client.game.starfield.scene.StarfieldManager
import au.com.codeka.warworlds.client.game.starfield.StarfieldScreen
import au.com.codeka.warworlds.client.game.welcome.CreateEmpireScreen
import au.com.codeka.warworlds.client.game.welcome.WarmWelcomeScreen
import au.com.codeka.warworlds.client.game.welcome.WelcomeScreen
import au.com.codeka.warworlds.client.net.auth.SIGN_IN_COMPLETE_RESULT_CODE
import au.com.codeka.warworlds.client.opengl.RenderSurfaceView
import au.com.codeka.warworlds.client.ui.ScreenStack
import au.com.codeka.warworlds.client.util.GameSettings
import au.com.codeka.warworlds.client.util.GameSettings.getBoolean
import au.com.codeka.warworlds.client.util.GameSettings.getString
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.tasks.Task
import com.google.common.base.Preconditions
class MainActivity : AppCompatActivity() {
// Will be non-null between of onCreate/onDestroy.
lateinit var starfieldManager: StarfieldManager
private set
// Will be non-null between onCreate/onDestroy.
private var screenStack: ScreenStack? = null
// Will be non-null between onCreate/onDestroy.
private var drawerController: DrawerController? = null
private var fragmentContainer: FrameLayout? = null
private var topPane: View? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
topPane = findViewById(R.id.top_pane)
setSupportActionBar(findViewById(R.id.toolbar))
App.auth.silentSignIn(this)
val renderSurfaceView = findViewById<RenderSurfaceView>(R.id.render_surface)
renderSurfaceView.setRenderer()
starfieldManager = StarfieldManager(renderSurfaceView)
starfieldManager.create()
val debugView = Preconditions.checkNotNull(findViewById<DebugView>(R.id.debug_view))
debugView.setFrameCounter(renderSurfaceView.frameCounter)
fragmentContainer = Preconditions.checkNotNull(findViewById(R.id.fragment_container))
screenStack = ScreenStack(this, fragmentContainer!!)
drawerController = DrawerController(
this,
screenStack!!,
supportActionBar!!,
findViewById(R.id.drawer_layout),
findViewById(R.id.drawer_content))
if (savedInstanceState != null) {
// TODO: restore the view state?
}
if (!getBoolean(GameSettings.Key.WARM_WELCOME_SEEN)) {
screenStack!!.push(WarmWelcomeScreen())
} else if (getString(GameSettings.Key.COOKIE).isEmpty()) {
screenStack!!.push(CreateEmpireScreen())
} else {
screenStack!!.push(WelcomeScreen())
}
}
fun setToolbarVisible(visible: Boolean) {
var marginSize: Int
if (visible) {
val typedValue = TypedValue()
theme.resolveAttribute(android.R.attr.actionBarSize, typedValue, true)
val attribute = intArrayOf(android.R.attr.actionBarSize)
val array = obtainStyledAttributes(typedValue.resourceId, attribute)
marginSize = array.getDimensionPixelSize(0, -1)
array.recycle()
// Adjust the margin by a couple of dp, the top pane has that strip of transparent pixels
marginSize -= TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 2f, resources.displayMetrics).toInt()
topPane!!.visibility = View.VISIBLE
supportActionBar!!.show()
} else {
marginSize = 0
topPane!!.visibility = View.GONE
supportActionBar!!.hide()
}
(fragmentContainer!!.layoutParams as FrameLayout.LayoutParams).topMargin = marginSize
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
@Suppress("DEPRECATION")
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SIGN_IN_COMPLETE_RESULT_CODE) {
val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
App.auth.handleSignInResult(task)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
drawerController!!.toggleDrawer()
return true
}
}
return false
}
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
if (!screenStack!!.backTo(StarfieldScreen::class.java)) {
super.onBackPressed()
}
}
public override fun onDestroy() {
super.onDestroy()
starfieldManager.destroy()
}
} | mit | f520a8e08e1c9e16d81759d4aaa8d7b6 | 34.868613 | 95 | 0.746998 | 4.305872 | false | false | false | false |
FDeityLink/KeroEdit | src/io/fdeitylink/keroedit/image/PxAttrManager.kt | 1 | 5021 | package io.fdeitylink.keroedit.image
import java.io.File
import java.nio.file.Paths
import java.nio.file.Files
import java.io.IOException
import java.text.ParseException
import java.nio.file.NoSuchFileException
import javafx.beans.property.ReadOnlyObjectProperty
import javafx.beans.property.ReadOnlyObjectWrapper
import io.fdeitylink.keroedit.gamedata.GameData
object PxAttrManager {
private val pxAttrMap = hashMapOf<String, ReadOnlyPxAttrWrapper>()
//TODO: Verify mpt00 is the default PXATTR file
private var mpt00: PxAttr? = null
@Throws(IOException::class, ParseException::class)
fun getPxAttr(tilesetName: String): ReadOnlyObjectProperty<PxAttr> {
if (!GameData.isInitialized) {
throw IllegalStateException("GameData must be initialized before PXATTRs can be retrieved from PxAttrManager")
}
if (pxAttrMap.contains(tilesetName)) {
return pxAttrMap[tilesetName]!!.readOnlyProperty
}
var path = Paths.get(GameData.resourceFolder.toString() +
File.separatorChar + GameData.imageFolder + File.separatorChar +
tilesetName + GameData.pxAttrExtension)
//If the mpt00 PXATTR was requested or it needs to be used as a default
val pxAttr = if ("mpt00" == tilesetName || !Files.exists(path)) {
if (null == mpt00) {
/*
* TODO:
* Don't throw except - return a PXATTR with all empty values
*/
path = path.resolveSibling("mpt00" + GameData.pxAttrExtension)
/*Paths.get(path.parent.toAbsolutePath().toString() + File.separatorChar +
"mpt00" + GameData.pxAttrExtension)*/
if (!Files.exists(path)) {
//The default PXATTR file mpt00 does not exist
/*
* TODO:
* Return null instead?
* Return PxAttr with all empty attributes?
*/
throw NoSuchFileException(path.toString(), null, "Missing default PXATTR file mpt00")
}
mpt00 = PxAttr(path)
}
/*
* Note that no changes are ever made to the mpt00 PXATTR
* if it is used as a default. Read the code for the
* setAttribute() method
*/
mpt00!!
}
else {
PxAttr(path)
}
val prop = ReadOnlyPxAttrWrapper(pxAttr)
pxAttrMap.put(tilesetName, prop)
return prop.readOnlyProperty
}
@Throws(IOException::class)
fun setAttribute(tilesetName: String, x: Int, y: Int, attribute: Int) {
require(pxAttrMap.contains(tilesetName))
{ "Given tileset has no stored PxAttr object yet (tilesetName: $tilesetName)" }
val prop = pxAttrMap[tilesetName]!!
/*
* mpt00.pxattr is used as the default PXATTR when no PXATTR
* file exists for a given tileset. As such, if a request is
* to change a property in a PXATTR file, we must check if
* mpt00 is the PXATTR being used for the tileset. If it is,
* we check if it is being used as a default (if being used
* as a default, tilesetName will be different from "mpt00").
* If it is in fact being used as a default, copy the properties
* of the mpt00 PXATTR into a new PXATTR and make the attribute
* changes on that new PXATTR. If mpt00 wasn't being used, or
* the tileset is mpt00, then we needn't make any new PXATTR
* and the attribute is simply changed on the PXATTR already
* corresponding to tilesetName
*/
if (prop.get() === mpt00 && "mpt00" != tilesetName) {
prop.set(PxAttr(mpt00!!, Paths.get(GameData.resourceFolder.toString() +
File.separatorChar + GameData.imageFolder + File.separatorChar +
tilesetName + GameData.pxAttrExtension)))
}
prop.setAttribute(x, y, attribute)
prop.get().save()
}
/**
* Clears all [PxAttr] objects stored by this object.
*/
fun wipe() {
//TODO: Also notify any MapEditTabs? This is only called when they are all closed but it doesn't hurt for safety
pxAttrMap.clear()
mpt00 = null
}
/*
* TODO:
* Use type alias?
* Use Kotlin observable properties?
*/
private class ReadOnlyPxAttrWrapper(pxAttr: PxAttr): ReadOnlyObjectWrapper<PxAttr>(pxAttr) {
fun setAttribute(x: Int, y: Int, attribute: Int) {
get().setAttribute(x, y, attribute)
/*
* This only triggers InvalidationListeners (not ChangeListeners)
* because the actual PxAttr object stored by this property is unchanged
*/
fireValueChangedEvent()
}
}
} | apache-2.0 | c07f99d85789d54c0942113802a43529 | 37.335878 | 122 | 0.591914 | 4.451241 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/calendar/JsValuesMappers.kt | 2 | 7224 | package abi43_0_0.expo.modules.calendar
import android.provider.CalendarContract
import android.util.Log
internal fun reminderStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Reminders.METHOD_ALARM -> "alarm"
CalendarContract.Reminders.METHOD_ALERT -> "alert"
CalendarContract.Reminders.METHOD_EMAIL -> "email"
CalendarContract.Reminders.METHOD_SMS -> "sms"
CalendarContract.Reminders.METHOD_DEFAULT -> "default"
else -> "default"
}
internal fun reminderConstantMatchingString(string: String?): Int =
when (string) {
"alert" -> CalendarContract.Reminders.METHOD_ALERT
"alarm" -> CalendarContract.Reminders.METHOD_ALARM
"email" -> CalendarContract.Reminders.METHOD_EMAIL
"sms" -> CalendarContract.Reminders.METHOD_SMS
else -> CalendarContract.Reminders.METHOD_DEFAULT
}
internal fun calendarAllowedRemindersFromDBString(dbString: String): ArrayList<String> {
val array = ArrayList<String>()
for (constant in dbString.split(",").toTypedArray()) {
try {
array.add(reminderStringMatchingConstant(constant.toInt()))
} catch (e: NumberFormatException) {
Log.e(CalendarModule.TAG, "Couldn't convert reminder constant into an int.", e)
}
}
return array
}
internal fun calendarAllowedAvailabilitiesFromDBString(dbString: String): ArrayList<String> {
val availabilitiesStrings = ArrayList<String>()
for (availabilityId in dbString.split(",").toTypedArray()) {
when (availabilityId.toInt()) {
CalendarContract.Events.AVAILABILITY_BUSY -> availabilitiesStrings.add("busy")
CalendarContract.Events.AVAILABILITY_FREE -> availabilitiesStrings.add("free")
CalendarContract.Events.AVAILABILITY_TENTATIVE -> availabilitiesStrings.add("tentative")
}
}
return availabilitiesStrings
}
internal fun availabilityStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Events.AVAILABILITY_BUSY -> "busy"
CalendarContract.Events.AVAILABILITY_FREE -> "free"
CalendarContract.Events.AVAILABILITY_TENTATIVE -> "tentative"
else -> "busy"
}
internal fun availabilityConstantMatchingString(string: String): Int =
when (string) {
"free" -> CalendarContract.Events.AVAILABILITY_FREE
"tentative" -> CalendarContract.Events.AVAILABILITY_TENTATIVE
else -> CalendarContract.Events.AVAILABILITY_BUSY
}
internal fun accessStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Events.ACCESS_CONFIDENTIAL -> "confidential"
CalendarContract.Events.ACCESS_PRIVATE -> "private"
CalendarContract.Events.ACCESS_PUBLIC -> "public"
CalendarContract.Events.ACCESS_DEFAULT -> "default"
else -> "default"
}
internal fun accessConstantMatchingString(string: String): Int =
when (string) {
"confidential" -> CalendarContract.Events.ACCESS_CONFIDENTIAL
"private" -> CalendarContract.Events.ACCESS_PRIVATE
"public" -> CalendarContract.Events.ACCESS_PUBLIC
else -> CalendarContract.Events.ACCESS_DEFAULT
}
internal fun calAccessStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR -> "contributor"
CalendarContract.Calendars.CAL_ACCESS_EDITOR -> "editor"
CalendarContract.Calendars.CAL_ACCESS_FREEBUSY -> "freebusy"
CalendarContract.Calendars.CAL_ACCESS_OVERRIDE -> "override"
CalendarContract.Calendars.CAL_ACCESS_OWNER -> "owner"
CalendarContract.Calendars.CAL_ACCESS_READ -> "read"
CalendarContract.Calendars.CAL_ACCESS_RESPOND -> "respond"
CalendarContract.Calendars.CAL_ACCESS_ROOT -> "root"
CalendarContract.Calendars.CAL_ACCESS_NONE -> "none"
else -> "none"
}
internal fun calAccessConstantMatchingString(string: String): Int =
when (string) {
"contributor" -> CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR
"editor" -> CalendarContract.Calendars.CAL_ACCESS_EDITOR
"freebusy" -> CalendarContract.Calendars.CAL_ACCESS_FREEBUSY
"override" -> CalendarContract.Calendars.CAL_ACCESS_OVERRIDE
"owner" -> CalendarContract.Calendars.CAL_ACCESS_OWNER
"read" -> CalendarContract.Calendars.CAL_ACCESS_READ
"respond" -> CalendarContract.Calendars.CAL_ACCESS_RESPOND
"root" -> CalendarContract.Calendars.CAL_ACCESS_ROOT
else -> CalendarContract.Calendars.CAL_ACCESS_NONE
}
internal fun attendeeRelationshipStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Attendees.RELATIONSHIP_ATTENDEE -> "attendee"
CalendarContract.Attendees.RELATIONSHIP_ORGANIZER -> "organizer"
CalendarContract.Attendees.RELATIONSHIP_PERFORMER -> "performer"
CalendarContract.Attendees.RELATIONSHIP_SPEAKER -> "speaker"
CalendarContract.Attendees.RELATIONSHIP_NONE -> "none"
else -> "none"
}
internal fun attendeeRelationshipConstantMatchingString(string: String): Int =
when (string) {
"attendee" -> CalendarContract.Attendees.RELATIONSHIP_ATTENDEE
"organizer" -> CalendarContract.Attendees.RELATIONSHIP_ORGANIZER
"performer" -> CalendarContract.Attendees.RELATIONSHIP_PERFORMER
"speaker" -> CalendarContract.Attendees.RELATIONSHIP_SPEAKER
else -> CalendarContract.Attendees.RELATIONSHIP_NONE
}
internal fun attendeeTypeStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Attendees.TYPE_OPTIONAL -> "optional"
CalendarContract.Attendees.TYPE_REQUIRED -> "required"
CalendarContract.Attendees.TYPE_RESOURCE -> "resource"
CalendarContract.Attendees.TYPE_NONE -> "none"
else -> "none"
}
internal fun attendeeTypeConstantMatchingString(string: String): Int =
when (string) {
"optional" -> CalendarContract.Attendees.TYPE_OPTIONAL
"required" -> CalendarContract.Attendees.TYPE_REQUIRED
"resource" -> CalendarContract.Attendees.TYPE_RESOURCE
else -> CalendarContract.Attendees.TYPE_NONE
}
internal fun calendarAllowedAttendeeTypesFromDBString(dbString: String): ArrayList<String> {
val array = ArrayList<String>()
for (constant in dbString.split(",").toTypedArray()) {
try {
array.add(attendeeTypeStringMatchingConstant(constant.toInt()))
} catch (e: NumberFormatException) {
Log.e(CalendarModule.TAG, "Couldn't convert attendee constant into an int.", e)
}
}
return array
}
internal fun attendeeStatusStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED -> "accepted"
CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED -> "declined"
CalendarContract.Attendees.ATTENDEE_STATUS_INVITED -> "invited"
CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE -> "tentative"
CalendarContract.Attendees.ATTENDEE_STATUS_NONE -> "none"
else -> "none"
}
internal fun attendeeStatusConstantMatchingString(string: String): Int =
when (string) {
"accepted" -> CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED
"declined" -> CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED
"invited" -> CalendarContract.Attendees.ATTENDEE_STATUS_INVITED
"tentative" -> CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE
else -> CalendarContract.Attendees.ATTENDEE_STATUS_NONE
}
| bsd-3-clause | f36091bffcfba75b0b5babc4d4f4a567 | 40.757225 | 94 | 0.751384 | 4.32834 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/ide/formatter/FortranFmtBlock.kt | 1 | 8745 | package org.jetbrains.fortran.ide.formatter
import com.intellij.formatting.*
import com.intellij.formatting.alignment.AlignmentStrategy
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.TokenType
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.formatter.FormatterUtil
import org.jetbrains.fortran.FortranLanguage
import org.jetbrains.fortran.lang.FortranTypes.EOL
import org.jetbrains.fortran.lang.psi.*
import java.util.*
class FortranFmtBlock(
private val node: ASTNode,
private val alignment: Alignment?,
private val indent: Indent,
private val wrap: Wrap?,
private val settings: CodeStyleSettings,
private val spacingBuilder: SpacingBuilder,
private val isFixedForm: Boolean
) : ASTBlock {
private val blockIsIncomplete: Boolean by lazy { FormatterUtil.isIncomplete(node) }
private val blockSubBlocks: List<Block> by lazy { buildChildren() }
override fun getAlignment(): Alignment? = alignment
override fun getChildAttributes(newChildIndex: Int): ChildAttributes = ChildAttributes(newChildIndent(), null)
override fun getIndent(): Indent? = indent
override fun getNode(): ASTNode = node
override fun getSpacing(child1: Block?, child2: Block): Spacing? = computeSpacing(child1, child2)
override fun getSubBlocks(): List<Block> = blockSubBlocks
override fun getTextRange(): TextRange = node.textRange
override fun getWrap(): Wrap? = wrap
override fun isIncomplete(): Boolean = blockIsIncomplete
override fun isLeaf(): Boolean = node.firstChildNode == null
override fun toString() = "${node.text} $textRange"
private fun buildChildren(): List<Block> {
if (isFixedForm) return emptyList()
val blocks = ArrayList<Block>()
val alignment = getAlignmentStrategy()
var child: ASTNode? = node.firstChildNode
while (child != null) {
val childType = child.elementType
if (child.textRange.length == 0) {
child = child.treeNext
continue
}
if (childType === TokenType.WHITE_SPACE || (childType === EOL && !child.text.contains(";"))) {
child = child.treeNext
continue
}
blocks.add(FortranFmtBlock(child,
alignment.getAlignment(child.elementType),
computeIndent(child),
null,
settings,
spacingBuilder,
isFixedForm))
child = child.treeNext
}
return blocks
}
private fun newChildIndent(): Indent? = when {
// inside blocks
node.psi is FortranProgramUnit -> Indent.getNormalIndent()
node.psi is FortranExecutableConstruct -> Indent.getNormalIndent()
node.psi is FortranDeclarationConstruct -> Indent.getNormalIndent()
node.psi is FortranInternalSubprogramPart -> Indent.getNormalIndent()
node.psi is FortranModuleSubprogramPart -> Indent.getNormalIndent()
node.psi is FortranInterfaceSpecification -> Indent.getNormalIndent()
// node.psi is FortranBlock -> Indent.getNormalIndent()
// line continuation
oneLineElement() -> Indent.getContinuationIndent()
else -> Indent.getNoneIndent()
}
private fun oneLineElement(): Boolean {
val parentPsi = node.psi
if (parentPsi is FortranFile
|| parentPsi is FortranProgramUnit
|| parentPsi is FortranBlock
|| parentPsi is FortranModuleSubprogramPart
|| parentPsi is FortranInternalSubprogramPart
|| parentPsi is FortranDeclarationConstruct
|| parentPsi is FortranExecutableConstruct
|| parentPsi is FortranComponentPart
|| parentPsi is FortranInterfaceSpecification) {
return false
}
return true
}
private fun computeIndent(child: ASTNode): Indent {
return when {
// always not indented
child.psi is FortranContainsStmt -> return Indent.getNoneIndent()
child.psi is FortranMacro -> Indent.getAbsoluteNoneIndent()
// inside blocks
node.psi is FortranMainProgram && node.psi.firstChild !is FortranStmt -> Indent.getNoneIndent()
node.psi is FortranProgramUnit && child.psi !is FortranStmt
&& child.psi !is FortranInternalSubprogramPart
&& child.psi !is FortranModuleSubprogramPart -> Indent.getNormalIndent()
node.psi is FortranDerivedTypeDef && child.psi is FortranTypeBoundProcedurePart -> Indent.getNoneIndent()
node.psi is FortranTypeBoundProcedurePart -> Indent.getNormalIndent()
node.psi is FortranExecutableConstruct && child.psi !is FortranStmt -> Indent.getNormalIndent()
node.psi is FortranEnumDef && child.psi is FortranEnumeratorDefStmt -> Indent.getNormalIndent()
node.psi is FortranEnumDef && child.psi !is FortranEnumeratorDefStmt -> Indent.getNoneIndent()
node.psi is FortranInterfaceSpecification -> Indent.getNoneIndent()
node.psi is FortranDeclarationConstruct && child.psi !is FortranStmt -> Indent.getNormalIndent()
node.psi is FortranInternalSubprogramPart && child.psi !is FortranStmt -> Indent.getNormalIndent()
node.psi is FortranModuleSubprogramPart && child.psi !is FortranStmt -> Indent.getNormalIndent()
// Line continuation
oneLineElement() && (node.firstChildNode !== child) -> Indent.getContinuationIndent()
else -> Indent.getNoneIndent()
}
}
private fun computeSpacing(child1: Block?, child2: Block): Spacing? {
if (child1 is ASTBlock && child2 is ASTBlock) {
val fortranCommonSettings = settings.getCommonSettings(FortranLanguage)
val node1 = child1.node
val node2 = child2.node
val psi1 = node1?.psi
val psi2 = node2?.psi
// MAYBE WE CAN MAKE IT BEAUTIFUL
// NEED TO ADD MORE PSI HERE
if ((node1?.elementType === FortranTokenType.LINE_COMMENT
|| psi1 is FortranStmt
|| psi1 is FortranExecutableConstruct
|| psi1 is FortranDeclarationConstruct
|| psi1 is FortranBlock)
&& (psi2 is FortranStmt
|| psi2 is FortranExecutableConstruct
|| psi2 is FortranDeclarationConstruct
|| psi2 is FortranBlock)) {
return Spacing.createSpacing(0, Int.MAX_VALUE, 1, true, fortranCommonSettings.KEEP_BLANK_LINES_IN_CODE)
}
// before comment
if (node1?.elementType === EOL && node2?.elementType === FortranTokenType.LINE_COMMENT) {
return Spacing.createSpacing(0, Int.MAX_VALUE, 1, true, fortranCommonSettings.KEEP_BLANK_LINES_IN_CODE)
}
// before subprogram part
if ((psi1 is FortranBlock || psi1 is FortranStmt)
&& (psi2 is FortranModuleSubprogramPart || psi2 is FortranInternalSubprogramPart || psi2 is FortranInterfaceSpecification))
return Spacing.createSpacing(0, Int.MAX_VALUE, 1, true, fortranCommonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS)
// before subprogram
if ((psi1 is FortranStmt) && psi2 is FortranProgramUnit)
return Spacing.createSpacing(0, Int.MAX_VALUE, 1, true, fortranCommonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS)
// between subprograms
if (psi1 is FortranProgramUnit && psi2 is FortranProgramUnit)
return Spacing.createSpacing(0, Int.MAX_VALUE, 1, true, fortranCommonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS)
// between subprogram and comment
if (psi1 is FortranProgramUnit && node2?.elementType === FortranTokenType.LINE_COMMENT)
return Spacing.createSpacing(0, Int.MAX_VALUE, 1, true, fortranCommonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS)
// after subprogram
if ((psi1 is FortranModuleSubprogramPart || psi1 is FortranInternalSubprogramPart)
&& (psi2 is FortranStmt || node2?.elementType === FortranTokenType.LINE_COMMENT))
return Spacing.createSpacing(0, Int.MAX_VALUE, 1, true, fortranCommonSettings.KEEP_BLANK_LINES_IN_DECLARATIONS)
}
return spacingBuilder.getSpacing(this, child1, child2)
}
private fun getAlignmentStrategy(): AlignmentStrategy = AlignmentStrategy.getNullStrategy()
}
| apache-2.0 | 3f8c2afd9243bcd48afb73410a899fd3 | 48.971429 | 143 | 0.6494 | 4.935102 | false | false | false | false |
androidx/androidx | privacysandbox/tools/tools-apigenerator/src/test/test-data/values/output/com/sdkwithvalues/SdkRequestConverter.kt | 3 | 1029 | package com.sdkwithvalues
public object SdkRequestConverter {
public fun fromParcelable(parcelable: ParcelableSdkRequest): SdkRequest {
val annotatedValue = SdkRequest(
id = parcelable.id,
innerValue =
com.sdkwithvalues.InnerSdkValueConverter.fromParcelable(parcelable.innerValue),
moreValues = parcelable.moreValues.map {
com.sdkwithvalues.InnerSdkValueConverter.fromParcelable(it) }.toList())
return annotatedValue
}
public fun toParcelable(annotatedValue: SdkRequest): ParcelableSdkRequest {
val parcelable = ParcelableSdkRequest()
parcelable.id = annotatedValue.id
parcelable.innerValue =
com.sdkwithvalues.InnerSdkValueConverter.toParcelable(annotatedValue.innerValue)
parcelable.moreValues = annotatedValue.moreValues.map {
com.sdkwithvalues.InnerSdkValueConverter.toParcelable(it) }.toTypedArray()
return parcelable
}
}
| apache-2.0 | 5321b0d84fab6fdba94bb4c16ad37511 | 43.73913 | 103 | 0.680272 | 5.22335 | false | false | false | false |
DemonWav/autosync | src/main/kotlin/com/demonwav/autosync/Table.kt | 1 | 1879 | package com.demonwav.autosync
import com.intellij.openapi.roots.ui.CellAppearanceEx
import com.intellij.openapi.roots.ui.FileAppearanceService
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.ui.ColoredTableCellRenderer
import com.intellij.util.ui.ItemRemovable
import javax.swing.BorderFactory
import javax.swing.JTable
import javax.swing.table.DefaultTableModel
class TableModel : DefaultTableModel(), ItemRemovable {
override fun getColumnName(column: Int) = null
override fun getColumnClass(columnIndex: Int) = TableItem::class.java
override fun getColumnCount() = 1
override fun isCellEditable(row: Int, column: Int) = false
fun getValueAt(row: Int) = getValueAt(row, 0) as TableItem
fun addTableItem(item: TableItem) = addRow(arrayOf(item))
}
class TableItem {
val url: String
val cellAppearance: CellAppearanceEx
constructor(file: VirtualFile) {
url = file.url
cellAppearance = FileAppearanceService.getInstance().forVirtualFile(file)
}
constructor(url: String) {
this.url = url
val file = VirtualFileManager.getInstance().findFileByUrl(url)
cellAppearance = if (file != null) {
FileAppearanceService.getInstance().forVirtualFile(file)
} else {
FileAppearanceService.getInstance().forInvalidUrl(url)
}
}
}
class Renderer : ColoredTableCellRenderer() {
override fun customizeCellRenderer(table: JTable?, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int) {
setPaintFocusBorder(false)
setFocusBorderAroundIcon(true)
border = NO_FOCUS_BORDER
(value as TableItem).cellAppearance.customize(this)
}
companion object {
private val NO_FOCUS_BORDER = BorderFactory.createEmptyBorder(1, 1, 1, 1)
}
}
| mit | 1477e63f389d82f806f083d0db8a6d49 | 33.163636 | 130 | 0.724321 | 4.329493 | false | false | false | false |
esofthead/mycollab | mycollab-web/src/main/java/com/mycollab/vaadin/resources/VaadinResourceFactory.kt | 3 | 2690 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.vaadin.resources
import com.mycollab.configuration.SiteConfiguration
import com.mycollab.core.MyCollabException
import com.mycollab.module.file.service.AbstractStorageService
import com.mycollab.spring.AppContextUtil
import com.mycollab.vaadin.AppUI
import com.mycollab.vaadin.resources.file.VaadinFileResource
import com.vaadin.server.ExternalResource
import com.vaadin.server.Resource
/**
* @author MyCollab Ltd
* @since 5.1.4
*/
class VaadinResourceFactory private constructor() {
private var vaadinResource: VaadinResource? = null
init {
vaadinResource = if (SiteConfiguration.isDemandEdition()) {
try {
val cls = Class.forName(S3_CLS) as Class<VaadinResource>
cls.getDeclaredConstructor().newInstance()
} catch (e: Exception) {
throw MyCollabException("Exception when load s3 resource file", e)
}
} else {
VaadinFileResource()
}
}
companion object {
private val S3_CLS = "com.mycollab.ondemand.vaadin.resources.s3.VaadinS3Resource"
private val _instance = VaadinResourceFactory()
@JvmStatic
val instance: VaadinResource?
get() = _instance.vaadinResource
@JvmStatic
fun getResource(documentPath: String) =
ExternalResource(AppContextUtil.getSpringBean(AbstractStorageService::class.java)
.getResourcePath(documentPath))
@JvmStatic
fun getLogoResource(logoId: String, size: Int) =
ExternalResource(AppContextUtil.getSpringBean(AbstractStorageService::class.java)
.getLogoPath(AppUI.accountId, logoId, size))
@JvmStatic
fun getAvatarResource(avatarId: String, size: Int) =
ExternalResource(AppContextUtil.getSpringBean(AbstractStorageService::class.java)
.getAvatarPath(avatarId, size))
}
}
| agpl-3.0 | e71e045eacf721de7c2ca665a533a77a | 36.347222 | 97 | 0.686872 | 4.725835 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/messages/dto/MessagesConversation.kt | 1 | 4531 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.messages.dto
import com.google.gson.annotations.SerializedName
import kotlin.Boolean
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param peer
* @param lastMessageId - ID of the last message in conversation
* @param inRead - Last message user have read
* @param outRead - Last outcoming message have been read by the opponent
* @param sortId
* @param lastConversationMessageId - Conversation message ID of the last message in conversation
* @param unreadCount - Unread messages number
* @param isMarkedUnread - Is this conversation uread
* @param outReadBy
* @param important
* @param unanswered
* @param specialServiceType
* @param messageRequestData
* @param mentions - Ids of messages with mentions
* @param expireMessages - Ids of messages with expiration time
* @param currentKeyboard
* @param pushSettings
* @param canWrite
* @param canSendMoney
* @param canReceiveMoney
* @param chatSettings
* @param spamExpiration
* @param isNew
* @param isArchived
*/
data class MessagesConversation(
@SerializedName("peer")
val peer: MessagesConversationPeer,
@SerializedName("last_message_id")
val lastMessageId: Int,
@SerializedName("in_read")
val inRead: Int,
@SerializedName("out_read")
val outRead: Int,
@SerializedName("sort_id")
val sortId: MessagesConversationSortId? = null,
@SerializedName("last_conversation_message_id")
val lastConversationMessageId: Int? = null,
@SerializedName("unread_count")
val unreadCount: Int? = null,
@SerializedName("is_marked_unread")
val isMarkedUnread: Boolean? = null,
@SerializedName("out_read_by")
val outReadBy: MessagesOutReadBy? = null,
@SerializedName("important")
val important: Boolean? = null,
@SerializedName("unanswered")
val unanswered: Boolean? = null,
@SerializedName("special_service_type")
val specialServiceType: MessagesConversation.SpecialServiceType? = null,
@SerializedName("message_request_data")
val messageRequestData: MessagesMessageRequestData? = null,
@SerializedName("mentions")
val mentions: List<Int>? = null,
@SerializedName("expire_messages")
val expireMessages: List<Int>? = null,
@SerializedName("current_keyboard")
val currentKeyboard: MessagesKeyboard? = null,
@SerializedName("push_settings")
val pushSettings: MessagesPushSettings? = null,
@SerializedName("can_write")
val canWrite: MessagesConversationCanWrite? = null,
@SerializedName("can_send_money")
val canSendMoney: Boolean? = null,
@SerializedName("can_receive_money")
val canReceiveMoney: Boolean? = null,
@SerializedName("chat_settings")
val chatSettings: MessagesChatSettings? = null,
@SerializedName("spam_expiration")
val spamExpiration: Int? = null,
@SerializedName("is_new")
val isNew: Boolean? = null,
@SerializedName("is_archived")
val isArchived: Boolean? = null
) {
enum class SpecialServiceType(
val value: String
) {
@SerializedName("business_notify")
BUSINESS_NOTIFY("business_notify");
}
}
| mit | 99a8a269a0c0bd5cb9870f09d0f1741a | 37.398305 | 97 | 0.70448 | 4.403304 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/messages/dto/MessagesChatSettings.kt | 1 | 3185 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.messages.dto
import com.google.gson.annotations.SerializedName
import com.vk.dto.common.id.UserId
import kotlin.Boolean
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param ownerId
* @param title - Chat title
* @param state
* @param activeIds
* @param acl
* @param membersCount
* @param friendsCount
* @param pinnedMessage
* @param photo
* @param adminIds - Ids of chat admins
* @param isGroupChannel
* @param permissions
* @param isDisappearing
* @param theme
* @param disappearingChatLink
* @param isService
*/
data class MessagesChatSettings(
@SerializedName("owner_id")
val ownerId: UserId,
@SerializedName("title")
val title: String,
@SerializedName("state")
val state: MessagesChatSettingsState,
@SerializedName("active_ids")
val activeIds: List<UserId>,
@SerializedName("acl")
val acl: MessagesChatSettingsAcl,
@SerializedName("members_count")
val membersCount: Int? = null,
@SerializedName("friends_count")
val friendsCount: Int? = null,
@SerializedName("pinned_message")
val pinnedMessage: MessagesPinnedMessage? = null,
@SerializedName("photo")
val photo: MessagesChatSettingsPhoto? = null,
@SerializedName("admin_ids")
val adminIds: List<UserId>? = null,
@SerializedName("is_group_channel")
val isGroupChannel: Boolean? = null,
@SerializedName("permissions")
val permissions: MessagesChatSettingsPermissions? = null,
@SerializedName("is_disappearing")
val isDisappearing: Boolean? = null,
@SerializedName("theme")
val theme: String? = null,
@SerializedName("disappearing_chat_link")
val disappearingChatLink: String? = null,
@SerializedName("is_service")
val isService: Boolean? = null
)
| mit | 77389c2b5c238048fefcc09c98eeb7d7 | 35.193182 | 81 | 0.695761 | 4.357045 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/Distribution.kt | 1 | 2613 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.konan.target.*
import org.jetbrains.kotlin.konan.file.*
import org.jetbrains.kotlin.konan.properties.*
class Distribution(val targetManager: TargetManager,
val propertyFileOverride: String? = null,
val runtimeFileOverride: String? = null) {
val target = targetManager.target
val targetName = targetManager.targetName
val host = TargetManager.host
val hostSuffix = TargetManager.hostSuffix
val hostTargetSuffix = targetManager.hostTargetSuffix
val targetSuffix = targetManager.targetSuffix
val localKonanDir = "${File.userHome}/.konan"
private fun findKonanHome(): String {
val value = System.getProperty("konan.home", "dist")
val path = File(value).absolutePath
return path
}
val konanHome = findKonanHome()
val propertyFileName = propertyFileOverride ?: "$konanHome/konan/konan.properties"
val properties = File(propertyFileName).loadProperties()
val klib = "$konanHome/klib"
val stdlib = "$klib/stdlib"
val runtime = runtimeFileOverride ?: "$stdlib/targets/${targetName}/native/runtime.bc"
val dependenciesDir = "$konanHome/dependencies"
val targetProperties = KonanProperties(target, properties, dependenciesDir)
val hostProperties = if (target == host) {
targetProperties
} else {
KonanProperties(host, properties, dependenciesDir)
}
val dependencies = targetProperties.dependencies
val llvmHome = hostProperties.absoluteLlvmHome
val hostSysRoot = hostProperties.absoluteTargetSysRoot
val llvmBin = "$llvmHome/bin"
val llvmLib = "$llvmHome/lib"
val llvmLto = "$llvmBin/llvm-lto"
private val libLTODir = when (TargetManager.host) {
KonanTarget.MACBOOK, KonanTarget.LINUX -> llvmLib
KonanTarget.MINGW -> llvmBin
else -> error("Don't know libLTO location for this platform.")
}
val libLTO = "$libLTODir/${System.mapLibraryName("LTO")}"
}
| apache-2.0 | b8ab7c6943ac3e48d659adc6e39387d3 | 35.291667 | 90 | 0.720628 | 4.340532 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/callableReference/bound/equals/receiverInEquals.kt | 2 | 627 | // TODO: investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
package test
class A {
fun foo() {}
fun bar() {}
}
val a = A()
val aa = A()
val aFoo = a::foo
val aBar = a::bar
val aaFoo = aa::foo
val A_foo = A::foo
fun box(): String =
when {
aFoo != a::foo -> "Bound refs with same receiver SHOULD be equal"
aFoo == aBar -> "Bound refs to different members SHOULD NOT be equal"
aFoo == aaFoo -> "Bound refs with different receiver SHOULD NOT be equal"
aFoo == A_foo -> "Bound ref SHOULD NOT be equal to free ref"
else -> "OK"
} | apache-2.0 | 98f18755bc56936ce324675b1311a994 | 22.259259 | 85 | 0.564593 | 3.522472 | false | false | false | false |
Cognifide/APM | app/aem/core/src/main/kotlin/com/cognifide/apm/core/endpoints/ScriptExecutionStatusForm.kt | 1 | 1250 | /*
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* 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.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.endpoints
import com.cognifide.apm.core.endpoints.params.RequestParameter
import org.apache.sling.api.SlingHttpServletRequest
import org.apache.sling.models.annotations.Model
import javax.inject.Inject
@Model(adaptables = [SlingHttpServletRequest::class])
class ScriptExecutionStatusForm @Inject constructor(
@param:RequestParameter("id", optional = false) val id: String
) | apache-2.0 | e802bd63981b496bd9bb0454656fa169 | 38.387097 | 75 | 0.6728 | 4.562044 | false | false | false | false |
divinespear/jpa-schema-gradle-plugin | src/functionalTest/kotlin/io/github/divinespear/plugin/test/functional/issue/Issue41KotlinSpec.kt | 1 | 3266 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.divinespear.plugin.test.functional.issue
import io.github.divinespear.plugin.test.KotlinFunctionalSpec
import io.kotest.matchers.and
import io.kotest.matchers.file.exist
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.contain
import org.gradle.testkit.runner.TaskOutcome
class Issue41KotlinSpec : KotlinFunctionalSpec() {
init {
"task" should {
"work with Hibernate 5.4.7 or higher" {
buildFile.appendText(
"""
plugins {
id("io.github.divinespear.jpa-schema-generate")
id("io.spring.dependency-management") version("1.0.9.RELEASE")
id("org.springframework.boot") version("2.2.5.RELEASE")
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
//compile 'org.hibernate:hibernate-entitymanager:5.4.7.Final'
runtimeOnly("org.mariadb.jdbc:mariadb-java-client:2.+")
}
generateSchema {
vendor = "hibernate+spring"
databaseProductName = "MariaDB"
databaseMajorVersion = 10
databaseMinorVersion = 3
databaseAction = "none"
scriptAction = "create"
format = true
jdbcDriver = "org.mariadb.jdbc.Driver"
createOutputFileName = "initial-create.sql"
packageToScan = setOf("io.github.divinespear.model")
properties = mapOf(
"hibernate.dialect" to "org.hibernate.dialect.MariaDB103Dialect",
"hibernate.physical_naming_strategy" to "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy",
"hibernate.implicit_naming_strategy" to "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
)
}
""".trimIndent()
)
val result = runGenerateSchemaTask()
result.task(":generateSchema") should {
it?.outcome shouldBe TaskOutcome.SUCCESS
}
resultFile("build/generated-schema/initial-create.sql") should {
exist()
it.readText() should (contain("create table key_value_store") and contain("create table many_column_table"))
}
}
}
}
}
| apache-2.0 | f9b41475a3c7ad39bf074a65edbbe2cf | 38.829268 | 130 | 0.640845 | 4.536111 | false | true | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/permissions/requesters/LegacyLocationRequester.kt | 2 | 2557 | package abi44_0_0.expo.modules.permissions.requesters
import android.Manifest
import android.os.Build
import android.os.Bundle
import abi44_0_0.expo.modules.interfaces.permissions.PermissionsResponse
import abi44_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.SCOPE_ALWAYS
import abi44_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.SCOPE_IN_USE
import abi44_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.SCOPE_KEY
import abi44_0_0.expo.modules.interfaces.permissions.PermissionsResponse.Companion.SCOPE_NONE
import abi44_0_0.expo.modules.interfaces.permissions.PermissionsStatus
class LegacyLocationRequester(private val includeBackgroundPermission: Boolean = false) : PermissionRequester {
override fun getAndroidPermissions(): List<String> {
val list = mutableListOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
if (includeBackgroundPermission && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
list.add(0, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
}
return list
}
override fun parseAndroidPermissions(permissionsResponse: Map<String, PermissionsResponse>): Bundle {
return parseBasicLocationPermissions(permissionsResponse).apply {
val accessFineLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_FINE_LOCATION)
val accessCoarseLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_COARSE_LOCATION)
val accuracy = when {
accessFineLocation.status == PermissionsStatus.GRANTED -> {
"fine"
}
accessCoarseLocation.status == PermissionsStatus.GRANTED -> {
"coarse"
}
else -> {
"none"
}
}
val scope =
if (includeBackgroundPermission && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val accessBackgroundLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
if (accessBackgroundLocation.status == PermissionsStatus.GRANTED) {
SCOPE_ALWAYS
} else {
SCOPE_IN_USE
}
} else if (accessCoarseLocation.status == PermissionsStatus.GRANTED || accessFineLocation.status == PermissionsStatus.GRANTED) {
SCOPE_ALWAYS
} else {
SCOPE_NONE
}
putString(SCOPE_KEY, scope)
putBundle(
"android",
Bundle().apply {
putString("accuracy", accuracy)
}
)
}
}
}
| bsd-3-clause | efb6e30cbe034eb9a9e2e6ee90dedc2e | 38.338462 | 136 | 0.712554 | 4.74397 | false | false | false | false |
Heiner1/AndroidAPS | openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansAPI.kt | 1 | 7426 | package info.nightscout.androidaps.plugin.general.openhumans
import android.annotation.SuppressLint
import android.util.Base64
import info.nightscout.androidaps.plugin.general.openhumans.di.BaseUrl
import info.nightscout.androidaps.plugin.general.openhumans.di.ClientId
import info.nightscout.androidaps.plugin.general.openhumans.di.ClientSecret
import info.nightscout.androidaps.plugin.general.openhumans.di.RedirectUrl
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.*
import okio.BufferedSink
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject
import kotlin.coroutines.resumeWithException
internal class OpenHumansAPI @Inject constructor(
@BaseUrl
private val baseUrl: String,
@ClientId
clientId: String,
@ClientSecret
clientSecret: String,
@RedirectUrl
private val redirectUrl: String
) {
private val authHeader = "Basic " + Base64.encodeToString("$clientId:$clientSecret".toByteArray(), Base64.NO_WRAP)
private val client = OkHttpClient()
suspend fun exchangeBearerToken(bearerToken: String) = sendTokenRequest(FormBody.Builder()
.add("grant_type", "authorization_code")
.add("redirect_uri", redirectUrl)
.add("code", bearerToken)
.build())
suspend fun refreshAccessToken(refreshToken: String) = sendTokenRequest(FormBody.Builder()
.add("grant_type", "refresh_token")
.add("redirect_uri", redirectUrl)
.add("refresh_token", refreshToken)
.build())
private suspend fun sendTokenRequest(body: FormBody): OAuthTokens {
val timestamp = System.currentTimeMillis()
val request = Request.Builder()
.url("$baseUrl/oauth2/token/")
.addHeader("Authorization", authHeader)
.post(body)
.build()
val response = request.await()
val json = response.body?.let { JSONObject(it.string()) }
if (json == null || !response.isSuccessful) throw OHHttpException(response.code, response.message, json?.getString("error"))
val accessToken = json.getString("access_token") ?: throw OHProtocolViolationException("access_token missing")
val refreshToken = json.getString("refresh_token") ?: throw OHProtocolViolationException("refresh_token missing")
if (!json.has("expires_in")) throw OHProtocolViolationException("expires_in missing")
val expiresAt = timestamp + json.getInt("expires_in") * 1000L
return OAuthTokens(accessToken, refreshToken, expiresAt)
}
suspend fun getProjectMemberId(accessToken: String): String {
val request = Request.Builder()
.url("$baseUrl/api/direct-sharing/project/exchange-member/?access_token=$accessToken")
.get()
.build()
val response = request.await()
val json = response.body?.let { JSONObject(it.string()) }
if (json == null || !response.isSuccessful) throw OHHttpException(response.code, response.message, json?.getString("detail"))
return json.getString("project_member_id") ?: throw OHProtocolViolationException("project_member_id missing")
}
suspend fun prepareFileUpload(accessToken: String, fileName: String, metadata: FileMetadata): PreparedUpload {
val request = Request.Builder()
.url("$baseUrl/api/direct-sharing/project/files/upload/direct/?access_token=$accessToken")
.post(FormBody.Builder()
.add("filename", fileName)
.add("metadata", metadata.toJSON().toString())
.build())
.build()
val response = request.await()
val json = response.body?.let { JSONObject(it.string()) }
if (json == null || !response.isSuccessful) throw OHHttpException(response.code, response.message, json?.getString("detail"))
return PreparedUpload(
fileId = json.getString("id") ?: throw OHProtocolViolationException("id missing"),
uploadURL = json.getString("url") ?: throw OHProtocolViolationException("url missing")
)
}
suspend fun uploadFile(url: String, content: ByteArray) {
val request = Request.Builder()
.url(url)
.put(object : RequestBody() {
override fun contentType(): MediaType? = null
override fun contentLength(): Long = content.size.toLong()
override fun writeTo(sink: BufferedSink) {
sink.write(content)
}
})
.build()
val response = request.await()
if (!response.isSuccessful) throw OHHttpException(response.code, response.message, null)
}
suspend fun completeFileUpload(accessToken: String, fileId: String) {
val request = Request.Builder()
.url("$baseUrl/api/direct-sharing/project/files/upload/complete/?access_token=$accessToken")
.post(FormBody.Builder()
.add("file_id", fileId)
.build())
.build()
val response = request.await()
if (!response.isSuccessful) throw OHHttpException(response.code, response.message, null)
}
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun Request.await(): Response {
val call = client.newCall(this)
return suspendCancellableCoroutine {
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
it.resumeWithException(e)
}
override fun onResponse(call: Call, response: Response) {
it.resume(response, null)
}
})
it.invokeOnCancellation { call.cancel() }
}
}
data class FileMetadata(
val tags: List<String>,
val description: String,
val md5: String? = null,
val creationDate: Long? = null,
val startDate: Long? = null,
val endDate: Long? = null
) {
fun toJSON(): JSONObject {
val jsonObject = JSONObject()
jsonObject.put("tags", JSONArray().apply { tags.forEach { put(it) } })
jsonObject.put("description", description)
jsonObject.put("md5", md5)
creationDate?.let { jsonObject.put("creation_date", iso8601DateFormatter.format(Date(it))) }
startDate?.let { jsonObject.put("start_date", iso8601DateFormatter.format(Date(it))) }
endDate?.let { jsonObject.put("end_date", iso8601DateFormatter.format(Date(it))) }
return jsonObject
}
}
data class PreparedUpload(
val fileId: String,
val uploadURL: String
)
data class OAuthTokens(
val accessToken: String,
val refreshToken: String,
val expiresAt: Long
)
data class OHHttpException(
val code: Int,
val meaning: String,
val detail: String?
) : RuntimeException() {
override val message: String get() = toString()
}
class OHProtocolViolationException(
override val message: String
) : RuntimeException()
private companion object {
@SuppressLint("SimpleDateFormat")
val iso8601DateFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
}
} | agpl-3.0 | 87b955b6b26343ff819b8e715206912e | 39.36413 | 133 | 0.645031 | 4.723919 | false | false | false | false |
A-Zaiats/Kotlinextensions | kotlinextensions/src/main/java/io/github/azaiats/kotlinextensions/Optional.kt | 1 | 1232 | @file:Suppress("unused")
package io.github.azaiats.kotlinextensions
/**
* @author Andrei Zaiats
* @since 02/05/2017
*/
class Optional<T> private constructor(private val value: T?) {
companion object {
fun <T> of(value: T) = Optional(value)
fun <T> ofNullable(value: T?) = Optional(value)
fun <T> empty() = Optional(null as T?)
}
fun get(): T = value ?: error("No value present")
fun isPresent() = value != null
fun ifPresent(action: (T) -> Unit) = value?.let(action)
fun orElse(other: T): T = value ?: other
fun orElseGet(producer: () -> T): T = value ?: producer()
fun orElseNullable(other: T?): T? = value ?: other
fun orElseGetNullable(producer: () -> T?): T? = value ?: producer()
fun <E: Throwable> orElseThrow(producer: () -> E): T = value ?: throw producer()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Optional<*>
return value == other.value
}
override fun hashCode(): Int {
return value?.hashCode() ?: 0
}
override fun toString(): String {
return "Optional(value=$value)"
}
} | apache-2.0 | 2d3425349d424f28948fa4c711fb8c6a | 22.264151 | 84 | 0.590097 | 3.826087 | false | false | false | false |
redutan/nbase-arc-monitoring | src/test/kotlin/io/redutan/nbasearc/monitoring/collector/FileLatencyLogPublisher.kt | 1 | 1696 | package io.redutan.nbasearc.monitoring.collector
import io.reactivex.Observable
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
import java.util.stream.Stream
private const val FILE_NAME = "latency-each-1seconds.txt"
/**
*
* @author myeongju.jung
*/
class FileLatencyLogPublisher(private val parser: Parser<Latency>,
private val headerParser: HeaderParser)
: LogPublishable<Latency> {
override fun observe(): Observable<Latency> {
val lineStream = getFileLineStream()
return Observable.create<Latency> { e ->
var header = UNKNOWN_HEADER // header 초기화
var currentDateTime = header.current
lineStream.forEach {
try {
// header 인가?
if (headerParser.isHeader(it)) {
header = headerParser.parse(it)
currentDateTime = header.current
}
val log = parser.parse(currentDateTime, it)
// 알 수 없는 로그인가?
if (log.isUnknown()) {
return@forEach
}
e.onNext(log) // 방출
currentDateTime = currentDateTime.plusSeconds(1)
TimeUnit.SECONDS.sleep(1)
} catch (t: Throwable) {
e.onError(t)
}
}
e.onComplete() // 방출종료
}
}
private fun getFileLineStream(): Stream<String> {
return Files.lines(Paths.get(this.javaClass.getResource(FILE_NAME).path))
}
}
| apache-2.0 | c45212d0a72db1f39631b8e1922fb9ba | 32.16 | 81 | 0.537394 | 4.409574 | false | false | false | false |
Saketme/JRAW | lib/src/test/kotlin/net/dean/jraw/test/unit/DeferredPersistentStoreTest.kt | 2 | 6837 | package net.dean.jraw.test.unit
import com.winterbe.expekt.should
import net.dean.jraw.filterValuesNotNull
import net.dean.jraw.models.OAuthData
import net.dean.jraw.models.PersistedAuthData
import net.dean.jraw.oauth.AuthManager
import net.dean.jraw.oauth.DeferredPersistentTokenStore
import net.dean.jraw.test.createMockOAuthData
import net.dean.jraw.test.expectException
import net.dean.jraw.test.withExpiration
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import java.util.*
class DeferredPersistentStoreTest : Spek({
// Sample data
val oauthData = createMockOAuthData()
val refreshToken = "<refresh token>"
val username = "username"
val data = mapOf(username to PersistedAuthData.create(oauthData, refreshToken))
// Constructor shortcut
fun newStore(initialData: Map<String, PersistedAuthData> = mapOf()) = MockDeferredPersistentTokenStore(initialData)
describe("load") {
it("should make the persisted data available") {
val store = newStore()
store._persisted = data.toMutableMap()
store.load()
store.fetchLatest(username).should.equal(oauthData)
store.fetchRefreshToken(username).should.equal(refreshToken)
}
it("shouldn't load insignificant data") {
val store = newStore()
val expiredOAuthData = OAuthData.create(
// Access token, scope, and refresh token are irrelevant
"<access_token>",
listOf("scope1", "scope2"),
null,
// Make the expiration 1 ms in the past
Date(Date().time - 1)
)
// Make sure our logic is correct: a PersistedAuthData with (1) either no OAuthData or one that is expired
// and (2) no refresh token makes this auth data insignificant.
val insignificantAuthData = PersistedAuthData.create(expiredOAuthData, null)
insignificantAuthData.isSignificant.should.be.`false`
store._persisted = mutableMapOf(username to insignificantAuthData)
// load() shouldn't load any insignificant entries
store.load()
store.size().should.equal(0)
}
}
describe("persist") {
it("should save the data") {
val store = newStore(data)
store._persisted.should.be.empty
store.persist()
store._persisted.should.not.be.empty
store._persisted.should.equal(data)
store.hasUnsaved().should.be.`false`
}
it("shouldn't save usernames with expired data by default") {
val insignificantData = mapOf(username to PersistedAuthData.create(oauthData.withExpiration(Date(0L)), null))
insignificantData[username]!!.isSignificant.should.be.`false`
val store = newStore(insignificantData)
store.persist()
store._persisted.should.be.empty
}
it("should persist expired data as null") {
val store = newStore(mapOf(username to PersistedAuthData.create(oauthData.withExpiration(Date(0L)), refreshToken)))
store.persist()
store._persisted[username]!!.should.equal(PersistedAuthData.create(null, refreshToken))
}
}
describe("hasUnsaved") {
it("should change based on whether there are unsaved changes") {
val store = newStore(data)
store.persist()
val name = store.usernames[0]
val prev = store.fetchRefreshToken(name)!!
store.storeRefreshToken(name, prev.repeat(2))
store.hasUnsaved().should.be.`true`
store.storeRefreshToken(name, prev)
store.hasUnsaved().should.be.`false`
}
}
describe("autoPersist") {
it("should persist changes immediately after storing data") {
val store = newStore()
store.autoPersist = true
store._persisted[username]?.refreshToken.should.be.`null`
store.storeRefreshToken(username, "foo")
store._persisted[username]?.refreshToken.should.equal("foo")
}
it("should persist changes immediately after deleting data") {
val store = newStore(data)
store.autoPersist = true
store.persist()
// Make sure deleteLatest persists
store.deleteLatest(username)
store._persisted[username].should.equal(PersistedAuthData.create(null, refreshToken))
// Make sure deleteRefreshToken persists
store.deleteRefreshToken(username)
store._persisted[username].should.be.`null`
}
}
describe("inspect") {
it("shouldn't keep empty auth data references") {
val store = newStore()
store.inspect(username).should.be.`null`
store.storeRefreshToken(username, "foo")
store.inspect(username).should.equal(PersistedAuthData.create(null, "foo"))
store.deleteRefreshToken(username)
store.inspect(username).should.be.`null`
}
}
describe("usernames") {
it("shouldn't include usernames that once had data but now don't") {
val store = newStore()
store.storeRefreshToken(username, "foo")
store.usernames.should.equal(listOf(username))
store.deleteRefreshToken(username)
store.usernames.should.be.empty
}
}
describe("clear") {
it("should remove all in-memory data") {
val store = newStore(initialData = mapOf("foo" to PersistedAuthData.create(createMockOAuthData(), null)))
store.data().should.have.size(1)
store.clear()
store.data().should.have.size(0)
}
}
describe("storeLatest/storeRefreshToken") {
it("should not accept data for a username of USERNAME_USERLESS") {
val store = newStore()
expectException(IllegalArgumentException::class) {
store.storeRefreshToken(AuthManager.USERNAME_UNKOWN, "")
}
expectException(IllegalArgumentException::class) {
store.storeLatest(AuthManager.USERNAME_UNKOWN, createMockOAuthData())
}
}
}
})
class MockDeferredPersistentTokenStore(initialData: Map<String, PersistedAuthData>) :
DeferredPersistentTokenStore(initialData) {
var _persisted: MutableMap<String, PersistedAuthData> = HashMap()
override fun doPersist(data: Map<String, PersistedAuthData>) {
this._persisted = data.toMutableMap()
}
override fun doLoad(): Map<String, PersistedAuthData> {
return this._persisted.filterValuesNotNull().toMutableMap()
}
}
| mit | 249deb4ab21b46ccc3625ccb016843b1 | 34.795812 | 127 | 0.631417 | 4.777778 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/core/overrideImplement/KtGenerateMembersHandler.kt | 3 | 15679 | // 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.core.overrideImplement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.idea.core.insertMembersAfter
import org.jetbrains.kotlin.idea.core.moveCaretIntoGeneratedElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.components.KtDeclarationRendererOptions
import org.jetbrains.kotlin.analysis.api.components.KtTypeRendererOptions
import org.jetbrains.kotlin.analysis.api.components.RendererModifier
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.idea.core.insertMembersAfter
import org.jetbrains.kotlin.idea.core.moveCaretIntoGeneratedElement
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtClassBody
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.prevSiblingOfSameType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
internal abstract class KtGenerateMembersHandler(
final override val toImplement: Boolean
) : AbstractGenerateMembersHandler<KtClassMember>() {
@OptIn(KtAllowAnalysisOnEdt::class)
override fun generateMembers(
editor: Editor,
classOrObject: KtClassOrObject,
selectedElements: Collection<KtClassMember>,
copyDoc: Boolean
) {
// Using allowAnalysisOnEdt here because we don't want to pre-populate all possible textual overrides before user selection.
val (commands, insertedBlocks) = allowAnalysisOnEdt {
val entryMembers = analyze(classOrObject) {
this.generateMembers(editor, classOrObject, selectedElements, copyDoc)
}
val insertedBlocks = insertMembersAccordingToPreferredOrder(entryMembers, editor, classOrObject)
// Reference shortening is done in a separate analysis session because the session need to be aware of the newly generated
// members.
val commands = analyze(classOrObject) {
insertedBlocks.mapNotNull { block ->
val declarations = block.declarations.mapNotNull { it.element }
val first = declarations.firstOrNull() ?: return@mapNotNull null
val last = declarations.last()
collectPossibleReferenceShortenings(first.containingKtFile, TextRange(first.startOffset, last.endOffset))
}
}
commands to insertedBlocks
}
runWriteAction {
commands.forEach { it.invokeShortening() }
val project = classOrObject.project
val codeStyleManager = CodeStyleManager.getInstance(project)
insertedBlocks.forEach { block ->
block.declarations.forEach { declaration ->
declaration.element?.let { element ->
codeStyleManager.reformat(
element
)
}
}
}
insertedBlocks.firstOrNull()?.declarations?.firstNotNullOfOrNull { it.element }?.let {
moveCaretIntoGeneratedElement(editor, it)
}
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.generateMembers(
editor: Editor,
currentClass: KtClassOrObject,
selectedElements: Collection<KtClassMember>,
copyDoc: Boolean
): List<MemberEntry> {
if (selectedElements.isEmpty()) return emptyList()
val selectedMemberSymbolsAndGeneratedPsi: Map<KtCallableSymbol, KtCallableDeclaration> = selectedElements.associate {
it.symbol to generateMember(currentClass.project, it, currentClass, copyDoc)
}
val classBody = currentClass.body
val offset = editor.caretModel.offset
// Insert members at the cursor position if the cursor is within the class body. Or, if there is no body, generate the body and put
// stuff in it.
if (classBody == null || isCursorInsideClassBodyExcludingBraces(classBody, offset)) {
return selectedMemberSymbolsAndGeneratedPsi.values.map { MemberEntry.NewEntry(it) }
}
// Insert members at positions such that the result aligns with ordering of members in super types.
return getMembersOrderedByRelativePositionsInSuperTypes(currentClass, selectedMemberSymbolsAndGeneratedPsi)
}
private fun isCursorInsideClassBodyExcludingBraces(classBody: KtClassBody, offset: Int): Boolean {
return classBody.textRange.contains(offset)
&& classBody.lBrace?.textRange?.contains(offset) == false
&& classBody.rBrace?.textRange?.contains(offset) == false
}
/**
* Given a class and some stub implementation of overridden members, output all the callable members in the desired order. For example,
* consider the following code
*
* ```
* interface Super {
* fun a()
* fun b()
* fun c()
* }
*
* class Sub: Super {
* override fun b() {}
* }
* ```
*
* Now this method is invoked with `Sub` as [currentClass] and `Super.a` and `Super.c` as [newMemberSymbolsAndGeneratedPsi]. This
* method outputs `[NewEntry(Sub.a), ExistingEntry(Sub.b), NewEntry(Sub.c)]`.
*
* How does this work?
*
* Initially we put all existing members in [currentClass] into a doubly linked list in the order they appear in the source code. Then,
* for each new member, the algorithm finds a target node nearby which this new member should be inserted. If the algorithm fails to
* find a desired target node, then the new member is inserted at the end.
*
* With the above code as an example, initially the doubly linked list contains `[ExistingEntry(Sub.b)]`. Then for `a`, the algorithm
* somehow (explained below) finds `ExistingEntry(Sub.b)` as the target node before which the new member `a` should be inserted. So now
* the doubly linked list contains `[NewEntry(Sub.a), ExistingEntry(Sub.b)]`. Similar steps are done for `c`.
*
* How does the algorithm find the target node and how does it decide whether to insert the new member before or after the target node?
*
* Throughout the algorithm, we maintain a map that tracks super member declarations for each member in the doubly linked list. For
* example, initially, the map contains `{ Super.b -> ExistingEntry(Sub.b) }`
*
* Given a new member, the algorithm first finds the PSI that declares this member in the super class. Then it traverses all the
* sibling members before this PSI element. With the above example, there is nothing before `Super.a`. Next it traverses all the
* sibling members after this PSI element. With the above example, it finds `Super.b`, which exists in the map. So the algorithm now
* knows `Sub.a` should be inserted before `Sub.b`.
*
* @param currentClass the class where the generated member code will be placed in
* @param newMemberSymbolsAndGeneratedPsi the generated members to insert into the class. For each entry in the map, the key is a
* callable symbol for an overridable member that the user has picked to override (or implement), and the value is the stub
* implementation for the chosen symbol.
*/
private fun KtAnalysisSession.getMembersOrderedByRelativePositionsInSuperTypes(
currentClass: KtClassOrObject,
newMemberSymbolsAndGeneratedPsi: Map<KtCallableSymbol, KtCallableDeclaration>
): List<MemberEntry> {
// This doubly linked list tracks the preferred ordering of members.
val sentinelHeadNode = DoublyLinkedNode<MemberEntry>()
val sentinelTailNode = DoublyLinkedNode<MemberEntry>()
sentinelHeadNode.append(sentinelTailNode)
// Traverse existing members in the current class and populate
// - a doubly linked list tracking the order
// - a map that tracks a member (as a doubly linked list node) in the current class and its overridden members in super classes (as
// a PSI element). This map is to allow fast look up from a super PSI element to a member entry in the current class
val existingDeclarations = currentClass.declarations.filterIsInstance<KtCallableDeclaration>()
val superPsiToMemberEntry = mutableMapOf<PsiElement, DoublyLinkedNode<MemberEntry>>().apply {
for (existingDeclaration in existingDeclarations) {
val node: DoublyLinkedNode<MemberEntry> = DoublyLinkedNode(MemberEntry.ExistingEntry(existingDeclaration))
sentinelTailNode.prepend(node)
val callableSymbol = existingDeclaration.getSymbol() as? KtCallableSymbol ?: continue
for (overriddenSymbol in callableSymbol.getAllOverriddenSymbols()) {
put(overriddenSymbol.psi ?: continue, node)
}
}
}
// Note on implementation: here we need the original ordering defined in the source code, so we stick to PSI rather than using
// `KtMemberScope` because the latter does not guarantee members are traversed in the original order. For example the
// FIR implementation groups overloaded functions together.
outer@ for ((selectedSymbol, generatedPsi) in newMemberSymbolsAndGeneratedPsi) {
val superSymbol = selectedSymbol.originalOverriddenSymbol
val superPsi = superSymbol?.psi
if (superPsi == null) {
// This normally should not happen, but we just try to play safe here.
sentinelTailNode.prepend(DoublyLinkedNode(MemberEntry.NewEntry(generatedPsi)))
continue
}
var currentPsi = superSymbol.psi?.prevSibling
while (currentPsi != null) {
val matchedNode = superPsiToMemberEntry[currentPsi]
if (matchedNode != null) {
val newNode = DoublyLinkedNode<MemberEntry>(MemberEntry.NewEntry(generatedPsi))
matchedNode.append(newNode)
superPsiToMemberEntry[superPsi] = newNode
continue@outer
}
currentPsi = currentPsi.prevSibling
}
currentPsi = superSymbol.psi?.nextSibling
while (currentPsi != null) {
val matchedNode = superPsiToMemberEntry[currentPsi]
if (matchedNode != null) {
val newNode = DoublyLinkedNode<MemberEntry>(MemberEntry.NewEntry(generatedPsi))
matchedNode.prepend(newNode)
superPsiToMemberEntry[superPsi] = newNode
continue@outer
}
currentPsi = currentPsi.nextSibling
}
val newNode = DoublyLinkedNode<MemberEntry>(MemberEntry.NewEntry(generatedPsi))
superPsiToMemberEntry[superPsi] = newNode
sentinelTailNode.prepend(newNode)
}
return sentinelHeadNode.toListSkippingNulls()
}
@OptIn(ExperimentalStdlibApi::class)
private fun insertMembersAccordingToPreferredOrder(
symbolsInPreferredOrder: List<MemberEntry>,
editor: Editor,
currentClass: KtClassOrObject
): List<InsertedBlock> {
if (symbolsInPreferredOrder.isEmpty()) return emptyList()
var firstAnchor: PsiElement? = null
if (symbolsInPreferredOrder.first() is MemberEntry.NewEntry) {
val firstExistingEntry = symbolsInPreferredOrder.firstIsInstanceOrNull<MemberEntry.ExistingEntry>()
if (firstExistingEntry != null) {
firstAnchor = firstExistingEntry.psi.prevSiblingOfSameType() ?: currentClass.body?.lBrace
}
}
val insertionBlocks = mutableListOf<InsertionBlock>()
var currentAnchor = firstAnchor
val currentBatch = mutableListOf<KtCallableDeclaration>()
fun updateBatch() {
if (currentBatch.isNotEmpty()) {
insertionBlocks += InsertionBlock(currentBatch.toList(), currentAnchor)
currentBatch.clear()
}
}
for (entry in symbolsInPreferredOrder) {
when (entry) {
is MemberEntry.ExistingEntry -> {
updateBatch()
currentAnchor = entry.psi
}
is MemberEntry.NewEntry -> {
currentBatch += entry.psi
}
}
}
updateBatch()
return runWriteAction {
insertionBlocks.map { (newDeclarations, anchor) ->
InsertedBlock(insertMembersAfter(editor, currentClass, newDeclarations, anchor = anchor))
}
}
}
private class DoublyLinkedNode<T>(val t: T? = null) {
private var prev: DoublyLinkedNode<T>? = null
private var next: DoublyLinkedNode<T>? = null
fun append(node: DoublyLinkedNode<T>) {
val next = this.next
this.next = node
node.prev = this
node.next = next
next?.prev = node
}
fun prepend(node: DoublyLinkedNode<T>) {
val prev = this.prev
this.prev = node
node.next = this
node.prev = prev
prev?.next = node
}
@OptIn(ExperimentalStdlibApi::class)
fun toListSkippingNulls(): List<T> {
var current: DoublyLinkedNode<T>? = this
return buildList {
while (current != null) {
current?.let {
if (it.t != null) add(it.t)
current = it.next
}
}
}
}
}
private sealed class MemberEntry {
data class ExistingEntry(val psi: KtCallableDeclaration) : MemberEntry()
data class NewEntry(val psi: KtCallableDeclaration) : MemberEntry()
}
companion object {
val renderOption = KtDeclarationRendererOptions(
modifiers = setOf(RendererModifier.OVERRIDE, RendererModifier.ANNOTATIONS),
renderDeclarationHeader = false,
renderUnitReturnType = true,
typeRendererOptions = KtTypeRendererOptions(
shortQualifiedNames = true,
renderFunctionType = true,
renderUnresolvedTypeAsResolved = true,
)
)
}
/** A block of code (represented as a list of Kotlin declarations) that should be inserted at a given anchor. */
private data class InsertionBlock(val declarations: List<KtDeclaration>, val anchor: PsiElement?)
/** A block of generated code. The code is represented as a list of Kotlin declarations that are defined one after another. */
private data class InsertedBlock(val declarations: List<SmartPsiElementPointer<KtDeclaration>>)
} | apache-2.0 | 352251952caea31612df0b7068e538d7 | 47.695652 | 139 | 0.661713 | 5.546162 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/concurrent/DefaultAsyncIOScopeFactoryTest.kt | 1 | 3135 | /*
* Copyright 2018 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.gradle.kotlin.dsl.concurrent
import org.awaitility.Duration.ONE_SECOND
import org.awaitility.kotlin.atMost
import org.awaitility.kotlin.await
import org.awaitility.kotlin.untilNotNull
import org.gradle.kotlin.dsl.support.useToRun
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.sameInstance
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import java.io.IOException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class DefaultAsyncIOScopeFactoryTest {
@Test
fun `#io failure is reported upon IOScope#close`() {
withAsyncIOScopeFactory {
val failure = IOException()
val scope = newScope().apply {
io { throw failure }
}
assertThat(
exceptionOrNullFrom { scope.close() },
sameInstance<Throwable>(failure)
)
}
}
@Test
fun `#io failure is reported upon next #io call`() {
withAsyncIOScopeFactory {
val expectedFailure = IOException()
val scope = newScope().apply {
io { throw expectedFailure }
}
assertThat(
awaitExceptionFrom(scope),
sameInstance<Throwable>(expectedFailure)
)
}
}
@Test
fun `IOScope failures are isolated`() {
withAsyncIOScopeFactory {
// given: a failure in one scope
val failedScope = newScope().apply {
io { throw IllegalStateException() }
}
awaitExceptionFrom(failedScope)
// then: actions can still be scheduled in separate scope
val isolatedScopeAction = CompletableFuture<Unit>()
newScope().apply {
io { isolatedScopeAction.complete(Unit) }
}
assertThat(
isolatedScopeAction.get(1, TimeUnit.SECONDS),
equalTo(Unit)
)
}
}
private
fun awaitExceptionFrom(scope: IOScope) =
await atMost ONE_SECOND untilNotNull { exceptionOrNullFrom { scope.io { } } }
private
fun exceptionOrNullFrom(action: () -> Unit) = runCatching(action).exceptionOrNull()
private
fun withAsyncIOScopeFactory(action: DefaultAsyncIOScopeFactory.() -> Unit) {
DefaultAsyncIOScopeFactory { Executors.newSingleThreadExecutor() }.useToRun(action)
}
}
| apache-2.0 | 2f590603ea7a6bd26c9d0a9483233cec | 27.243243 | 91 | 0.644338 | 4.73565 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/card/classic/ClassicReader.kt | 1 | 8460 | /*
* ClassicReader.kt
*
* Copyright 2012-2015 Eric Butler <[email protected]>
* Copyright 2012 Wilbert Duijvenvoorde <[email protected]>
* Copyright 2015-2018 Michael Farrell <[email protected]>
* Copyright 2019 Google
*
* 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 au.id.micolous.metrodroid.card.classic
import au.id.micolous.metrodroid.card.CardLostException
import au.id.micolous.metrodroid.card.CardTransceiveException
import au.id.micolous.metrodroid.card.CardTransceiver
import au.id.micolous.metrodroid.card.TagReaderFeedbackInterface
import au.id.micolous.metrodroid.key.CardKeysRetriever
import au.id.micolous.metrodroid.key.ClassicSectorKey
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.util.ImmutableByteArray
object ClassicReader {
private suspend fun readSectorWithKey(tech: ClassicCardTech, sectorIndex: Int,
correctKey: ClassicSectorKey,
extraKey: ClassicSectorKey? = null): ClassicSectorRaw {
val blocks = mutableListOf<ImmutableByteArray>()
// FIXME: First read trailer block to get type of other blocks.
val firstBlockIndex = tech.sectorToBlock(sectorIndex)
for (blockIndex in 0 until tech.getBlockCountInSector(sectorIndex)) {
var data = tech.readBlock(firstBlockIndex + blockIndex)
// Sometimes the result is just a single byte 04
// Reauthenticate if that happens
repeat(3) {
if (data.size == 1) {
tech.authenticate(sectorIndex, correctKey)
data = tech.readBlock(firstBlockIndex + blockIndex)
}
}
blocks.add(data)
}
if (correctKey.type == ClassicSectorKey.KeyType.B)
return ClassicSectorRaw(blocks = blocks, keyA = extraKey?.key, keyB = correctKey.key)
return ClassicSectorRaw(blocks = blocks, keyA = correctKey.key, keyB = extraKey?.key)
}
private const val TAG = "ClassicReader"
private fun earlyCheck(subType: ClassicCard.SubType,
sectors: List<ClassicSector>,
feedbackInterface: TagReaderFeedbackInterface): ClassicCardTransitFactory? {
val secnum = sectors.size
val factories = when (subType) {
ClassicCard.SubType.CLASSIC -> ClassicCardFactoryRegistry.classicFactories
ClassicCard.SubType.PLUS -> ClassicCardFactoryRegistry.plusFactories
}
factories.filter { factory -> factory.earlySectors == secnum }
.forEach lambda@{ factory ->
val ci = try {
if (!factory.earlyCheck(sectors))
return@lambda
factory.earlyCardInfo(sectors) ?: return@lambda
} catch (e: Exception) {
return@lambda
}
feedbackInterface.showCardType(ci)
feedbackInterface.updateStatusText(Localizer.localizeString(R.string.card_reading_type, ci.name))
return factory
}
return null
}
suspend fun readCard(retriever: CardKeysRetriever, tech: ClassicCardTech,
feedbackInterface: TagReaderFeedbackInterface): ClassicCard {
val sectorCount = tech.sectorCount
val sectors = mutableListOf<ClassicSector>()
val maxProgress = sectorCount * 5
var cardType: ClassicCardTransitFactory? = null
val tagId = tech.tagId
val auth = ClassicAuthenticator.makeAuthenticator(tagId = tagId, maxProgress = maxProgress,
retriever = retriever)
for (sectorIndex in 0 until sectorCount) {
try {
val correctKey = auth.authenticate(
tech, feedbackInterface,
sectorIndex, cardType?.isDynamicKeys(sectors, sectorIndex,
ClassicSectorKey.KeyType.UNKNOWN) ?: false,
ClassicSectorKey.KeyType.UNKNOWN)
feedbackInterface.updateProgressBar(sectorIndex * 5 + 3, maxProgress)
// Fallback if no key is found
if (correctKey == null) {
sectors.add(UnauthorizedClassicSector())
continue
}
feedbackInterface.updateStatusText(Localizer.localizeString(R.string.mfc_reading_blocks, sectorIndex))
var sector = ClassicSector.create(ClassicReader.readSectorWithKey(tech, sectorIndex, correctKey))
// If we used keyA and it wasn't enough try finding B
if (sector.keyA?.type == ClassicSectorKey.KeyType.A
&& sector.blocks.any { it.isUnauthorized }) {
val correctKeyB = auth.authenticate(
tech, feedbackInterface,
sectorIndex, cardType?.isDynamicKeys(sectors, sectorIndex,
ClassicSectorKey.KeyType.B) ?: false,
ClassicSectorKey.KeyType.B)
if (correctKeyB != null)
sector = ClassicSector.create(ClassicReader.readSectorWithKey(tech, sectorIndex, correctKeyB, extraKey = correctKey))
// In cases of readable keyB, tag shouldn't succeed auth at all
// yet some clones succeed auth but then fail to read any blocks.
} else if (sector.keyB?.type == ClassicSectorKey.KeyType.B
&& sector.blocks.all { it.isUnauthorized }) {
val correctKeyA = auth.authenticate(
tech, feedbackInterface,
sectorIndex, cardType?.isDynamicKeys(sectors, sectorIndex,
ClassicSectorKey.KeyType.A) ?: false,
ClassicSectorKey.KeyType.A)
if (correctKeyA != null)
sector = ClassicSector.create(ClassicReader.readSectorWithKey(tech, sectorIndex, correctKeyA, extraKey = correctKey))
}
sectors.add(sector)
if (cardType == null)
cardType = earlyCheck(tech.subType, sectors, feedbackInterface)
feedbackInterface.updateProgressBar(sectorIndex * 5 + 4, maxProgress)
} catch (ex: CardLostException) {
Log.w(TAG, "tag lost!", ex)
sectors.add(InvalidClassicSector(ex.message))
return ClassicCard(sectorsRaw = sectors.map { it.raw }, isPartialRead = true, subType = tech.subType)
} catch (ex: CardTransceiveException) {
sectors.add(InvalidClassicSector(ex.message))
}
}
return ClassicCard(sectorsRaw = sectors.map { it.raw }, isPartialRead = false, subType = tech.subType)
}
suspend fun readPlusCardNoSak(retriever: CardKeysRetriever, tag: CardTransceiver,
feedbackInterface: TagReaderFeedbackInterface): ClassicCard? {
val protocol = PlusProtocol.connect(tag) ?: return null
return readCard(retriever, protocol, feedbackInterface)
}
suspend fun readPlusCard(retriever: CardKeysRetriever, tag: CardTransceiver,
feedbackInterface: TagReaderFeedbackInterface,
atqa: Int, sak: Short): ClassicCard? {
// MIFARE Type Identification Procedure
// ref: https://www.nxp.com/docs/en/application-note/AN10833.pdf
if (sak != 0x20.toShort() || atqa !in listOf(0x0002, 0x0004, 0x0042, 0x0044))
return null
return readPlusCardNoSak(retriever, tag, feedbackInterface)
}
}
| gpl-3.0 | 853a5dad356fec2b3937820b9b1e56e4 | 47.342857 | 141 | 0.621277 | 4.895833 | false | false | false | false |
markusressel/TutorialTooltip | library/src/main/java/de/markusressel/android/library/tutorialtooltip/view/CardMessageView.kt | 1 | 5154 | /*
* Copyright (c) 2016 Markus Ressel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.markusressel.android.library.tutorialtooltip.view
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import de.markusressel.android.library.tutorialtooltip.interfaces.TutorialTooltipMessage
import kotlin.math.roundToInt
/**
* Basic Message view implementation
*
* Created by Markus on 24.11.2016.
*/
class CardMessageView : FrameLayout, TutorialTooltipMessage {
private var backgroundColor = Color.parseColor("#FFFFFFFF")
var borderColor = Color.parseColor("#FFFFFFFF")
/**
* Set the card border color
*
* @param color color as int
*/
set(color) {
field = color
cardShape.setStroke(borderThickness, field)
invalidate()
}
var borderThickness = 3
/**
* Set the card border thickness
*
* @param thickness width in pixel
*/
set(thickness) {
field = thickness
cardShape.setStroke(field, borderColor)
invalidate()
}
var cornerRadius: Float = 0F
/**
* Set the card corner radius
*
* @param radius radius in pixel
*/
set(radius) {
field = radius
cardShape.cornerRadii = floatArrayOf(
field, field, field, field,
field, field, field, field
)
invalidate()
}
private var defaultPadding: Int = 0
private var linearLayout: LinearLayout
private var textView: TextView
private val cardShape: GradientDrawable = GradientDrawable()
@JvmOverloads
constructor(context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) {
linearLayout = LinearLayout(context, attrs, defStyleAttr)
textView = TextView(context, attrs, defStyleAttr)
init()
}
@TargetApi(21)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int,
defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
linearLayout = LinearLayout(context, attrs, defStyleAttr, defStyleRes)
textView = TextView(context, attrs, defStyleAttr, defStyleRes)
init()
}
private fun init() {
cornerRadius = ViewHelper.pxFromDp(context, 12f).roundToInt().toFloat()
defaultPadding = ViewHelper.pxFromDp(context, 8f).roundToInt()
textView.gravity = Gravity.CENTER
textView.setBackgroundColor(Color.argb(0, 0, 0, 0))
linearLayout.addView(textView)
addView(linearLayout)
cardShape.mutate()
cardShape.shape = GradientDrawable.RECTANGLE
cardShape.cornerRadii = floatArrayOf(cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius)
cardShape.setColor(backgroundColor)
cardShape.setStroke(borderThickness, borderColor)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
linearLayout.background = cardShape
} else {
linearLayout.setBackgroundDrawable(cardShape)
}
linearLayout.setPadding(defaultPadding, defaultPadding, defaultPadding, defaultPadding)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val elevation = ViewHelper.pxFromDp(context, 6f)
val padding = ViewHelper.pxFromDp(context, 6f).toInt()
linearLayout.elevation = elevation
linearLayout.clipToPadding = false
setPadding(padding, padding, padding, padding)
clipToPadding = false
}
}
override fun setText(text: CharSequence) {
textView.text = text
}
override fun setTextColor(@ColorInt color: Int) {
textView.setTextColor(color)
}
override fun setBackgroundColor(color: Int) {
this.backgroundColor = color
this.borderColor = color
cardShape.setColor(this.backgroundColor)
cardShape.setStroke(borderThickness, borderColor)
invalidate()
}
}
| apache-2.0 | 83f3a8b1d6daa5e5d398b3bfaf42ad71 | 29.678571 | 95 | 0.645518 | 4.984526 | false | false | false | false |
byu-oit/android-byu-suite-v2 | app/src/main/java/edu/byu/suite/features/cougarCash/controller/CougarCashMainActivity.kt | 2 | 7023 | package edu.byu.suite.features.cougarCash.controller
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import android.view.ViewGroup
import edu.byu.suite.R
import edu.byu.suite.features.cougarCash.model.BalanceWrapper
import edu.byu.suite.features.cougarCash.model.CardStatus
import edu.byu.suite.features.cougarCash.model.TransactionWrapper
import edu.byu.suite.features.cougarCash.service.CougarCashClient
import edu.byu.support.ByuClickListener
import edu.byu.support.ByuViewHolder
import edu.byu.support.activity.ByuRecyclerViewActivity
import edu.byu.support.adapter.LoadingAdapter
import edu.byu.support.adapter.LoadingAdapter.LoadInterface
import edu.byu.support.retrofit.ByuCallback
import edu.byu.support.retrofit.ByuError
import edu.byu.support.retrofit.ByuSuccessCallback
import edu.byu.support.utils.ViewUtils
import edu.byu.support.utils.orFalse
import kotlinx.android.synthetic.main.cougar_cash_activity_main.*
import kotlinx.android.synthetic.main.cougar_cash_list_item_transaction.view.*
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Response
import java.text.NumberFormat
class CougarCashMainActivity: ByuRecyclerViewActivity() {
companion object {
private const val MANAGE_ACCOUNT_URL = "https://sa.byu.edu/psp/ps/EMPLOYEE/HRMS/c/Y_MY_FINANCIAL_CENTER.Y_SIG_HOME_FL.GBL?Page=Y_SIG_HOME_FL&Action=U"
private const val CCD_SIGN_UP_URL = "https://sa.byu.edu/psp/ps/EMPLOYEE/HRMS/c/Y_MY_FINANCIAL_CENTER.Y_SIG_HOME_FL.GBL?Page=Y_SIG_DESCR_PG1_FL&Action=U"
}
private var pageNumber = 0
private val adapter = TransactionAdapter()
private var cardLost: Boolean = false
private lateinit var api: CougarCashClient.Api
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState, R.layout.cougar_cash_activity_main)
api = CougarCashClient().getApi(this)
setAdapter(adapter)
swipeRefreshLayout.setOnRefreshListener {
// pageNumber is set to 0 to reset the loading process
pageNumber = 0
// transactions are reloaded
loadTransactions()
}
// loadTransactions() is called in bind() of the LoadingViewHolder within the TransactionAdapter class
showProgressDialog()
loadTransactions()
loadCardStatus()
loadBalance()
lostCardButton.setOnClickListener { changeCardStatus() }
signUpButton.setOnClickListener { startChromeTabView(CCD_SIGN_UP_URL) }
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
// When another activity clears top and resumes this one, we reload everything
// pageNumber is set to 0 to reset the loading process
showProgressDialog()
pageNumber = 0
loadTransactions()
loadBalance()
loadCardStatus()
}
private fun loadBalance() {
enqueueCall(api.getBalance(), object: ByuSuccessCallback<BalanceWrapper>(this) {
override fun onSuccess(call: Call<BalanceWrapper>, response: Response<BalanceWrapper>) {
balanceText.text = NumberFormat.getCurrencyInstance().format(response.body()?.balance)
when {
response.body()?.canAddFunds.orFalse() -> {
addFundsButton.visibility = View.VISIBLE
addFundsButton.text = getString(R.string.add_funds_button_text)
addFundsButton.setOnClickListener { startActivity(Intent(this@CougarCashMainActivity, CougarCashPaymentAccountsActivity::class.java)) }
}
response.body()?.canManageAccount.orFalse() -> {
addFundsButton.visibility = View.VISIBLE
addFundsButton.text = getString(R.string.manage_account_button_text)
addFundsButton.setOnClickListener { startChromeTabView(MANAGE_ACCOUNT_URL) }
}
else -> addFundsButton.visibility = View.INVISIBLE
}
signUpButton.visibility = if (response.body()?.canAddCougarCashDirect.orFalse()) View.VISIBLE else View.GONE
onLoadFinished()
}
})
}
private fun loadCardStatus() {
lostCardButton.isEnabled = false
enqueueCall(api.getCardStatus(), object: ByuSuccessCallback<CardStatus>(this) {
override fun onSuccess(call: Call<CardStatus>, response: Response<CardStatus>) {
cardLost = response.body()?.cardLost.orFalse()
lostCardButton.text = if (cardLost) getString(R.string.card_found_button_text) else getString(R.string.lost_card_button_text)
onLoadFinished()
}
})
}
private fun loadTransactions() {
enqueueCall(api.getTransactions(pageNumber++), object: ByuCallback<TransactionWrapper>(this) {
override fun onSuccess(call: Call<TransactionWrapper>, response: Response<TransactionWrapper>) {
val body = response.body()
if (pageNumber == 1) {
adapter.setFirstPage(body?.transactions, body?.lastPage.orFalse())
onLoadFinished()
} else {
adapter.addPage(body?.transactions, body?.lastPage.orFalse())
}
}
override fun onFailure(call: Call<TransactionWrapper>, byuError: ByuError) {
dismissProgressDialog()
if (pageNumber == 1) {
showErrorDialog(byuError.readableMessage)
} else {
showErrorDialog(byuError.readableMessage, null)
adapter.stopLoading()
}
}
})
}
private fun changeCardStatus() {
showProgressDialog(false)
enqueueCall(if (cardLost) api.reportCardFound() else api.reportCardLost(), object: ByuSuccessCallback<ResponseBody>(this) {
override fun onSuccess(call: Call<ResponseBody>, response: Response<ResponseBody>) {
loadCardStatus()
loadBalance()
AlertDialog.Builder(this@CougarCashMainActivity)
.setTitle(R.string.success)
.setMessage(if (cardLost) getString(R.string.cougar_cash_found_card_message) else getString(R.string.cougar_cash_lost_card_message))
.setPositiveButton(android.R.string.ok, null)
.show()
}
})
}
private fun onLoadFinished() {
if (areAllCallsCompleted()) {
dismissProgressDialog()
lostCardButton.isEnabled = true
swipeRefreshLayout.isRefreshing = false
}
}
override fun getEmptyDataText(): String = getString(R.string.no_transactions)
private inner class TransactionAdapter: LoadingAdapter<TransactionWrapper.Transaction>(LoadInterface { loadTransactions() }) {
override fun getViewHolder(parent: ViewGroup, viewType: Int) = TransactionViewHolder(ViewUtils.inflate(parent, R.layout.cougar_cash_list_item_transaction))
private inner class TransactionViewHolder(itemView: View): ByuViewHolder<TransactionWrapper.Transaction>(itemView) {
override fun bind(data: TransactionWrapper.Transaction, listener: ByuClickListener<TransactionWrapper.Transaction>?) {
itemView.transactionDescriptionText.text = data.transactionDescription
itemView.transactionDateText.text = data.getFormattedTransactionDate()
itemView.transactionTotalText.text = data.getFormattedTransactionAmount()
if (data.transactionAmount < 0) {
itemView.transactionTotalText.setTextColor(ContextCompat.getColor(this@CougarCashMainActivity, R.color.red))
} else {
itemView.transactionTotalText.setTextColor(ContextCompat.getColor(this@CougarCashMainActivity, R.color.green))
}
}
}
}
}
| apache-2.0 | f6a0b7c206562bfc96c3c851b5b66474 | 39.362069 | 157 | 0.769329 | 3.747599 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidWiki/src/main/kotlin/com/eden/orchid/wiki/model/WikiModel.kt | 2 | 1258 | package com.eden.orchid.wiki.model
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.generators.OrchidGenerator
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.wiki.pages.WikiSectionsPage
class WikiModel(
sectionsList: List<WikiSection>,
override val collections: List<OrchidCollection<*>>
) : OrchidGenerator.Model {
var sectionsPage: WikiSectionsPage? = null
var sections: Map<String, WikiSection> = linkedMapOf(*(sectionsList.map { it.key to it }.toTypedArray()))
override val allPages: List<OrchidPage>
get() {
val allPages = ArrayList<OrchidPage>()
for (value in sections.values) {
allPages.add(value.summaryPage)
allPages.addAll(value.wikiPages)
if (value.bookPage != null) {
allPages.add(value.bookPage!!)
}
}
if (sectionsPage != null) {
allPages.add(sectionsPage!!)
}
return allPages
}
fun getSection(sectionKey: String): WikiSection? {
if (sectionKey.isNotBlank()) {
return sections.getOrDefault(sectionKey, null)
}
return null
}
}
| mit | 17e555a7dfe75e3a1697939ffb7c87bf | 29.682927 | 109 | 0.620827 | 4.429577 | false | false | false | false |
izonder/intellij-community | plugins/settings-repository/src/IcsManager.kt | 2 | 10935 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.configurationStore.StateStorageManagerImpl
import com.intellij.configurationStore.StreamProvider
import com.intellij.ide.ApplicationLoadListener
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.impl.stores.StorageUtil
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectLifecycleListener
import com.intellij.openapi.util.AtomicNotNullLazyValue
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.SingleAlarm
import com.intellij.util.SystemProperties
import org.jetbrains.keychain.CredentialsStore
import org.jetbrains.keychain.FileCredentialsStore
import org.jetbrains.keychain.OsXCredentialsStore
import org.jetbrains.keychain.isOSXCredentialsStoreSupported
import org.jetbrains.settingsRepository.git.GitRepositoryManager
import org.jetbrains.settingsRepository.git.GitRepositoryService
import org.jetbrains.settingsRepository.git.processChildren
import java.io.File
import java.io.InputStream
import kotlin.properties.Delegates
val PLUGIN_NAME: String = "Settings Repository"
val LOG: Logger = Logger.getInstance(javaClass<IcsManager>())
val icsManager by Delegates.lazy {
ApplicationLoadListener.EP_NAME.findExtension(javaClass<IcsApplicationLoadListener>()).icsManager
}
class IcsManager(dir: File) {
val credentialsStore = object : AtomicNotNullLazyValue<CredentialsStore>() {
override fun compute(): CredentialsStore {
if (isOSXCredentialsStoreSupported && SystemProperties.getBooleanProperty("ics.use.osx.keychain", true)) {
try {
return OsXCredentialsStore("IntelliJ Platform Settings Repository")
}
catch (e: Throwable) {
LOG.error(e)
}
}
return FileCredentialsStore(File(dir, ".git_auth"))
}
}
val settingsFile = File(dir, "config.json")
val settings: IcsSettings
val repositoryManager: RepositoryManager = GitRepositoryManager(credentialsStore, File(dir, "repository"))
init {
try {
settings = loadSettings(settingsFile)
}
catch (e: Exception) {
settings = IcsSettings()
LOG.error(e)
}
}
val readOnlySourcesManager = ReadOnlySourcesManager(settings, dir)
val repositoryService: RepositoryService = GitRepositoryService()
private val commitAlarm = SingleAlarm(object : Runnable {
override fun run() {
ProgressManager.getInstance().run(object : Task.Backgroundable(null, IcsBundle.message("task.commit.title")) {
override fun run(indicator: ProgressIndicator) {
try {
repositoryManager.commit(indicator)
}
catch (e: Throwable) {
LOG.error(e)
}
}
})
}
}, settings.commitDelay)
private volatile var autoCommitEnabled = true
volatile var repositoryActive = false
val autoSyncManager = AutoSyncManager(this)
private val syncManager = SyncManager(this, autoSyncManager)
private fun scheduleCommit() {
if (autoCommitEnabled && !ApplicationManager.getApplication()!!.isUnitTestMode()) {
commitAlarm.cancelAndRequest()
}
}
inner class ApplicationLevelProvider : IcsStreamProvider(null) {
override fun delete(fileSpec: String, roamingType: RoamingType) {
if (syncManager.writeAndDeleteProhibited) {
throw IllegalStateException("Delete is prohibited now")
}
repositoryManager.delete(buildPath(fileSpec, roamingType))
scheduleCommit()
}
}
private fun registerProjectLevelProviders(project: Project) {
val storageManager = project.stateStore.getStateStorageManager()
val projectId = storageManager.getStateStorage(StoragePathMacros.WORKSPACE_FILE, RoamingType.DISABLED).getState(ProjectId(), "IcsProjectId", javaClass<ProjectId>())
if (projectId == null || projectId.uid == null) {
// not mapped, if user wants, he can map explicitly, we don't suggest
// we cannot suggest "map to ICS" for any project that user opens, it will be annoying
return
}
// storageManager.setStreamProvider(ProjectLevelProvider(projectId.uid!!))
// updateStoragesFromStreamProvider(storageManager, storageManager.getStorageFileNames())
}
private inner class ProjectLevelProvider(projectId: String) : IcsStreamProvider(projectId) {
override fun isAutoCommit(fileSpec: String, roamingType: RoamingType) = !StorageUtil.isProjectOrModuleFile(fileSpec)
override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean {
if (StorageUtil.isProjectOrModuleFile(fileSpec)) {
// applicable only if file was committed to Settings Server explicitly
return repositoryManager.has(buildPath(fileSpec, roamingType, this.projectId))
}
return settings.shareProjectWorkspace || fileSpec != StoragePathMacros.WORKSPACE_FILE
}
}
fun sync(syncType: SyncType, project: Project? = null, localRepositoryInitializer: (() -> Unit)? = null) = syncManager.sync(syncType, project, localRepositoryInitializer)
private fun cancelAndDisableAutoCommit() {
if (autoCommitEnabled) {
autoCommitEnabled = false
commitAlarm.cancel()
}
}
fun runInAutoCommitDisabledMode(task: ()->Unit) {
cancelAndDisableAutoCommit()
try {
task()
}
finally {
autoCommitEnabled = true
repositoryActive = repositoryManager.isRepositoryExists()
}
}
fun beforeApplicationLoaded(application: Application) {
repositoryActive = repositoryManager.isRepositoryExists()
(application.stateStore.getStateStorageManager() as StateStorageManagerImpl).streamProvider = ApplicationLevelProvider()
autoSyncManager.registerListeners(application)
application.getMessageBus().connect().subscribe(ProjectLifecycleListener.TOPIC, object : ProjectLifecycleListener.Adapter() {
override fun beforeProjectLoaded(project: Project) {
if (project.isDefault()) {
return
}
//registerProjectLevelProviders(project)
autoSyncManager.registerListeners(project)
}
override fun afterProjectClosed(project: Project) {
autoSyncManager.autoSync()
}
})
}
open inner class IcsStreamProvider(protected val projectId: String?) : StreamProvider {
override val enabled: Boolean
get() = repositoryActive
override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) {
val fullPath = buildPath(path, roamingType, null)
// first of all we must load read-only schemes - scheme could be overridden if bundled or read-only, so, such schemes must be loaded first
for (repository in readOnlySourcesManager.repositories) {
repository.processChildren(fullPath, filter, { name, input -> processor(name, input, true) })
}
repositoryManager.processChildren(fullPath, filter, { name, input -> processor(name, input, false) })
}
override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
if (syncManager.writeAndDeleteProhibited) {
throw IllegalStateException("Save is prohibited now")
}
if (doSave(fileSpec, content, size, roamingType) && isAutoCommit(fileSpec, roamingType)) {
scheduleCommit()
}
}
fun doSave(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) = repositoryManager.write(buildPath(fileSpec, roamingType, projectId), content, size)
protected open fun isAutoCommit(fileSpec: String, roamingType: RoamingType): Boolean = true
override fun read(fileSpec: String, roamingType: RoamingType): InputStream? {
return repositoryManager.read(buildPath(fileSpec, roamingType, projectId))
}
override fun delete(fileSpec: String, roamingType: RoamingType) {
}
}
}
class IcsApplicationLoadListener : ApplicationLoadListener {
var icsManager: IcsManager by Delegates.notNull()
private set
override fun beforeApplicationLoaded(application: Application, configPath: String) {
if (application.isUnitTestMode()) {
return
}
val customPath = System.getProperty("ics.settingsRepository")
val pluginSystemDir = if (customPath == null) File(configPath, "settingsRepository") else File(FileUtil.expandUserHome(customPath))
icsManager = IcsManager(pluginSystemDir)
if (!pluginSystemDir.exists()) {
try {
val oldPluginDir = File(PathManager.getSystemPath(), "settingsRepository")
if (oldPluginDir.exists()) {
FileUtil.rename(oldPluginDir, pluginSystemDir)
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
val repositoryManager = icsManager.repositoryManager
if (repositoryManager.isRepositoryExists() && repositoryManager is GitRepositoryManager) {
if (repositoryManager.renameDirectory(linkedMapOf(
Pair("\$ROOT_CONFIG$", null),
Pair("_mac/\$ROOT_CONFIG$", "_mac"),
Pair("_windows/\$ROOT_CONFIG$", "_windows"),
Pair("_linux/\$ROOT_CONFIG$", "_linux"),
Pair("_freebsd/\$ROOT_CONFIG$", "_freebsd"),
Pair("_unix/\$ROOT_CONFIG$", "_unix"),
Pair("_unknown/\$ROOT_CONFIG$", "_unknown"),
Pair("\$APP_CONFIG$", null),
Pair("_mac/\$APP_CONFIG$", "_mac"),
Pair("_windows/\$APP_CONFIG$", "_windows"),
Pair("_linux/\$APP_CONFIG$", "_linux"),
Pair("_freebsd/\$APP_CONFIG$", "_freebsd"),
Pair("_unix/\$APP_CONFIG$", "_unix"),
Pair("_unknown/\$APP_CONFIG$", "_unknown")
))) {
// schedule push to avoid merge conflicts
application.invokeLater(Runnable { icsManager.autoSyncManager.autoSync(force = true) })
}
}
icsManager.beforeApplicationLoaded(application)
}
} | apache-2.0 | 33c7ff419c044d0dd95f26d80c0aadc1 | 37.10453 | 186 | 0.723457 | 4.890429 | false | true | false | false |
Mystery00/JanYoShare | app/src/main/java/com/janyo/janyoshare/util/drawable/DrawableFactory.kt | 1 | 1472 | package com.janyo.janyoshare.util.drawable
import android.graphics.Bitmap
import android.graphics.drawable.AdaptiveIconDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import com.janyo.janyoshare.util.Settings
import com.janyo.janyoshare.util.bitmap.BitmapCropContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
/**
* Created by mystery0.
*/
class DrawableFactory(settings: Settings)
{
private val drawableConvertContext = DrawableConvertContext()
private val bitmapCropContext = BitmapCropContext()
init
{
when (settings.iconCropType)
{
1 -> bitmapCropContext.setCropType(BitmapCropContext.ROUND)
2 -> bitmapCropContext.setCropType(BitmapCropContext.RECTANGLE)
3 -> bitmapCropContext.setCropType(BitmapCropContext.ROUND_RECTANGLE)
else -> bitmapCropContext.setCropType(BitmapCropContext.DEFAULT)
}
}
fun save(drawable: Drawable, path: String): Boolean
{
try
{
val file = File(path)
if (!file.parentFile.exists())
{
file.parentFile.mkdirs()
}
val out = FileOutputStream(file)
var bitmap = drawableConvertContext.convert(drawable) ?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && drawable is AdaptiveIconDrawable)
{
bitmap = bitmapCropContext.crop(bitmap)
}
bitmap.compress(Bitmap.CompressFormat.PNG, 1, out)
out.close()
}
catch (e: IOException)
{
e.printStackTrace()
return false
}
return true
}
} | gpl-3.0 | 6fd5f429f50206f4d9893de33dd0f70c | 24.842105 | 90 | 0.755435 | 3.504762 | false | false | false | false |
carltonwhitehead/crispy-fish | library/src/main/kotlin/org/coner/crispyfish/datatype/underscorepairs/SimpleStringUnderscorePairReader.kt | 1 | 753 | package org.coner.crispyfish.datatype.underscorepairs
class SimpleStringUnderscorePairReader : UnderscorePairReader<String> {
override fun get(pairs: String, key: String): String? {
val keyStartPosition = pairs.indexOf(key)
if (keyStartPosition < 0) {
// pairs doesn't contain key
return null
}
val keyLength = key.length
val valueStartPosition = keyStartPosition + keyLength + 1 // +1 to account for the trailing _
val valueStopPosition = pairs.indexOf('_', valueStartPosition)
return if (valueStopPosition >= 0) {
pairs.substring(valueStartPosition, valueStopPosition)
} else {
pairs.substring(valueStartPosition)
}
}
}
| gpl-2.0 | 59a1e68b7e9c3ba120e4857fb319c907 | 34.857143 | 101 | 0.648074 | 4.765823 | false | false | false | false |
tginsberg/advent-2016-kotlin | src/main/kotlin/com/ginsberg/advent2016/Day20.kt | 1 | 1233 | /*
* Copyright (c) 2016 by Todd Ginsberg
*/
package com.ginsberg.advent2016
/**
* Advent of Code - Day 20: December 20, 2016
*
* From http://adventofcode.com/2016/day/20
*
*/
class Day20(val input: List<String>) {
val ipRanges = parseInput()
fun solvePart1(): Long =
ipRanges.first().last.inc()
fun solvePart2(upperBound: Long = 4294967295): Long =
upperBound.inc() - ipRanges.map { (it.last - it.first).inc() }.sum()
private fun parseInput(): List<LongRange> =
optimize(input
.map { it.split("-") }
.map { LongRange(it[0].toLong(), it[1].toLong()) }
.sortedBy { it.first }
)
private fun optimize(ranges: List<LongRange>): List<LongRange> =
ranges.drop(1).fold(ranges.take(1)) { carry, next ->
if (carry.last().combinesWith(next)) carry.dropLast(1).plusElement(carry.last().plus(next))
else carry.plusElement(next)
}
private fun LongRange.plus(other: LongRange): LongRange =
LongRange(Math.min(this.first, other.first), Math.max(this.last, other.last))
private fun LongRange.combinesWith(other: LongRange): Boolean =
other.first in this || this.last + 1 in other
}
| mit | 5f5c9b39a3909439047d122f8bc143e3 | 29.073171 | 103 | 0.61395 | 3.691617 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/persistence/query/QueryCriteriaOperator.kt | 1 | 1775 | package com.onyx.persistence.query
/**
* Set of defined Query Operators. Used when specifying a Query and QueryCriteria.
*
* @author Tim Osborn
* @since 1.0.0
*
* @see com.onyx.persistence.query.QueryCriteria
*/
enum class QueryCriteriaOperator {
EQUAL,
NOT_EQUAL,
NOT_STARTS_WITH,
NOT_NULL,
IS_NULL,
STARTS_WITH,
CONTAINS,
NOT_CONTAINS,
LIKE,
NOT_LIKE,
MATCHES,
NOT_MATCHES,
LESS_THAN,
GREATER_THAN,
LESS_THAN_EQUAL,
GREATER_THAN_EQUAL,
IN,
NOT_IN;
/**
* Indicates if the operator supports indexing capabilities
* @return If this operator supports index scanning
*/
val isIndexed: Boolean
get() = this === EQUAL
|| this === IN
|| this === GREATER_THAN
|| this === GREATER_THAN_EQUAL
|| this === LESS_THAN
|| this === LESS_THAN_EQUAL
/**
* Get the inverse in order to support the .not() feature within query criteria
*
* @since 2.0.0
*/
val inverse: QueryCriteriaOperator
get() = when(this) {
EQUAL -> NOT_EQUAL
NOT_EQUAL -> EQUAL
NOT_STARTS_WITH -> STARTS_WITH
NOT_NULL -> IS_NULL
IS_NULL -> NOT_NULL
STARTS_WITH -> NOT_STARTS_WITH
CONTAINS -> NOT_CONTAINS
NOT_CONTAINS -> CONTAINS
LIKE -> NOT_LIKE
NOT_LIKE -> LIKE
MATCHES -> NOT_MATCHES
NOT_MATCHES -> MATCHES
LESS_THAN -> GREATER_THAN_EQUAL
GREATER_THAN -> LESS_THAN_EQUAL
LESS_THAN_EQUAL -> GREATER_THAN
GREATER_THAN_EQUAL -> LESS_THAN
IN -> NOT_IN
NOT_IN -> IN
}
}
| agpl-3.0 | bea618d6f6b4416600ec2aa4ef1ef897 | 24.724638 | 83 | 0.531831 | 4.206161 | false | false | false | false |
yongce/AndroidLib | baseLib/src/main/java/me/ycdev/android/lib/common/utils/GcHelper.kt | 1 | 1399 | package me.ycdev.android.lib.common.utils
import me.ycdev.android.lib.common.type.BooleanHolder
import timber.log.Timber
@Suppress("unused")
object GcHelper {
private const val TAG = "GcHelper"
fun forceGc(gcState: BooleanHolder) {
// Now, 'objPartner' can be collected by GC!
val timeStart = System.currentTimeMillis()
// create a lot of objects to force GC
val memAllocSize = 1024 * 1024 // 1MB
var memAllocCount: Long = 0
while (true) {
Runtime.getRuntime().gc()
ThreadUtils.sleep(100) // wait for GC
if (gcState.value) {
break // GC happened
}
Timber.tag(TAG).d("Allocating mem...")
ByteArray(memAllocSize)
memAllocCount++
}
val timeUsed = System.currentTimeMillis() - timeStart
Timber.tag(TAG).d("Force GC, time used: %d, memAlloc: %dMB", timeUsed, memAllocCount)
}
fun forceGc() {
val gcState = BooleanHolder(false)
createGcWatcherObject(gcState)
forceGc(gcState)
}
private fun createGcWatcherObject(gcState: BooleanHolder) {
object : Any() {
@Throws(Throwable::class)
protected fun finalize() {
Timber.tag(TAG).d("GC Partner object was collected")
gcState.value = true
}
}
}
}
| apache-2.0 | cfcf513edb6967356af8b473c7b7cac4 | 28.765957 | 93 | 0.580415 | 4.226586 | false | false | false | false |
deniotokiari/shikimori-client | app/src/main/kotlin/by/deniotokiari/shikimoriclient/activity/LoginActivity.kt | 1 | 2687 | package by.deniotokiari.shikimoriclient.activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.EditText
import android.widget.Toast
import by.deniotokiari.shikimoriapi.ApiService
import by.deniotokiari.shikimoriapi.models.ApiAccessToken
import by.deniotokiari.shikimoriclient.App
import by.deniotokiari.shikimoriclient.Constants
import by.deniotokiari.shikimoriclient.ISharedPreferences
import by.deniotokiari.shikimoriclient.R
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
class LoginActivity : AppCompatActivity() {
@Inject
lateinit var api: ApiService
@Inject
lateinit var prefs: ISharedPreferences
private lateinit var progress: View
override fun onCreate(savedInstanceState: Bundle?) {
App.appComponent.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
progress = findViewById(android.R.id.progress)
val nickNameEditText = findViewById(R.id.nick_name) as EditText
val passwordEditText = findViewById(R.id.password) as EditText
fun isValid(): Boolean {
return nickNameEditText.text != null && passwordEditText.text != null && !nickNameEditText.text.isEmpty() && !passwordEditText.text.isEmpty()
}
findViewById(R.id.login).setOnClickListener {
if (isValid()) {
progress.visibility = View.VISIBLE
api.access_token(nickNameEditText.text.toString(), passwordEditText.text.toString()).enqueue(object : Callback<ApiAccessToken?> {
override fun onFailure(call: Call<ApiAccessToken?>?, t: Throwable?) {
progress.visibility = View.GONE
t?.message?.let {
Toast.makeText(this@LoginActivity, it, Toast.LENGTH_SHORT).show()
}
}
override fun onResponse(call: Call<ApiAccessToken?>?, response: Response<ApiAccessToken?>?) {
progress.visibility = View.GONE
response?.body()?.api_access_token?.let { token ->
prefs.put(Constants.Pref.USER_TOKEN, token)
startActivity(Intent(this@LoginActivity, MainActivity::class.java))
finish()
}
}
})
} else {
Toast.makeText(this, R.string.WRONG_CREDENTIALS, Toast.LENGTH_LONG).show()
}
}
}
} | apache-2.0 | 655913d1332bef0230d5f82d7e7cb54a | 33.909091 | 153 | 0.636025 | 4.957565 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-okhttp/jvm/src/io/ktor/client/engine/okhttp/OkUtils.kt | 1 | 2761 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.okhttp
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.*
import okhttp3.*
import java.io.*
import java.net.*
import kotlin.coroutines.*
import okhttp3.Headers as OkHttpHeaders
internal suspend fun OkHttpClient.execute(
request: Request,
requestData: HttpRequestData
): Response = suspendCancellableCoroutine { continuation ->
val call = newCall(request)
call.enqueue(OkHttpCallback(requestData, continuation))
continuation.invokeOnCancellation {
call.cancel()
}
}
private class OkHttpCallback(
private val requestData: HttpRequestData,
private val continuation: CancellableContinuation<Response>
) : Callback {
override fun onFailure(call: Call, e: IOException) {
if (continuation.isCancelled) {
return
}
continuation.resumeWithException(mapOkHttpException(requestData, e))
}
override fun onResponse(call: Call, response: Response) {
if (!call.isCanceled()) {
continuation.resume(response)
}
}
}
internal fun OkHttpHeaders.fromOkHttp(): Headers = object : Headers {
override val caseInsensitiveName: Boolean = true
override fun getAll(name: String): List<String>? = [email protected](name).takeIf { it.isNotEmpty() }
override fun names(): Set<String> = [email protected]()
override fun entries(): Set<Map.Entry<String, List<String>>> = [email protected]().entries
override fun isEmpty(): Boolean = [email protected] == 0
}
@Suppress("DEPRECATION")
internal fun Protocol.fromOkHttp(): HttpProtocolVersion = when (this) {
Protocol.HTTP_1_0 -> HttpProtocolVersion.HTTP_1_0
Protocol.HTTP_1_1 -> HttpProtocolVersion.HTTP_1_1
Protocol.SPDY_3 -> HttpProtocolVersion.SPDY_3
Protocol.HTTP_2 -> HttpProtocolVersion.HTTP_2_0
Protocol.H2_PRIOR_KNOWLEDGE -> HttpProtocolVersion.HTTP_2_0
Protocol.QUIC -> HttpProtocolVersion.QUIC
}
private fun mapOkHttpException(
requestData: HttpRequestData,
origin: IOException
): Throwable = when (val cause = origin.unwrapSuppressed()) {
is SocketTimeoutException ->
if (cause.isConnectException()) {
ConnectTimeoutException(requestData, cause)
} else {
SocketTimeoutException(requestData, cause)
}
else -> cause
}
private fun IOException.isConnectException() =
message?.contains("connect", ignoreCase = true) == true
private fun IOException.unwrapSuppressed(): Throwable {
if (suppressed.isNotEmpty()) return suppressed[0]
return this
}
| apache-2.0 | 16e2f2fe72970dc50dc84e2f2c4feaeb | 29.677778 | 119 | 0.710612 | 4.348031 | false | false | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Double/MutableDoubleVec3.kt | 1 | 29411 | package glm
data class MutableDoubleVec3(var x: Double, var y: Double, var z: Double) {
// Initializes each element by evaluating init from 0 until 2
constructor(init: (Int) -> Double) : this(init(0), init(1), init(2))
operator fun get(idx: Int): Double = when (idx) {
0 -> x
1 -> y
2 -> z
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
operator fun set(idx: Int, value: Double) = when (idx) {
0 -> x = value
1 -> y = value
2 -> z = value
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): MutableDoubleVec3 = MutableDoubleVec3(x.inc(), y.inc(), z.inc())
operator fun dec(): MutableDoubleVec3 = MutableDoubleVec3(x.dec(), y.dec(), z.dec())
operator fun unaryPlus(): MutableDoubleVec3 = MutableDoubleVec3(+x, +y, +z)
operator fun unaryMinus(): MutableDoubleVec3 = MutableDoubleVec3(-x, -y, -z)
operator fun plus(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(x + rhs.x, y + rhs.y, z + rhs.z)
operator fun minus(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(x - rhs.x, y - rhs.y, z - rhs.z)
operator fun times(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(x * rhs.x, y * rhs.y, z * rhs.z)
operator fun div(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(x / rhs.x, y / rhs.y, z / rhs.z)
operator fun rem(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(x % rhs.x, y % rhs.y, z % rhs.z)
operator fun plus(rhs: Double): MutableDoubleVec3 = MutableDoubleVec3(x + rhs, y + rhs, z + rhs)
operator fun minus(rhs: Double): MutableDoubleVec3 = MutableDoubleVec3(x - rhs, y - rhs, z - rhs)
operator fun times(rhs: Double): MutableDoubleVec3 = MutableDoubleVec3(x * rhs, y * rhs, z * rhs)
operator fun div(rhs: Double): MutableDoubleVec3 = MutableDoubleVec3(x / rhs, y / rhs, z / rhs)
operator fun rem(rhs: Double): MutableDoubleVec3 = MutableDoubleVec3(x % rhs, y % rhs, z % rhs)
inline fun map(func: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(func(x), func(y), func(z))
fun toList(): List<Double> = listOf(x, y, z)
// Predefined vector constants
companion object Constants {
val zero: MutableDoubleVec3 get() = MutableDoubleVec3(0.0, 0.0, 0.0)
val ones: MutableDoubleVec3 get() = MutableDoubleVec3(1.0, 1.0, 1.0)
val unitX: MutableDoubleVec3 get() = MutableDoubleVec3(1.0, 0.0, 0.0)
val unitY: MutableDoubleVec3 get() = MutableDoubleVec3(0.0, 1.0, 0.0)
val unitZ: MutableDoubleVec3 get() = MutableDoubleVec3(0.0, 0.0, 1.0)
}
// Conversions to Float
fun toVec(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec(conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Double) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec3(conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec4(w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w)
inline fun toVec4(w: Float = 0f, conv: (Double) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w)
// Conversions to Float
fun toMutableVec(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec(conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Double) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec3(conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec4(w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w)
inline fun toMutableVec4(w: Float = 0f, conv: (Double) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w)
// Conversions to Double
fun toDoubleVec(): DoubleVec3 = DoubleVec3(x, y, z)
inline fun toDoubleVec(conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x, y)
inline fun toDoubleVec2(conv: (Double) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x, y, z)
inline fun toDoubleVec3(conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec4(w: Double = 0.0): DoubleVec4 = DoubleVec4(x, y, z, w)
inline fun toDoubleVec4(w: Double = 0.0, conv: (Double) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w)
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec3 = MutableDoubleVec3(x, y, z)
inline fun toMutableDoubleVec(conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x, y)
inline fun toMutableDoubleVec2(conv: (Double) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x, y, z)
inline fun toMutableDoubleVec3(conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec4(w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x, y, z, w)
inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (Double) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w)
// Conversions to Int
fun toIntVec(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec(conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec2(conv: (Double) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec3(conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec4(w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w)
inline fun toIntVec4(w: Int = 0, conv: (Double) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w)
// Conversions to Int
fun toMutableIntVec(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec(conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec2(conv: (Double) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec3(conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec4(w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w)
inline fun toMutableIntVec4(w: Int = 0, conv: (Double) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w)
// Conversions to Long
fun toLongVec(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec(conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Double) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec3(conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec4(w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w)
inline fun toLongVec4(w: Long = 0L, conv: (Double) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w)
// Conversions to Long
fun toMutableLongVec(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec(conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Double) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec3(conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec4(w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w)
inline fun toMutableLongVec4(w: Long = 0L, conv: (Double) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w)
// Conversions to Short
fun toShortVec(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toShortVec(conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec2(conv: (Double) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toShortVec3(conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec4(w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w)
inline fun toShortVec4(w: Short = 0.toShort(), conv: (Double) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w)
// Conversions to Short
fun toMutableShortVec(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toMutableShortVec(conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec2(conv: (Double) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toMutableShortVec3(conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec4(w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w)
inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (Double) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w)
// Conversions to Byte
fun toByteVec(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec(conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec2(conv: (Double) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec3(conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec4(w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w)
inline fun toByteVec4(w: Byte = 0.toByte(), conv: (Double) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w)
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec(conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec2(conv: (Double) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec3(conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec4(w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w)
inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (Double) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w)
// Conversions to Char
fun toCharVec(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec(conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Double) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec3(conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec4(w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w)
inline fun toCharVec4(w: Char, conv: (Double) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w)
// Conversions to Char
fun toMutableCharVec(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec(conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Double) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec3(conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec4(w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w)
inline fun toMutableCharVec4(w: Char, conv: (Double) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w)
// Conversions to Boolean
fun toBoolVec(): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toBoolVec(conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.0, y != 0.0)
inline fun toBoolVec2(conv: (Double) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toBoolVec3(conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x != 0.0, y != 0.0, z != 0.0, w)
inline fun toBoolVec4(w: Boolean = false, conv: (Double) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w)
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toMutableBoolVec(conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.0, y != 0.0)
inline fun toMutableBoolVec2(conv: (Double) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toMutableBoolVec3(conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0.0, y != 0.0, z != 0.0, w)
inline fun toMutableBoolVec4(w: Boolean = false, conv: (Double) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w)
// Conversions to String
fun toStringVec(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec(conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Double) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec3(conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w)
inline fun toStringVec4(w: String = "", conv: (Double) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec(conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Double) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec3(conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w)
inline fun toMutableStringVec4(w: String = "", conv: (Double) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w)
// Conversions to T2
inline fun <T2> toTVec(conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec2(conv: (Double) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec4(w: T2, conv: (Double) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec2(conv: (Double) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec4(w: T2, conv: (Double) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: MutableDoubleVec2 get() = MutableDoubleVec2(x, x)
var xy: MutableDoubleVec2
get() = MutableDoubleVec2(x, y)
set(value) {
x = value.x
y = value.y
}
var xz: MutableDoubleVec2
get() = MutableDoubleVec2(x, z)
set(value) {
x = value.x
z = value.y
}
var yx: MutableDoubleVec2
get() = MutableDoubleVec2(y, x)
set(value) {
y = value.x
x = value.y
}
val yy: MutableDoubleVec2 get() = MutableDoubleVec2(y, y)
var yz: MutableDoubleVec2
get() = MutableDoubleVec2(y, z)
set(value) {
y = value.x
z = value.y
}
var zx: MutableDoubleVec2
get() = MutableDoubleVec2(z, x)
set(value) {
z = value.x
x = value.y
}
var zy: MutableDoubleVec2
get() = MutableDoubleVec2(z, y)
set(value) {
z = value.x
y = value.y
}
val zz: MutableDoubleVec2 get() = MutableDoubleVec2(z, z)
val xxx: MutableDoubleVec3 get() = MutableDoubleVec3(x, x, x)
val xxy: MutableDoubleVec3 get() = MutableDoubleVec3(x, x, y)
val xxz: MutableDoubleVec3 get() = MutableDoubleVec3(x, x, z)
val xyx: MutableDoubleVec3 get() = MutableDoubleVec3(x, y, x)
val xyy: MutableDoubleVec3 get() = MutableDoubleVec3(x, y, y)
var xyz: MutableDoubleVec3
get() = MutableDoubleVec3(x, y, z)
set(value) {
x = value.x
y = value.y
z = value.z
}
val xzx: MutableDoubleVec3 get() = MutableDoubleVec3(x, z, x)
var xzy: MutableDoubleVec3
get() = MutableDoubleVec3(x, z, y)
set(value) {
x = value.x
z = value.y
y = value.z
}
val xzz: MutableDoubleVec3 get() = MutableDoubleVec3(x, z, z)
val yxx: MutableDoubleVec3 get() = MutableDoubleVec3(y, x, x)
val yxy: MutableDoubleVec3 get() = MutableDoubleVec3(y, x, y)
var yxz: MutableDoubleVec3
get() = MutableDoubleVec3(y, x, z)
set(value) {
y = value.x
x = value.y
z = value.z
}
val yyx: MutableDoubleVec3 get() = MutableDoubleVec3(y, y, x)
val yyy: MutableDoubleVec3 get() = MutableDoubleVec3(y, y, y)
val yyz: MutableDoubleVec3 get() = MutableDoubleVec3(y, y, z)
var yzx: MutableDoubleVec3
get() = MutableDoubleVec3(y, z, x)
set(value) {
y = value.x
z = value.y
x = value.z
}
val yzy: MutableDoubleVec3 get() = MutableDoubleVec3(y, z, y)
val yzz: MutableDoubleVec3 get() = MutableDoubleVec3(y, z, z)
val zxx: MutableDoubleVec3 get() = MutableDoubleVec3(z, x, x)
var zxy: MutableDoubleVec3
get() = MutableDoubleVec3(z, x, y)
set(value) {
z = value.x
x = value.y
y = value.z
}
val zxz: MutableDoubleVec3 get() = MutableDoubleVec3(z, x, z)
var zyx: MutableDoubleVec3
get() = MutableDoubleVec3(z, y, x)
set(value) {
z = value.x
y = value.y
x = value.z
}
val zyy: MutableDoubleVec3 get() = MutableDoubleVec3(z, y, y)
val zyz: MutableDoubleVec3 get() = MutableDoubleVec3(z, y, z)
val zzx: MutableDoubleVec3 get() = MutableDoubleVec3(z, z, x)
val zzy: MutableDoubleVec3 get() = MutableDoubleVec3(z, z, y)
val zzz: MutableDoubleVec3 get() = MutableDoubleVec3(z, z, z)
val xxxx: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, x, x)
val xxxy: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, x, y)
val xxxz: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, x, z)
val xxyx: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, y, x)
val xxyy: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, y, y)
val xxyz: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, y, z)
val xxzx: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, z, x)
val xxzy: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, z, y)
val xxzz: MutableDoubleVec4 get() = MutableDoubleVec4(x, x, z, z)
val xyxx: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, x, x)
val xyxy: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, x, y)
val xyxz: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, x, z)
val xyyx: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, y, x)
val xyyy: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, y, y)
val xyyz: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, y, z)
val xyzx: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, z, x)
val xyzy: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, z, y)
val xyzz: MutableDoubleVec4 get() = MutableDoubleVec4(x, y, z, z)
val xzxx: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, x, x)
val xzxy: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, x, y)
val xzxz: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, x, z)
val xzyx: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, y, x)
val xzyy: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, y, y)
val xzyz: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, y, z)
val xzzx: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, z, x)
val xzzy: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, z, y)
val xzzz: MutableDoubleVec4 get() = MutableDoubleVec4(x, z, z, z)
val yxxx: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, x, x)
val yxxy: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, x, y)
val yxxz: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, x, z)
val yxyx: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, y, x)
val yxyy: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, y, y)
val yxyz: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, y, z)
val yxzx: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, z, x)
val yxzy: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, z, y)
val yxzz: MutableDoubleVec4 get() = MutableDoubleVec4(y, x, z, z)
val yyxx: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, x, x)
val yyxy: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, x, y)
val yyxz: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, x, z)
val yyyx: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, y, x)
val yyyy: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, y, y)
val yyyz: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, y, z)
val yyzx: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, z, x)
val yyzy: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, z, y)
val yyzz: MutableDoubleVec4 get() = MutableDoubleVec4(y, y, z, z)
val yzxx: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, x, x)
val yzxy: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, x, y)
val yzxz: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, x, z)
val yzyx: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, y, x)
val yzyy: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, y, y)
val yzyz: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, y, z)
val yzzx: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, z, x)
val yzzy: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, z, y)
val yzzz: MutableDoubleVec4 get() = MutableDoubleVec4(y, z, z, z)
val zxxx: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, x, x)
val zxxy: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, x, y)
val zxxz: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, x, z)
val zxyx: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, y, x)
val zxyy: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, y, y)
val zxyz: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, y, z)
val zxzx: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, z, x)
val zxzy: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, z, y)
val zxzz: MutableDoubleVec4 get() = MutableDoubleVec4(z, x, z, z)
val zyxx: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, x, x)
val zyxy: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, x, y)
val zyxz: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, x, z)
val zyyx: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, y, x)
val zyyy: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, y, y)
val zyyz: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, y, z)
val zyzx: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, z, x)
val zyzy: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, z, y)
val zyzz: MutableDoubleVec4 get() = MutableDoubleVec4(z, y, z, z)
val zzxx: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, x, x)
val zzxy: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, x, y)
val zzxz: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, x, z)
val zzyx: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, y, x)
val zzyy: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, y, y)
val zzyz: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, y, z)
val zzzx: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, z, x)
val zzzy: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, z, y)
val zzzz: MutableDoubleVec4 get() = MutableDoubleVec4(z, z, z, z)
}
val swizzle: Swizzle get() = Swizzle()
}
fun mutableVecOf(x: Double, y: Double, z: Double): MutableDoubleVec3 = MutableDoubleVec3(x, y, z)
operator fun Double.plus(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(this + rhs.x, this + rhs.y, this + rhs.z)
operator fun Double.minus(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(this - rhs.x, this - rhs.y, this - rhs.z)
operator fun Double.times(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(this * rhs.x, this * rhs.y, this * rhs.z)
operator fun Double.div(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(this / rhs.x, this / rhs.y, this / rhs.z)
operator fun Double.rem(rhs: MutableDoubleVec3): MutableDoubleVec3 = MutableDoubleVec3(this % rhs.x, this % rhs.y, this % rhs.z)
| mit | e3717602c2b52dace7f4ee14a77aa7cd | 65.540724 | 149 | 0.642617 | 3.644486 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/AnalyticsEvaluatorHelper.kt | 1 | 10539 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use 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 HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* 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 org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator
import java.util.*
import org.hisp.dhis.android.core.analytics.aggregated.DimensionItem
import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.helpers.DateUtils
import org.hisp.dhis.android.core.category.CategoryCategoryComboLinkTableInfo as cToCcInfo
import org.hisp.dhis.android.core.category.CategoryDataDimensionType
import org.hisp.dhis.android.core.category.CategoryOptionComboCategoryOptionLinkTableInfo as cocToCoInfo
import org.hisp.dhis.android.core.category.CategoryOptionComboTableInfo as cocInfo
import org.hisp.dhis.android.core.common.AggregationType
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitTableInfo
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.PeriodTableInfo
import org.hisp.dhis.android.core.period.PeriodType
/**
* This class includes some SQL helpers to build the where clause. Dimensions might include several items, like for
* example a Period dimension might include January, February and March. It is important to join the inner clauses
* using an OR operator in order to include all the element that match any element in the dimension. For example, this
* query should result in something like:
* - ... AND (period = January OR period = February OR period = March)...
*
* This logic applies for all the dimensions.
*/
@Suppress("TooManyFunctions")
internal object AnalyticsEvaluatorHelper {
private const val firstLastAggrYearOffset = -10
fun getElementAggregator(aggregationType: String?): AggregationType {
return aggregationType?.let { AggregationType.valueOf(it) }
?: AggregationType.SUM
}
fun appendOrgunitWhereClause(
columnName: String,
items: List<DimensionItem>,
builder: WhereClauseBuilder,
metadata: Map<String, MetadataItem>
): WhereClauseBuilder {
val innerClause = WhereClauseBuilder().apply {
items.map { i ->
when (val item = i as DimensionItem.OrganisationUnitItem) {
is DimensionItem.OrganisationUnitItem.Absolute -> {
appendOrInSubQuery(columnName, getOrgunitClause(item.uid))
}
is DimensionItem.OrganisationUnitItem.Level -> {
val metadataItem = metadata[item.id] as MetadataItem.OrganisationUnitLevelItem
appendOrInSubQuery(columnName, getOrgunitListClause(metadataItem.organisationUnitUids))
}
is DimensionItem.OrganisationUnitItem.Relative -> {
val metadataItem = metadata[item.id] as MetadataItem.OrganisationUnitRelativeItem
appendOrInSubQuery(columnName, getOrgunitListClause(metadataItem.organisationUnitUids))
}
is DimensionItem.OrganisationUnitItem.Group -> {
val metadataItem = metadata[item.id] as MetadataItem.OrganisationUnitGroupItem
appendOrInSubQuery(columnName, getOrgunitListClause(metadataItem.organisationUnitUids))
}
}
}
}.build()
return builder.appendComplexQuery(innerClause)
}
fun getReportingPeriods(
items: List<DimensionItem>,
metadata: Map<String, MetadataItem>
): List<Period> {
return mutableListOf<Period>().apply {
items.forEach { i ->
when (val item = i as DimensionItem.PeriodItem) {
is DimensionItem.PeriodItem.Absolute -> {
val periodItem = metadata[item.periodId] as MetadataItem.PeriodItem
add(periodItem.item)
}
is DimensionItem.PeriodItem.Relative -> {
val relativeItem = metadata[item.id] as MetadataItem.RelativePeriodItem
addAll(relativeItem.periods)
}
}
}
}
}
fun getReportingPeriodsForAggregationType(
periods: List<Period>,
aggregationType: AggregationType
): List<Period> {
return when (aggregationType) {
AggregationType.FIRST,
AggregationType.FIRST_AVERAGE_ORG_UNIT,
AggregationType.LAST,
AggregationType.LAST_AVERAGE_ORG_UNIT -> {
val startDate = DateUtils.getStartDate(periods)
val endDate = DateUtils.getEndDate(periods)
startDate?.let {
val earliest = DateUtils.dateWithOffset(startDate, firstLastAggrYearOffset, PeriodType.Yearly)
listOf(Period.builder().startDate(earliest).endDate(endDate).build())
} ?: periods
}
else -> periods
}
}
fun getStartDate(
items: List<DimensionItem>,
metadata: Map<String, MetadataItem>
): Date? {
return items.map { it as DimensionItem.PeriodItem }
.map { metadata[it.id] as MetadataItem.PeriodItem }
.map { it.item }
.let { DateUtils.getStartDate(it) }
}
fun getEndDate(
items: List<DimensionItem>,
metadata: Map<String, MetadataItem>
): Date? {
return items.map { it as DimensionItem.PeriodItem }
.map { metadata[it.id] as MetadataItem.PeriodItem }
.map { it.item }
.let { DateUtils.getEndDate(it) }
}
fun getInPeriodsClause(periods: List<Period>): String {
return "SELECT ${PeriodTableInfo.Columns.PERIOD_ID} " +
"FROM ${PeriodTableInfo.TABLE_INFO.name()} " +
"WHERE ${
periods.joinToString(" OR ") {
"(${
getPeriodWhereClause(
PeriodTableInfo.Columns.START_DATE,
PeriodTableInfo.Columns.END_DATE,
it
)
})"
}
}"
}
fun getPeriodWhereClause(columnStart: String, columnEnd: String, period: Period): String {
return "$columnStart >= '${DateUtils.DATE_FORMAT.format(period.startDate()!!)}' " +
"AND " +
"$columnEnd <= '${DateUtils.DATE_FORMAT.format(period.endDate()!!)}'"
}
private fun getOrgunitClause(orgunitUid: String): String {
return "SELECT ${OrganisationUnitTableInfo.Columns.UID} " +
"FROM ${OrganisationUnitTableInfo.TABLE_INFO.name()} " +
"WHERE " +
"${OrganisationUnitTableInfo.Columns.PATH} LIKE '%$orgunitUid%'"
}
private fun getOrgunitListClause(orgunitUids: List<String>): String {
return "SELECT ${OrganisationUnitTableInfo.Columns.UID} " +
"FROM ${OrganisationUnitTableInfo.TABLE_INFO.name()} " +
"WHERE " +
orgunitUids.joinToString(" OR ") { "${OrganisationUnitTableInfo.Columns.PATH} LIKE '%$it%'" }
}
fun appendCategoryWhereClause(
attributeColumnName: String?,
disaggregationColumnName: String?,
items: List<DimensionItem>,
builder: WhereClauseBuilder,
metadata: Map<String, MetadataItem>
): WhereClauseBuilder {
val innerClause = WhereClauseBuilder().apply {
items.map { it as DimensionItem.CategoryItem }.map { item ->
metadata[item.uid]?.let { it as MetadataItem.CategoryItem }.let { category ->
val columnName =
if (category?.item?.dataDimensionType() == CategoryDataDimensionType.ATTRIBUTE.name) {
attributeColumnName
} else {
disaggregationColumnName
}
columnName?.let { appendOrInSubQuery(it, getCategoryOptionClause(item.uid, item.categoryOption)) }
}
}
}.build()
return builder.appendComplexQuery(innerClause)
}
private fun getCategoryOptionClause(categoryUid: String, categoryOptionUid: String): String {
return "SELECT ${cocInfo.Columns.UID} " +
"FROM ${cocInfo.TABLE_INFO.name()} " +
"WHERE " +
"${cocInfo.Columns.UID} IN " +
"(" +
"SELECT ${cocToCoInfo.Columns.CATEGORY_OPTION_COMBO} " +
"FROM ${cocToCoInfo.TABLE_INFO.name()} " +
"WHERE ${cocToCoInfo.Columns.CATEGORY_OPTION} = '$categoryOptionUid'" +
") " +
"AND " +
"${cocInfo.Columns.CATEGORY_COMBO} IN " +
"(" +
"SELECT ${cToCcInfo.Columns.CATEGORY_COMBO} " +
"FROM ${cToCcInfo.TABLE_INFO.name()} " +
"WHERE ${cToCcInfo.Columns.CATEGORY} = '$categoryUid'" +
") "
}
}
| bsd-3-clause | db1f5dbcc8fcd79f4306306cc7b8c01e | 44.038462 | 118 | 0.633741 | 4.863406 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/readinglist/ReadingListFragment.kt | 1 | 35599 | package org.wikipedia.readinglist
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.ActionMode
import androidx.core.content.ContextCompat
import androidx.core.graphics.BlendModeColorFilterCompat
import androidx.core.graphics.BlendModeCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.ReadingListsFunnel
import org.wikipedia.databinding.FragmentReadingListBinding
import org.wikipedia.events.PageDownloadEvent
import org.wikipedia.history.HistoryEntry
import org.wikipedia.history.SearchActionModeCallback
import org.wikipedia.main.MainActivity
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.PageActivity
import org.wikipedia.page.PageAvailableOfflineHandler
import org.wikipedia.page.PageAvailableOfflineHandler.check
import org.wikipedia.readinglist.database.ReadingList
import org.wikipedia.readinglist.database.ReadingListDbHelper
import org.wikipedia.readinglist.database.ReadingListPage
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter
import org.wikipedia.readinglist.sync.ReadingListSyncEvent
import org.wikipedia.settings.Prefs
import org.wikipedia.settings.SiteInfoClient.maxPagesPerReadingList
import org.wikipedia.util.*
import org.wikipedia.views.*
import org.wikipedia.views.MultiSelectActionModeCallback.Companion.isTagType
class ReadingListFragment : Fragment(), ReadingListItemActionsDialog.Callback {
private var _binding: FragmentReadingListBinding? = null
private val binding get() = _binding!!
private lateinit var touchCallback: SwipeableItemTouchHelperCallback
private lateinit var headerView: ReadingListItemView
private val disposables = CompositeDisposable()
private var readingList: ReadingList? = null
private var readingListId: Long = 0
private val adapter = ReadingListPageItemAdapter()
private var actionMode: ActionMode? = null
private val appBarListener = AppBarListener()
private var showOverflowMenu = false
private val funnel = ReadingListsFunnel()
private val readingListItemCallback = ReadingListItemCallback()
private val readingListPageItemCallback = ReadingListPageItemCallback()
private val searchActionModeCallback = SearchCallback()
private val multiSelectActionModeCallback = MultiSelectCallback()
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
private var toolbarExpanded = true
private var displayedLists = mutableListOf<Any>()
private var currentSearchQuery: String? = null
private var articleLimitMessageShown = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentReadingListBinding.inflate(inflater, container, false)
appCompatActivity.setSupportActionBar(binding.readingListToolbar)
appCompatActivity.supportActionBar!!.setDisplayHomeAsUpEnabled(true)
appCompatActivity.supportActionBar!!.title = ""
DeviceUtil.updateStatusBarTheme(requireActivity(), binding.readingListToolbar, true)
touchCallback = SwipeableItemTouchHelperCallback(requireContext())
ItemTouchHelper(touchCallback).attachToRecyclerView(binding.readingListRecyclerView)
readingListId = requireArguments().getLong(ReadingListActivity.EXTRA_READING_LIST_ID)
setToolbar()
setHeaderView()
setRecyclerView()
setSwipeRefreshView()
disposables.add(WikipediaApp.getInstance().bus.subscribe(EventBusConsumer()))
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
}
override fun onResume() {
super.onResume()
updateReadingListData()
}
override fun onDestroyView() {
disposables.clear()
binding.readingListRecyclerView.adapter = null
binding.readingListAppBar.removeOnOffsetChangedListener(appBarListener)
_binding = null
super.onDestroyView()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_reading_list, menu)
if (showOverflowMenu) {
inflater.inflate(R.menu.menu_reading_list_item, menu)
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
val sortByNameItem = menu.findItem(R.id.menu_sort_by_name)
val sortByRecentItem = menu.findItem(R.id.menu_sort_by_recent)
val sortMode = Prefs.getReadingListPageSortMode(ReadingList.SORT_BY_NAME_ASC)
sortByNameItem.setTitle(if (sortMode == ReadingList.SORT_BY_NAME_ASC) R.string.reading_list_sort_by_name_desc else R.string.reading_list_sort_by_name)
sortByRecentItem.setTitle(if (sortMode == ReadingList.SORT_BY_RECENT_DESC) R.string.reading_list_sort_by_recent_desc else R.string.reading_list_sort_by_recent)
val searchItem = menu.findItem(R.id.menu_search_lists)
val sortOptionsItem = menu.findItem(R.id.menu_sort_options)
val iconColor = if (toolbarExpanded) ContextCompat.getColor(requireContext(), android.R.color.white) else ResourceUtil.getThemedColor(requireContext(), R.attr.toolbar_icon_color)
searchItem.icon.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(iconColor, BlendModeCompat.SRC_IN)
sortOptionsItem.icon.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(iconColor, BlendModeCompat.SRC_IN)
readingList?.let {
if (it.isDefault) {
menu.findItem(R.id.menu_reading_list_rename)?.let { item ->
item.isVisible = false
}
menu.findItem(R.id.menu_reading_list_delete)?.let { item ->
item.isVisible = false
}
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_search_lists -> {
appCompatActivity.startSupportActionMode(searchActionModeCallback)
true
}
R.id.menu_sort_by_name -> {
setSortMode(ReadingList.SORT_BY_NAME_ASC, ReadingList.SORT_BY_NAME_DESC)
true
}
R.id.menu_sort_by_recent -> {
setSortMode(ReadingList.SORT_BY_RECENT_DESC, ReadingList.SORT_BY_RECENT_ASC)
true
}
R.id.menu_reading_list_rename -> {
rename()
true
}
R.id.menu_reading_list_delete -> {
delete()
true
}
R.id.menu_reading_list_save_all_offline -> {
readingList?.let {
ReadingListBehaviorsUtil.savePagesForOffline(requireActivity(), it.pages) {
adapter.notifyDataSetChanged()
update()
}
}
true
}
R.id.menu_reading_list_remove_all_offline -> {
readingList?.let {
ReadingListBehaviorsUtil.removePagesFromOffline(requireActivity(), it.pages) {
adapter.notifyDataSetChanged()
update()
}
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun setToolbar() {
binding.readingListAppBar.addOnOffsetChangedListener(appBarListener)
binding.readingListToolbarContainer.setCollapsedTitleTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.toolbar_icon_color))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
binding.readingListToolbarContainer.setStatusBarScrimColor(ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color))
}
}
private fun setHeaderView() {
headerView = ReadingListItemView(requireContext())
headerView.callback = HeaderCallback()
headerView.isClickable = false
headerView.setThumbnailVisible(false)
headerView.setTitleTextAppearance(R.style.ReadingListTitleTextAppearance)
headerView.setOverflowViewVisibility(View.VISIBLE)
}
private fun setRecyclerView() {
binding.readingListRecyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.readingListRecyclerView.adapter = adapter
(binding.readingListRecyclerView.itemAnimator as SimpleItemAnimator?)!!.supportsChangeAnimations = false
binding.readingListRecyclerView.addItemDecoration(DrawableItemDecoration(requireContext(), R.attr.list_separator_drawable, drawStart = true, drawEnd = false))
}
private fun setSwipeRefreshView() {
binding.readingListSwipeRefresh.setColorSchemeResources(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.colorAccent))
binding.readingListSwipeRefresh.setOnRefreshListener { ReadingListsFragment.refreshSync(this, binding.readingListSwipeRefresh) }
if (ReadingListSyncAdapter.isDisabledByRemoteConfig) {
binding.readingListSwipeRefresh.isEnabled = false
}
}
private val appCompatActivity get() = requireActivity() as AppCompatActivity
private fun update(readingList: ReadingList? = this.readingList) {
readingList?.let {
binding.readingListEmptyText.visibility = if (it.pages.isEmpty()) View.VISIBLE else View.GONE
headerView.setReadingList(it, ReadingListItemView.Description.DETAIL)
binding.readingListHeader.setReadingList(it)
ReadingList.sort(readingList, Prefs.getReadingListPageSortMode(ReadingList.SORT_BY_NAME_ASC))
setSearchQuery()
if (!toolbarExpanded) {
binding.readingListToolbarContainer.title = it.title
}
if (!articleLimitMessageShown && it.pages.size >= maxPagesPerReadingList) {
val message = getString(R.string.reading_list_article_limit_message, readingList.title, maxPagesPerReadingList)
FeedbackUtil.makeSnackbar(requireActivity(), message, FeedbackUtil.LENGTH_DEFAULT).show()
articleLimitMessageShown = true
}
}
}
private fun updateReadingListData() {
disposables.add(Observable.fromCallable { ReadingListDbHelper.getListById(readingListId, true) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ list ->
binding.readingListSwipeRefresh.isRefreshing = false
readingList = list
readingList?.let {
binding.searchEmptyView.setEmptyText(getString(R.string.search_reading_list_no_results, it.title))
}
update()
}) {
// If we failed to retrieve the requested list, it means that the list is no
// longer in the database (likely removed due to sync).
// In this case, there's nothing for us to do, so just bail from the activity.
requireActivity().finish()
})
}
private fun setSearchQuery() {
setSearchQuery(currentSearchQuery)
}
private fun setSearchQuery(query: String?) {
readingList?.let {
currentSearchQuery = query
if (query.isNullOrEmpty()) {
displayedLists.clear()
displayedLists.addAll(it.pages)
adapter.notifyDataSetChanged()
updateEmptyState(query)
} else {
ReadingListBehaviorsUtil.searchListsAndPages(query) { lists ->
displayedLists = lists
adapter.notifyDataSetChanged()
updateEmptyState(query)
}
}
touchCallback.swipeableEnabled = query.isNullOrEmpty()
}
}
private fun updateEmptyState(searchQuery: String?) {
if (searchQuery.isNullOrEmpty()) {
binding.searchEmptyView.visibility = View.GONE
binding.readingListRecyclerView.visibility = View.VISIBLE
binding.readingListEmptyText.visibility = if (displayedLists.isEmpty()) View.VISIBLE else View.GONE
} else {
binding.readingListRecyclerView.visibility = if (displayedLists.isEmpty()) View.GONE else View.VISIBLE
binding.searchEmptyView.visibility = if (displayedLists.isEmpty()) View.VISIBLE else View.GONE
binding.readingListEmptyText.visibility = View.GONE
}
}
private fun setSortMode(sortModeAsc: Int, sortModeDesc: Int) {
var sortMode = Prefs.getReadingListPageSortMode(ReadingList.SORT_BY_NAME_ASC)
sortMode = if (sortMode != sortModeAsc) {
sortModeAsc
} else {
sortModeDesc
}
Prefs.setReadingListPageSortMode(sortMode)
requireActivity().invalidateOptionsMenu()
update()
}
private fun rename() {
ReadingListBehaviorsUtil.renameReadingList(requireActivity(), readingList) {
update()
funnel.logModifyList(readingList!!, 0)
}
}
private fun finishActionMode() {
actionMode?.finish()
}
private fun beginMultiSelect() {
if (SearchActionModeCallback.`is`(actionMode)) {
finishActionMode()
}
if (!isTagType(actionMode)) {
appCompatActivity.startSupportActionMode(multiSelectActionModeCallback)
}
}
private fun toggleSelectPage(page: ReadingListPage?) {
page?.let {
it.selected = !it.selected
if (selectedPageCount == 0) {
finishActionMode()
} else {
actionMode?.title = resources.getQuantityString(R.plurals.multi_items_selected, selectedPageCount, selectedPageCount)
}
adapter.notifyDataSetChanged()
}
}
private val selectedPageCount: Int
get() {
var selectedCount = 0
displayedLists.forEach {
if (it is ReadingListPage && it.selected) {
selectedCount++
}
}
return selectedCount
}
private fun unselectAllPages() {
readingList?.let {
it.pages.forEach { page ->
page.selected = false
}
adapter.notifyDataSetChanged()
}
}
/**
* CAUTION: This returns the selected pages AND automatically marks them as unselected.
* Make sure to call this getter once, and operate only on the returned list.
*/
private val selectedPages: List<ReadingListPage>
get() {
val result = mutableListOf<ReadingListPage>()
readingList?.let {
displayedLists.forEach { list ->
if (list is ReadingListPage && list.selected) {
result.add(list)
list.selected = false
}
}
}
return result
}
private fun deleteSelectedPages() {
readingList?.let {
val pages = selectedPages
if (pages.isNotEmpty()) {
ReadingListDbHelper.markPagesForDeletion(it, pages)
it.pages.removeAll(pages)
funnel.logDeleteItem(it, 0)
ReadingListBehaviorsUtil.showDeletePagesUndoSnackbar(requireActivity(), it, pages) { updateReadingListData() }
update()
}
}
}
private fun addSelectedPagesToList() {
val pages = selectedPages
if (pages.isNotEmpty()) {
val titles = pages.map { ReadingListPage.toPageTitle(it) }
bottomSheetPresenter.show(childFragmentManager,
AddToReadingListDialog.newInstance(titles, InvokeSource.READING_LIST_ACTIVITY))
update()
}
}
private fun moveSelectedPagesToList() {
val pages = selectedPages
if (pages.isNotEmpty()) {
val titles = pages.map { ReadingListPage.toPageTitle(it) }
bottomSheetPresenter.show(childFragmentManager,
MoveToReadingListDialog.newInstance(readingListId, titles, InvokeSource.READING_LIST_ACTIVITY))
update()
}
}
private fun delete() {
readingList?.let {
ReadingListBehaviorsUtil.deleteReadingList(requireActivity(), it, true) {
startActivity(MainActivity.newIntent(requireActivity()).putExtra(Constants.INTENT_EXTRA_DELETE_READING_LIST, it.title))
requireActivity().finish()
}
}
}
override fun onToggleItemOffline(pageId: Long) {
val page = getPageById(pageId) ?: return
ReadingListBehaviorsUtil.togglePageOffline(requireActivity(), page) {
adapter.notifyDataSetChanged()
update()
}
}
override fun onShareItem(pageId: Long) {
val page = getPageById(pageId) ?: return
ShareUtil.shareText(requireContext(), ReadingListPage.toPageTitle(page))
}
override fun onAddItemToOther(pageId: Long) {
val page = getPageById(pageId) ?: return
bottomSheetPresenter.show(childFragmentManager,
AddToReadingListDialog.newInstance(ReadingListPage.toPageTitle(page), InvokeSource.READING_LIST_ACTIVITY))
}
override fun onMoveItemToOther(pageId: Long) {
val page = getPageById(pageId) ?: return
bottomSheetPresenter.show(childFragmentManager,
MoveToReadingListDialog.newInstance(readingListId, ReadingListPage.toPageTitle(page), InvokeSource.READING_LIST_ACTIVITY))
}
override fun onSelectItem(pageId: Long) {
val page = getPageById(pageId) ?: return
if (actionMode == null || isTagType(actionMode)) {
beginMultiSelect()
toggleSelectPage(page)
}
}
override fun onDeleteItem(pageId: Long) {
val page = getPageById(pageId) ?: return
readingList?.let {
val listsContainPage = if (currentSearchQuery.isNullOrEmpty()) listOf(it) else ReadingListBehaviorsUtil.getListsContainPage(page)
ReadingListBehaviorsUtil.deletePages(requireActivity(), listsContainPage, page, { updateReadingListData() }, {
// TODO: need to verify the log of delete item since this action will delete multiple items in the same time.
funnel.logDeleteItem(it, 0)
update()
})
}
}
private fun getPageById(id: Long): ReadingListPage? {
return readingList?.pages?.firstOrNull { it.id == id }
}
private inner class AppBarListener : OnOffsetChangedListener {
override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
if (verticalOffset > -appBarLayout.totalScrollRange && showOverflowMenu) {
showOverflowMenu = false
binding.readingListToolbarContainer.title = ""
appCompatActivity.invalidateOptionsMenu()
toolbarExpanded = true
} else if (verticalOffset <= -appBarLayout.totalScrollRange && !showOverflowMenu) {
showOverflowMenu = true
binding.readingListToolbarContainer.title = readingList?.title
appCompatActivity.invalidateOptionsMenu()
toolbarExpanded = false
}
DeviceUtil.updateStatusBarTheme(requireActivity(), binding.readingListToolbar,
actionMode == null && appBarLayout.totalScrollRange + verticalOffset > appBarLayout.totalScrollRange / 2)
(requireActivity() as ReadingListActivity).updateNavigationBarColor()
// prevent swiping when collapsing the view
binding.readingListSwipeRefresh.isEnabled = verticalOffset == 0
}
}
private inner class ReadingListItemHolder constructor(itemView: ReadingListItemView) : DefaultViewHolder<View>(itemView) {
fun bindItem(readingList: ReadingList) {
view.setReadingList(readingList, ReadingListItemView.Description.SUMMARY)
view.setSearchQuery(currentSearchQuery)
}
override val view get() = itemView as ReadingListItemView
}
private inner class ReadingListPageItemHolder constructor(itemView: PageItemView<ReadingListPage>) : DefaultViewHolder<PageItemView<ReadingListPage>>(itemView), SwipeableItemTouchHelperCallback.Callback {
private lateinit var page: ReadingListPage
fun bindItem(page: ReadingListPage) {
this.page = page
view.item = page
view.setTitle(page.displayTitle)
view.setDescription(page.description)
view.setImageUrl(page.thumbUrl)
view.isSelected = page.selected
view.setSecondaryActionIcon(if (page.saving) R.drawable.ic_download_in_progress else R.drawable.ic_download_circle_gray_24dp,
!page.offline || page.saving)
view.setCircularProgressVisibility(page.downloadProgress > 0 && page.downloadProgress < CircularProgressBar.MAX_PROGRESS)
view.setProgress(if (page.downloadProgress == CircularProgressBar.MAX_PROGRESS) 0 else page.downloadProgress)
view.setActionHint(R.string.reading_list_article_make_offline)
view.setSearchQuery(currentSearchQuery)
view.setListItemImageDimensions(imageDimension, imageDimension)
check(page, PageAvailableOfflineHandler.Callback { available -> view.setViewsGreyedOut(!available) })
if (!currentSearchQuery.isNullOrEmpty()) {
view.setTitleMaxLines(2)
view.setTitleEllipsis()
view.setDescriptionMaxLines(2)
view.setDescriptionEllipsis()
view.setUpChipGroup(ReadingListBehaviorsUtil.getListsContainPage(page))
} else {
view.hideChipGroup()
}
}
override fun onSwipe() {
readingList?.let {
if (currentSearchQuery.isNullOrEmpty()) {
ReadingListBehaviorsUtil.deletePages(requireActivity(), listOf(it), page, { updateReadingListData() }, {
funnel.logDeleteItem(it, 0)
update()
})
}
}
}
private val imageDimension
get() = DimenUtil.roundedDpToPx(if (currentSearchQuery.isNullOrEmpty()) DimenUtil.getDimension(R.dimen.view_list_card_item_image) else ReadingListsFragment.ARTICLE_ITEM_IMAGE_DIMENSION.toFloat())
}
private inner class ReadingListHeaderHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView)
private inner class ReadingListPageItemAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val headerCount get() = if (currentSearchQuery.isNullOrEmpty()) 1 else 0
override fun getItemViewType(position: Int): Int {
return if (headerCount == 1 && position == 0) {
Companion.TYPE_HEADER
} else if (displayedLists[position - headerCount] is ReadingList) {
Companion.TYPE_ITEM
} else {
Companion.TYPE_PAGE_ITEM
}
}
override fun getItemCount(): Int {
return headerCount + displayedLists.size
}
override fun onCreateViewHolder(parent: ViewGroup, type: Int): RecyclerView.ViewHolder {
return when (type) {
Companion.TYPE_ITEM -> {
val view = ReadingListItemView(requireContext())
ReadingListItemHolder(view)
}
Companion.TYPE_HEADER -> {
ReadingListHeaderHolder(headerView)
}
else -> {
ReadingListPageItemHolder(PageItemView(requireContext()))
}
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, pos: Int) {
readingList?.let {
if (holder is ReadingListItemHolder) {
holder.bindItem(displayedLists[pos - headerCount] as ReadingList)
} else if (holder is ReadingListPageItemHolder) {
holder.bindItem(displayedLists[pos - headerCount] as ReadingListPage)
}
}
}
override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
super.onViewAttachedToWindow(holder)
if (holder is ReadingListItemHolder) {
holder.view.callback = readingListItemCallback
} else if (holder is ReadingListPageItemHolder) {
holder.view.callback = readingListPageItemCallback
}
}
override fun onViewDetachedFromWindow(holder: RecyclerView.ViewHolder) {
if (holder is ReadingListItemHolder) {
holder.view.callback = null
} else if (holder is ReadingListPageItemHolder) {
holder.view.callback = null
}
super.onViewDetachedFromWindow(holder)
}
}
private inner class HeaderCallback : ReadingListItemView.Callback {
override fun onClick(readingList: ReadingList) {}
override fun onRename(readingList: ReadingList) {
rename()
}
override fun onDelete(readingList: ReadingList) {
delete()
}
override fun onSaveAllOffline(readingList: ReadingList) {
ReadingListBehaviorsUtil.savePagesForOffline(requireActivity(), readingList.pages) {
adapter.notifyDataSetChanged()
update()
}
}
override fun onRemoveAllOffline(readingList: ReadingList) {
ReadingListBehaviorsUtil.removePagesFromOffline(requireActivity(), readingList.pages) {
adapter.notifyDataSetChanged()
update()
}
}
}
private inner class ReadingListItemCallback : ReadingListItemView.Callback {
override fun onClick(readingList: ReadingList) {
actionMode?.finish()
startActivity(ReadingListActivity.newIntent(requireContext(), readingList))
}
override fun onRename(readingList: ReadingList) {
ReadingListBehaviorsUtil.renameReadingList(requireActivity(), readingList) { update(readingList) }
}
override fun onDelete(readingList: ReadingList) {
ReadingListBehaviorsUtil.deleteReadingList(requireActivity(), readingList, true) {
ReadingListBehaviorsUtil.showDeleteListUndoSnackbar(requireActivity(), readingList) { setSearchQuery() }
setSearchQuery()
}
}
override fun onSaveAllOffline(readingList: ReadingList) {
ReadingListBehaviorsUtil.savePagesForOffline(requireActivity(), readingList.pages) { setSearchQuery() }
}
override fun onRemoveAllOffline(readingList: ReadingList) {
ReadingListBehaviorsUtil.removePagesFromOffline(requireActivity(), readingList.pages) { setSearchQuery() }
}
}
private inner class ReadingListPageItemCallback : PageItemView.Callback<ReadingListPage?> {
override fun onClick(item: ReadingListPage?) {
if (isTagType(actionMode)) {
toggleSelectPage(item)
} else if (item != null) {
val title = ReadingListPage.toPageTitle(item)
val entry = HistoryEntry(title, HistoryEntry.SOURCE_READING_LIST)
item.touch()
Completable.fromAction {
ReadingListDbHelper.updateLists(ReadingListBehaviorsUtil.getListsContainPage(item), false)
ReadingListDbHelper.updatePage(item)
}.subscribeOn(Schedulers.io()).subscribe()
startActivity(PageActivity.newIntentForCurrentTab(requireContext(), entry, entry.title))
}
}
override fun onLongClick(item: ReadingListPage?): Boolean {
item?.let {
bottomSheetPresenter.show(childFragmentManager,
ReadingListItemActionsDialog.newInstance(if (currentSearchQuery.isNullOrEmpty()) listOf(readingList!!)
else ReadingListBehaviorsUtil.getListsContainPage(it), it.id, actionMode != null))
return true
}
return false
}
override fun onThumbClick(item: ReadingListPage?) {
onClick(item)
}
override fun onActionClick(item: ReadingListPage?, view: View) {
item?.let {
if (Prefs.isDownloadOnlyOverWiFiEnabled() && !DeviceUtil.isOnWiFi() && it.status == ReadingListPage.STATUS_QUEUE_FOR_SAVE) {
it.offline = false
}
if (it.saving) {
Toast.makeText(context, R.string.reading_list_article_save_in_progress, Toast.LENGTH_LONG).show()
} else {
ReadingListBehaviorsUtil.toggleOffline(requireActivity(), item) {
adapter.notifyDataSetChanged()
update()
}
}
}
}
override fun onListChipClick(readingList: ReadingList) {
startActivity(ReadingListActivity.newIntent(requireContext(), readingList))
}
}
private fun setStatusBarActionMode(inActionMode: Boolean) {
DeviceUtil.updateStatusBarTheme(requireActivity(), binding.readingListToolbar, toolbarExpanded && !inActionMode)
requireActivity().window.statusBarColor = if (!inActionMode) Color.TRANSPARENT else ResourceUtil.getThemedColor(requireActivity(), R.attr.paper_color)
}
private inner class SearchCallback : SearchActionModeCallback() {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
actionMode = mode
binding.readingListRecyclerView.stopScroll()
binding.readingListAppBar.setExpanded(false, false)
setStatusBarActionMode(true)
return super.onCreateActionMode(mode, menu)
}
override fun onQueryChange(s: String) {
setSearchQuery(s.trim())
}
override fun onDestroyActionMode(mode: ActionMode) {
super.onDestroyActionMode(mode)
actionMode = null
currentSearchQuery = null
setStatusBarActionMode(false)
updateReadingListData()
}
override fun getSearchHintString(): String {
return getString(R.string.filter_hint_filter_my_lists_and_articles)
}
override fun getParentContext(): Context {
return requireContext()
}
}
private inner class MultiSelectCallback : MultiSelectActionModeCallback() {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
super.onCreateActionMode(mode, menu)
mode.menuInflater.inflate(R.menu.menu_action_mode_reading_list, menu)
actionMode = mode
setStatusBarActionMode(true)
return true
}
override fun onActionItemClicked(mode: ActionMode, menuItem: MenuItem): Boolean {
when (menuItem.itemId) {
R.id.menu_delete_selected -> {
onDeleteSelected()
finishActionMode()
return true
}
R.id.menu_remove_from_offline -> {
ReadingListBehaviorsUtil.removePagesFromOffline(requireActivity(), selectedPages) {
adapter.notifyDataSetChanged()
update()
}
finishActionMode()
return true
}
R.id.menu_save_for_offline -> {
ReadingListBehaviorsUtil.savePagesForOffline(requireActivity(), selectedPages) {
adapter.notifyDataSetChanged()
update()
}
finishActionMode()
return true
}
R.id.menu_add_to_another_list -> {
addSelectedPagesToList()
finishActionMode()
return true
}
R.id.menu_move_to_another_list -> {
moveSelectedPagesToList()
finishActionMode()
return true
}
else -> return false
}
}
override fun onDeleteSelected() {
deleteSelectedPages()
}
override fun onDestroyActionMode(mode: ActionMode) {
unselectAllPages()
actionMode = null
setStatusBarActionMode(false)
super.onDestroyActionMode(mode)
}
}
private inner class EventBusConsumer : Consumer<Any> {
override fun accept(event: Any) {
if (event is ReadingListSyncEvent) {
updateReadingListData()
} else if (event is PageDownloadEvent) {
val pagePosition = getPagePositionInList(event.page)
if (pagePosition != -1 && displayedLists[pagePosition] is ReadingListPage) {
(displayedLists[pagePosition] as ReadingListPage).downloadProgress = event.page.downloadProgress
adapter.notifyItemChanged(pagePosition + 1)
}
}
}
}
private fun getPagePositionInList(page: ReadingListPage): Int {
displayedLists.forEach {
if (it is ReadingListPage && it.id == page.id) {
return displayedLists.indexOf(it)
}
}
return -1
}
companion object {
private const val TYPE_HEADER = 0
private const val TYPE_ITEM = 1
private const val TYPE_PAGE_ITEM = 2
fun newInstance(listId: Long): ReadingListFragment {
return ReadingListFragment().apply {
arguments = bundleOf(ReadingListActivity.EXTRA_READING_LIST_ID to listId)
}
}
}
}
| apache-2.0 | c5121e5241e5f3bcc666014592f09900 | 41.78726 | 208 | 0.637068 | 5.387258 | false | false | false | false |
dahlstrom-g/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/LibraryPropertiesEntityImpl.kt | 2 | 9725 | package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild
import com.intellij.workspaceModel.storage.referrersx
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.io.Serializable
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class LibraryPropertiesEntityImpl: LibraryPropertiesEntity, WorkspaceEntityBase() {
companion object {
internal val LIBRARY_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, LibraryPropertiesEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
LIBRARY_CONNECTION_ID,
)
}
override val library: LibraryEntity
get() = snapshot.extractOneToOneParent(LIBRARY_CONNECTION_ID, this)!!
@JvmField var _libraryType: String? = null
override val libraryType: String
get() = _libraryType!!
@JvmField var _propertiesXmlTag: String? = null
override val propertiesXmlTag: String?
get() = _propertiesXmlTag
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: LibraryPropertiesEntityData?): ModifiableWorkspaceEntityBase<LibraryPropertiesEntity>(), LibraryPropertiesEntity.Builder {
constructor(): this(LibraryPropertiesEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity LibraryPropertiesEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (_diff != null) {
if (_diff.extractOneToOneParent<WorkspaceEntityBase>(LIBRARY_CONNECTION_ID, this) == null) {
error("Field LibraryPropertiesEntity#library should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)] == null) {
error("Field LibraryPropertiesEntity#library should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field LibraryPropertiesEntity#entitySource should be initialized")
}
if (!getEntityData().isLibraryTypeInitialized()) {
error("Field LibraryPropertiesEntity#libraryType should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var library: LibraryEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneParent(LIBRARY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)]!! as LibraryEntity
} else {
this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)]!! as LibraryEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, LIBRARY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneParentOfChild(LIBRARY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, LIBRARY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)] = value
}
changedProperty.add("library")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var libraryType: String
get() = getEntityData().libraryType
set(value) {
checkModificationAllowed()
getEntityData().libraryType = value
changedProperty.add("libraryType")
}
override var propertiesXmlTag: String?
get() = getEntityData().propertiesXmlTag
set(value) {
checkModificationAllowed()
getEntityData().propertiesXmlTag = value
changedProperty.add("propertiesXmlTag")
}
override fun getEntityData(): LibraryPropertiesEntityData = result ?: super.getEntityData() as LibraryPropertiesEntityData
override fun getEntityClass(): Class<LibraryPropertiesEntity> = LibraryPropertiesEntity::class.java
}
}
class LibraryPropertiesEntityData : WorkspaceEntityData<LibraryPropertiesEntity>() {
lateinit var libraryType: String
var propertiesXmlTag: String? = null
fun isLibraryTypeInitialized(): Boolean = ::libraryType.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LibraryPropertiesEntity> {
val modifiable = LibraryPropertiesEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): LibraryPropertiesEntity {
val entity = LibraryPropertiesEntityImpl()
entity._libraryType = libraryType
entity._propertiesXmlTag = propertiesXmlTag
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return LibraryPropertiesEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LibraryPropertiesEntityData
if (this.entitySource != other.entitySource) return false
if (this.libraryType != other.libraryType) return false
if (this.propertiesXmlTag != other.propertiesXmlTag) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as LibraryPropertiesEntityData
if (this.libraryType != other.libraryType) return false
if (this.propertiesXmlTag != other.propertiesXmlTag) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + libraryType.hashCode()
result = 31 * result + propertiesXmlTag.hashCode()
return result
}
} | apache-2.0 | 3d1f31c0ef0ea468ae6082e384f49c96 | 40.564103 | 189 | 0.637738 | 6.174603 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceCallWithUnaryOperatorIntention.kt | 5 | 2453 | // 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.conventionNameCalls
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.calleeName
import org.jetbrains.kotlin.idea.intentions.isReceiverExpressionWithValue
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.types.expressions.OperatorConventions
class ReplaceCallWithUnaryOperatorIntention : SelfTargetingRangeIntention<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java,
KotlinBundle.lazyMessage("replace.call.with.unary.operator")
), HighPriorityAction {
override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? {
val operation = operation(element.calleeName) ?: return null
if (!isApplicableOperation(operation)) return null
val call = element.callExpression ?: return null
if (call.typeArgumentList != null) return null
if (call.valueArguments.isNotEmpty()) return null
if (!element.isReceiverExpressionWithValue()) return null
setTextGetter(KotlinBundle.lazyMessage("replace.with.0.operator", operation.value))
return call.calleeExpression?.textRange
}
override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) {
val operation = operation(element.calleeName)?.value ?: return
val receiver = element.receiverExpression
element.replace(KtPsiFactory(element).createExpressionByPattern("$0$1", operation, receiver))
}
private fun isApplicableOperation(operation: KtSingleValueToken): Boolean = operation !in OperatorConventions.INCREMENT_OPERATIONS
private fun operation(functionName: String?): KtSingleValueToken? = functionName?.let {
OperatorConventions.UNARY_OPERATION_NAMES.inverse()[Name.identifier(it)]
}
}
| apache-2.0 | af7f269e18c8eece23bad4cf7175ac41 | 49.061224 | 158 | 0.794945 | 5.197034 | false | false | false | false |
hkokocin/androidKit | library/src/main/java/com/github/hkokocin/androidkit/widget/PageChangedListener.kt | 1 | 723 | package com.github.hkokocin.androidkit.widget
import android.support.v4.view.ViewPager
class PageChangedListener(
private val onPageSelected: (Int) -> Unit = {},
private val onPageScrollStateChanged: (Int) -> Unit = {},
private val onPageScrolled: (Int, Float, Int) -> Unit = {_, _, _ ->}
): ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int):Unit = onPageScrollStateChanged.invoke(state)
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
onPageScrolled.invoke(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int):Unit = onPageSelected.invoke(position)
} | mit | 3619609e6db2a81e98820537033bb2c0 | 41.588235 | 99 | 0.731674 | 4.918367 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/devkit/devkit-core/src/inspections/missingApi/SinceUntilRange.kt | 12 | 860 | // 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 org.jetbrains.idea.devkit.inspections.missingApi
import com.intellij.openapi.util.BuildNumber
import org.jetbrains.idea.devkit.DevKitBundle
/**
* Holds compatibility range of a plugin, consisting of [[sinceBuild]; [untilBuild]] build numbers.
*/
data class SinceUntilRange(val sinceBuild: BuildNumber?, val untilBuild: BuildNumber?) {
fun asString() = when {
sinceBuild != null && untilBuild != null -> sinceBuild.asString() + " - " + untilBuild.asString()
sinceBuild != null -> sinceBuild.asString() + "+"
untilBuild != null -> "1.0 - $untilBuild"
else -> DevKitBundle.message("inspections.missing.recent.api.since.until.range.all.builds")
}
override fun toString() = asString()
}
| apache-2.0 | 5af18146b54d0ca02311df5a3aa37520 | 39.952381 | 140 | 0.724419 | 3.944954 | false | false | false | false |
phylame/jem | mala/src/main/kotlin/mala/ixin/Commands.kt | 1 | 3008 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mala.ixin
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.*
interface CommandHandler {
fun handle(command: String, source: Any): Boolean
}
annotation class Command(val name: String = "")
class CommandDispatcher(proxies: Array<out Any> = emptyArray()) : CommandHandler {
private val handlers = LinkedList<CommandHandler>()
private val invocations = hashMapOf<String, Invocation>()
init {
register(proxies)
}
fun reset() {
handlers.clear()
invocations.clear()
}
fun register(vararg proxies: Any) {
for (proxy in proxies) {
proxy.javaClass.methods.filter {
!Modifier.isStatic(it.modifiers) && !Modifier.isAbstract(it.modifiers) && it.parameterTypes.let {
it.isEmpty() || it.first() == Any::class.java
}
}.forEach {
val command = it.getAnnotation(Command::class.java)
if (command != null) {
val invocation = Invocation(proxy, it)
synchronized(invocations) {
invocations.put(if (command.name.isNotEmpty()) command.name else it.name, invocation)
}
}
}
if (proxy is CommandHandler) {
synchronized(handlers) {
handlers += proxy
}
continue
}
}
}
override fun handle(command: String, source: Any): Boolean {
val invocation = invocations[command]
if (invocation != null) {
return invocation.invoke(command, source)
}
for (handler in handlers) {
if (handler.handle(command, source)) {
invocations[command] = Invocation(handler)
return true
}
}
return false
}
override fun toString() = "CommandDispatcher(handlers=$handlers, invocations=$invocations)"
private data class Invocation(val proxy: Any, val method: Method? = null) {
fun invoke(command: String, source: Any) = if (method != null) {
if (method.parameterCount == 0) method.invoke(proxy) else method.invoke(proxy, source)
true
} else (proxy as? CommandHandler)?.handle(command, source) == true
}
}
| apache-2.0 | 40b0a3c851634a4162fdc05872df777b | 32.422222 | 113 | 0.600066 | 4.620584 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/base/db/RoundRepository.kt | 1 | 1543 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.base.db
import androidx.room.RoomDatabase
import de.dreier.mytargets.base.db.dao.EndDAO
import de.dreier.mytargets.base.db.dao.RoundDAO
import de.dreier.mytargets.shared.models.augmented.AugmentedRound
import de.dreier.mytargets.shared.models.db.Round
class RoundRepository(val database: AppDatabase) {
private val roundDAO: RoundDAO = database.roundDAO()
private val endDAO: EndDAO = database.endDAO()
private val endRepository = EndRepository(endDAO)
fun loadAugmentedRound(id: Long) =
AugmentedRound(roundDAO.loadRound(id), endRepository.loadAugmentedEnds(id))
fun loadAugmentedRound(round: Round) =
AugmentedRound(round, endRepository.loadAugmentedEnds(round.id))
fun insertRound(round: AugmentedRound) {
database.runInTransaction {
roundDAO.insertRound(round.round, round.ends.map { it.end })
round.ends.forEach {
endDAO.insertCompleteEnd(it.end, it.images, it.shots)
}
}
}
}
| gpl-2.0 | e542210595494e565609300141b8b257 | 34.068182 | 83 | 0.729099 | 4.060526 | false | false | false | false |
vladmm/intellij-community | platform/vcs-log/graph/test/com/intellij/vcs/log/graph/impl/print/PrintElementGeneratorTest.kt | 2 | 4129 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.graph.impl.print
import com.intellij.util.NotNullFunction
import com.intellij.vcs.log.graph.AbstractTestWithTwoTextFile
import com.intellij.vcs.log.graph.api.elements.GraphEdge
import com.intellij.vcs.log.graph.api.elements.GraphElement
import com.intellij.vcs.log.graph.api.elements.GraphNode
import com.intellij.vcs.log.graph.api.printer.PrintElementManager
import com.intellij.vcs.log.graph.asString
import com.intellij.vcs.log.graph.impl.permanent.GraphLayoutBuilder
import com.intellij.vcs.log.graph.impl.print.elements.PrintElementWithGraphElement
import com.intellij.vcs.log.graph.parser.LinearGraphParser
import com.intellij.vcs.log.graph.utils.LinearGraphUtils
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.Comparator
public open class PrintElementGeneratorTest : AbstractTestWithTwoTextFile("elementGenerator") {
class TestPrintElementManager(private val myGraphElementComparator: Comparator<GraphElement>) : PrintElementManager {
override fun isSelected(printElement: PrintElementWithGraphElement): Boolean {
return false
}
override fun getColorId(element: GraphElement): Int {
if (element is GraphNode) {
return (element as GraphNode).getNodeIndex()
}
if (element is GraphEdge) {
val edge = element as GraphEdge
val normalEdge = LinearGraphUtils.asNormalEdge(edge)
if (normalEdge != null) return normalEdge!!.first + normalEdge!!.second
return LinearGraphUtils.getNotNullNodeIndex(edge)
}
throw IllegalStateException("Incorrect graph element type: " + element)
}
override fun getGraphElementComparator(): Comparator<GraphElement> {
return myGraphElementComparator
}
}
override fun runTest(`in`: String, out: String) {
runTest(`in`, out, 7, 2, 10)
}
private fun runTest(`in`: String, out: String, longEdgeSize: Int, visiblePartSize: Int, edgeWithArrowSize: Int) {
val graph = LinearGraphParser.parse(`in`)
val graphLayout = GraphLayoutBuilder.build(graph, object : Comparator<Int> {
override fun compare(o1: Int, o2: Int): Int {
return o1.compareTo(o2)
}
})
val graphElementComparator = GraphElementComparatorByLayoutIndex(object : NotNullFunction<Int, Int> {
override fun `fun`(nodeIndex: Int?): Int {
return graphLayout.getLayoutIndex(nodeIndex!!)
}
})
val elementManager = TestPrintElementManager(graphElementComparator)
val printElementGenerator = PrintElementGeneratorImpl(graph, elementManager, longEdgeSize, visiblePartSize, edgeWithArrowSize)
val actual = printElementGenerator.asString(graph.nodesCount())
assertEquals(out, actual)
}
@Test
public fun oneNode() {
doTest("oneNode")
}
@Test
public fun manyNodes() {
doTest("manyNodes")
}
@Test
public fun longEdges() {
doTest("longEdges")
}
@Test
public fun specialElements() {
doTest("specialElements")
}
// oneUpOneDown tests were created in order to investigate some arrow behavior in upsource
@Test
public fun oneUpOneDown1() {
val testName = "oneUpOneDown1"
runTest(loadText(testName + AbstractTestWithTwoTextFile.IN_POSTFIX), loadText(testName + AbstractTestWithTwoTextFile.OUT_POSTFIX), 7, 1, 10)
}
@Test
public fun oneUpOneDown2() {
val testName = "oneUpOneDown2"
runTest(loadText(testName + AbstractTestWithTwoTextFile.IN_POSTFIX), loadText(testName + AbstractTestWithTwoTextFile.OUT_POSTFIX), 10, 1, 10)
}
}
| apache-2.0 | 23340e6b2afff6ec0ef17fa7a346bbbf | 34.904348 | 145 | 0.742795 | 4.020448 | false | true | false | false |
paplorinc/intellij-community | platform/platform-api/src/com/intellij/credentialStore/OneTimeString.kt | 2 | 3880 | // 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.credentialStore
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.ExceptionUtil
import com.intellij.util.io.toByteArray
import com.intellij.util.text.CharArrayCharSequence
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.CodingErrorAction
import java.util.concurrent.atomic.AtomicReference
/**
* clearable only if specified explicitly.
*
* Case
* 1) you create OneTimeString manually on user input.
* 2) you store it in CredentialStore
* 3) you consume it... BUT native credentials store do not store credentials immediately - write is postponed, so, will be an critical error.
*
* so, currently - only credentials store implementations should set this flag on get.
*/
@Suppress("EqualsOrHashCode")
class OneTimeString @JvmOverloads constructor(value: CharArray, offset: Int = 0, length: Int = value.size, private var clearable: Boolean = false) : CharArrayCharSequence(value, offset, offset + length) {
private val consumed = AtomicReference<String?>()
constructor(value: String): this(value.toCharArray())
private fun consume(willBeCleared: Boolean) {
if (!clearable) {
return
}
if (!willBeCleared) {
consumed.get()?.let { throw IllegalStateException("Already consumed: $it\n---\n") }
}
else if (!consumed.compareAndSet(null, ExceptionUtil.currentStackTrace())) {
throw IllegalStateException("Already consumed at ${consumed.get()}")
}
}
fun toString(clear: Boolean = false): String {
consume(clear)
val result = super.toString()
clear()
return result
}
// string will be cleared and not valid after
@JvmOverloads
fun toByteArray(clear: Boolean = true): ByteArray {
consume(clear)
val result = Charsets.UTF_8.encode(CharBuffer.wrap(myChars, myStart, length))
if (clear) {
clear()
}
return result.toByteArray()
}
private fun clear() {
if (clearable) {
myChars.fill('\u0000', myStart, myEnd)
}
}
@JvmOverloads
fun toCharArray(clear: Boolean = true): CharArray {
consume(clear)
if (clear) {
val result = CharArray(length)
getChars(result, 0)
clear()
return result
}
else {
return chars
}
}
fun clone(clear: Boolean, clearable: Boolean) = OneTimeString(toCharArray(clear), clearable = clearable)
override fun equals(other: Any?): Boolean {
if (other is CharSequence) {
return StringUtil.equals(this, other)
}
return super.equals(other)
}
fun appendTo(builder: StringBuilder) {
consume(false)
builder.append(myChars, myStart, length)
}
}
@Suppress("FunctionName")
@JvmOverloads
fun OneTimeString(value: ByteArray, offset: Int = 0, length: Int = value.size - offset, clearable: Boolean = false): OneTimeString {
if (length == 0) {
return OneTimeString(ArrayUtil.EMPTY_CHAR_ARRAY)
}
// jdk decodes to heap array, but since this code is very critical, we cannot rely on it, so, we don't use Charsets.UTF_8.decode()
val charsetDecoder = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)
val charArray = CharArray((value.size * charsetDecoder.maxCharsPerByte().toDouble()).toInt())
charsetDecoder.reset()
val charBuffer = CharBuffer.wrap(charArray)
var cr = charsetDecoder.decode(ByteBuffer.wrap(value, offset, length), charBuffer, true)
if (!cr.isUnderflow) {
cr.throwException()
}
cr = charsetDecoder.flush(charBuffer)
if (!cr.isUnderflow) {
cr.throwException()
}
value.fill(0, offset, offset + length)
return OneTimeString(charArray, 0, charBuffer.position(), clearable = clearable)
} | apache-2.0 | 2b967a84e71731ba1d8780596137bfb6 | 31.341667 | 204 | 0.71366 | 4.067086 | false | false | false | false |
bradylangdale/IntrepidClient | Client Files/IntrepidClient/src/main/kotlin/org/abendigo/plugin/csgo/TriggerBotPlugin.kt | 1 | 710 | package org.abendigo.plugin.csgo
import org.abendigo.DEBUG
import org.abendigo.csgo.*
import org.abendigo.csgo.offsets.m_dwForceAttack
import org.abendigo.csgo.Client.clientDLL
import org.abendigo.csgo.Client.enemies
import org.abendigo.plugin.sleep
object TriggerBotPlugin : InGamePlugin("Trigger Bot", duration = 1) {
override fun cycle() {
for ((i, e) in enemies) {
try {
val weapon = (+Me().weapon).type!!
if (weapon.knife || weapon.grenade) return
} catch (t: Throwable) {
if (DEBUG) t.printStackTrace()
}
if (e.address == +Me.targetAddress) {
clientDLL[m_dwForceAttack] = 5.toByte()
sleep(10)
clientDLL[m_dwForceAttack] = 4.toByte()
}
}
}
} | gpl-3.0 | 43ecd38a41d2aa643349918755847871 | 21.21875 | 69 | 0.676056 | 3.127753 | false | false | false | false |
JetBrains/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/actions/ReaderModeListener.kt | 1 | 3386 | // 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.codeInsight.actions
import com.intellij.application.options.colors.ReaderModeStatsCollector
import com.intellij.codeInsight.actions.ReaderModeSettingsListener.Companion.applyToAllEditors
import com.intellij.ide.DataManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions
import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.options.ex.Settings
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectPostStartupActivity
import com.intellij.util.messages.Topic
import java.beans.PropertyChangeListener
import java.util.*
internal interface ReaderModeListener : EventListener {
fun modeChanged(project: Project)
}
class ReaderModeSettingsListener : ReaderModeListener {
companion object {
@Topic.ProjectLevel
@JvmField
internal val TOPIC = Topic(ReaderModeListener::class.java, Topic.BroadcastDirection.NONE)
fun applyToAllEditors(project: Project) {
for (editor in FileEditorManager.getInstance(project).allEditors) {
if (editor is TextEditor) {
ReaderModeSettings.applyReaderMode(project, editor.editor, editor.file, fileIsOpenAlready = true)
}
}
EditorFactory.getInstance().allEditors.forEach {
if (it !is EditorImpl) return@forEach
if (it.getProject() != project) return@forEach
ReaderModeSettings.applyReaderMode(project, it, FileDocumentManager.getInstance().getFile(it.document), fileIsOpenAlready = true)
}
}
fun goToEditorReaderMode() {
DataManager.getInstance().dataContextFromFocusAsync.onSuccess { context ->
context?.let { dataContext ->
Settings.KEY.getData(dataContext)?.let { settings ->
settings.select(settings.find("editor.reader.mode"))
ReaderModeStatsCollector.logSeeAlsoNavigation()
}
}
}
}
}
override fun modeChanged(project: Project) {
if (!project.isDefault) {
applyToAllEditors(project)
}
}
}
private class ReaderModeEditorSettingsListener : ProjectPostStartupActivity {
override suspend fun execute(project: Project) {
val propertyChangeListener = PropertyChangeListener { event ->
when (event.propertyName) {
EditorSettingsExternalizable.PROP_DOC_COMMENT_RENDERING -> {
ReaderModeSettings.getInstance(project).showRenderedDocs = EditorSettingsExternalizable.getInstance().isDocCommentRenderingEnabled
applyToAllEditors(project)
}
}
}
EditorSettingsExternalizable.getInstance().addPropertyChangeListener(propertyChangeListener, project)
val fontPreferences = AppEditorFontOptions.getInstance().fontPreferences as FontPreferencesImpl
fontPreferences.addChangeListener({
ReaderModeSettings.getInstance(project).showLigatures = fontPreferences.useLigatures()
applyToAllEditors(project)
}, project)
}
} | apache-2.0 | 732718b6e13de6a2a0360895eb3b3cf3 | 39.807229 | 140 | 0.767277 | 4.886003 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/applicators/AbstractKotlinApplicatorBasedInspection.kt | 1 | 4820 | // 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.codeinsight.api.applicators
import com.intellij.codeInspection.*
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.codeInspection.util.IntentionName
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.analyzeWithReadAction
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtVisitorVoid
import kotlin.reflect.KClass
@Deprecated("Please don't use this for new inspections. Use `KotlinApplicableInspection` or `KotlinApplicableInspectionWithContext` instead.")
abstract class AbstractKotlinApplicatorBasedInspection<PSI : KtElement, INPUT : KotlinApplicatorInput>(
val elementType: KClass<PSI>
) : AbstractKotlinInspection() {
final override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
super.visitKtElement(element)
if (!elementType.isInstance(element) || element.textLength == 0) return
@Suppress("UNCHECKED_CAST")
visitTargetElement(element as PSI, holder, isOnTheFly)
}
}
private fun visitTargetElement(element: PSI, holder: ProblemsHolder, isOnTheFly: Boolean) {
val applicator = getApplicator()
if (!applicator.isApplicableByPsi(element, holder.project)) return
val targets = getApplicabilityRange().getApplicabilityRanges(element)
if (targets.isEmpty()) return
val input = getInput(element) ?: return
require(input.isValidFor(element)) { "Input should be valid after creation" }
registerProblems(applicator, holder, element, targets, isOnTheFly, input)
}
private fun registerProblems(
applicator: KotlinApplicator<PSI, INPUT>,
holder: ProblemsHolder,
element: PSI,
ranges: List<TextRange>,
isOnTheFly: Boolean,
input: INPUT
) {
val description = applicator.getActionName(element, input)
val fix = applicator.asLocalQuickFix(input, actionName = applicator.getActionName(element, input))
ranges.forEach { range ->
registerProblem(holder, element, range, description, isOnTheFly, fix)
}
}
private fun registerProblem(
holder: ProblemsHolder,
element: PSI,
range: TextRange,
@InspectionMessage description: String,
isOnTheFly: Boolean,
fix: LocalQuickFix
) {
with(holder) {
val problemDescriptor = manager.createProblemDescriptor(
element,
range,
description,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
fix
)
registerProblem(problemDescriptor)
}
}
@OptIn(KtAllowAnalysisOnEdt::class)
private fun getInput(element: PSI): INPUT? = allowAnalysisOnEdt {
analyzeWithReadAction(element) {
with(getInputProvider()) { provideInput(element) }
}
}
abstract fun getApplicabilityRange(): KotlinApplicabilityRange<PSI>
abstract fun getInputProvider(): KotlinApplicatorInputProvider<PSI, INPUT>
abstract fun getApplicator(): KotlinApplicator<PSI, INPUT>
}
private fun <PSI : PsiElement, INPUT : KotlinApplicatorInput> KotlinApplicator<PSI, INPUT>.asLocalQuickFix(
input: INPUT,
@IntentionName actionName: String,
): LocalQuickFix = object : LocalQuickFix {
override fun startInWriteAction() = false
override fun getElementToMakeWritable(currentFile: PsiFile) = currentFile
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
@Suppress("UNCHECKED_CAST")
val element = descriptor.psiElement as PSI
if (isApplicableByPsi(element, project) && input.isValidFor(element)) {
runWriteActionIfPhysical(element) {
applyTo(element, input, project, element.findExistingEditor())
}
}
}
override fun getFamilyName() = [email protected]()
override fun getName() = actionName
}
| apache-2.0 | 76bed41b8c9882d9053c55d592c8c4e8 | 38.834711 | 142 | 0.706224 | 5.205184 | false | false | false | false |
aohanyao/CodeMall | code/ServerCode/CodeMallServer/src/main/java/com/jjc/mailshop/service/imp/AddressServiceImp.kt | 1 | 3117 | package com.jjc.mailshop.service.imp
import com.github.pagehelper.PageHelper
import com.github.pagehelper.PageInfo
import com.jjc.mailshop.common.ServerResponse
import com.jjc.mailshop.dao.ShippingMapper
import com.jjc.mailshop.pojo.Shipping
import com.jjc.mailshop.service.IAddressService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
/**
* Created by Administrator on 2017/6/15 0015.
*/
@Service(value = "iAddressService")
class AddressServiceImp : IAddressService {
@Autowired
var mShippingMapper: ShippingMapper? = null
override fun createAddress(shipping: Shipping): ServerResponse<Shipping> {
//调用接口插入数据
if (mShippingMapper!!.insertSelective(shipping) > 0) {
//返回当前数据
return ServerResponse.createBySuccess("新增成功", shipping)
}
return ServerResponse.createByErrorMessage("新增失败")
}
override fun updateAddress(shipping: Shipping, userId: Int): ServerResponse<Shipping> {
//查询地址详情
val addressDetails = getAddressDetails(shipping.id, userId)
//不成功
if (!addressDetails.isSuccess) {
return ServerResponse.createByErrorMessage(addressDetails.message)
}
//调用 修改数据
if (mShippingMapper!!.updateByPrimaryKeySelective(shipping) > 0) {
return ServerResponse.createBySuccessMessage("修改成功")
}
return ServerResponse.createByErrorMessage("修改失败")
}
override fun deleteAddress(shippingId: Int, userId: Int): ServerResponse<String> {
//查询地址详情
val addressDetails = getAddressDetails(shippingId, userId)
//不成功
if (!addressDetails.isSuccess) {
return ServerResponse.createByErrorMessage(addressDetails.message)
}
//调用 删除数据
if (mShippingMapper!!.deleteByPrimaryKey(shippingId) > 0) {
return ServerResponse.createBySuccessMessage("删除成功")
}
return ServerResponse.createByErrorMessage("删除失败")
}
override fun getAddressDetails(shippingId: Int, userId: Int): ServerResponse<Shipping> {
//查询数据
val addressDetails = mShippingMapper!!.selectByPrimaryKey(shippingId) ?: return ServerResponse.createByErrorMessage("找不到该地址")
//判断是不是当前用户的
if (addressDetails.userId != userId) {
return ServerResponse.createByErrorMessage("查询不到该地址")
}
return ServerResponse.createBySuccess("查询成功", addressDetails)
}
override fun getAddressList(userId: String, pageIndex: Int, pageSize: Int): ServerResponse<PageInfo<Shipping>> {
//设置分页
PageHelper.startPage<Shipping>(pageIndex, pageSize)
//调用 查询数据
val pageInfo: PageInfo<Shipping> = PageInfo(mShippingMapper!!.selectByUserId(userId))
//返回数据
return ServerResponse.createBySuccess("查询成功", pageInfo)
}
} | apache-2.0 | f0d1a56d35246818302a1304513076bb | 33.746988 | 133 | 0.694069 | 4.415008 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/processings/inspectionLikeProcessings.kt | 1 | 22982 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.j2k.post.processing.processings
import com.intellij.openapi.application.runWriteAction
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.utils.isRedundantGetter
import org.jetbrains.kotlin.idea.codeinsight.utils.isRedundantSetter
import org.jetbrains.kotlin.idea.codeinsight.utils.removeRedundantGetter
import org.jetbrains.kotlin.idea.codeinsight.utils.removeRedundantSetter
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.inspections.*
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeArgumentsIntention
import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeIntention
import org.jetbrains.kotlin.idea.intentions.addUseSiteTarget
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils
import org.jetbrains.kotlin.idea.j2k.post.processing.InspectionLikeProcessingForElement
import org.jetbrains.kotlin.idea.quickfix.AddConstModifierFix
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.j2k.ConverterSettings
import org.jetbrains.kotlin.j2k.isInSingleLine
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class RemoveExplicitPropertyTypeProcessing : InspectionLikeProcessingForElement<KtProperty>(KtProperty::class.java) {
override fun isApplicableTo(element: KtProperty, settings: ConverterSettings?): Boolean {
val typeReference = element.typeReference
if (typeReference == null || typeReference.annotationEntries.isNotEmpty()) return false
val needFieldTypes = settings?.specifyFieldTypeByDefault == true
val needLocalVariablesTypes = settings?.specifyLocalVariableTypeByDefault == true
if (needLocalVariablesTypes && element.isLocal) return false
if (needFieldTypes && element.isMember) return false
val initializer = element.initializer ?: return false
val withoutExpectedType =
initializer.analyzeInContext(initializer.getResolutionScope()).getType(initializer) ?: return false
val typeBeDescriptor = element.resolveToDescriptorIfAny().safeAs<CallableDescriptor>()?.returnType ?: return false
return KotlinTypeChecker.DEFAULT.equalTypes(withoutExpectedType, typeBeDescriptor)
}
override fun apply(element: KtProperty) {
val typeReference = element.typeReference ?: return
element.colon?.let { colon ->
val followingWhiteSpace = colon.nextSibling?.takeIf { following ->
following is PsiWhiteSpace && following.isInSingleLine()
}
followingWhiteSpace?.delete()
colon.delete()
}
typeReference.delete()
}
}
internal class RemoveRedundantNullabilityProcessing : InspectionLikeProcessingForElement<KtProperty>(KtProperty::class.java) {
override fun isApplicableTo(element: KtProperty, settings: ConverterSettings?): Boolean {
if (!element.isLocal) return false
val typeReference = element.typeReference
if (typeReference == null || typeReference.typeElement !is KtNullableType) return false
val initializerType = element.initializer?.let {
it.analyzeInContext(element.getResolutionScope()).getType(it)
}
if (initializerType?.isNullable() == true) return false
return ReferencesSearch.search(element, element.useScope).findAll().mapNotNull { ref ->
val parent = (ref.element.parent as? KtExpression)?.asAssignment()
parent?.takeIf { it.left == ref.element }
}.all {
val right = it.right
val withoutExpectedType = right?.analyzeInContext(element.getResolutionScope())
withoutExpectedType?.getType(right)?.isNullable() == false
}
}
override fun apply(element: KtProperty) {
val typeElement = element.typeReference?.typeElement
typeElement?.replace(typeElement.safeAs<KtNullableType>()?.innerType ?: return)
}
}
internal class RemoveExplicitTypeArgumentsProcessing :
InspectionLikeProcessingForElement<KtTypeArgumentList>(KtTypeArgumentList::class.java) {
override fun isApplicableTo(element: KtTypeArgumentList, settings: ConverterSettings?): Boolean =
RemoveExplicitTypeArgumentsIntention.isApplicableTo(element, approximateFlexible = true)
override fun apply(element: KtTypeArgumentList) {
element.delete()
}
}
// the types arguments for Stream.collect calls cannot be explicitly specified in Kotlin,
// but we need them in nullability inference, so we remove it here
internal class RemoveJavaStreamsCollectCallTypeArgumentsProcessing :
InspectionLikeProcessingForElement<KtCallExpression>(KtCallExpression::class.java) {
override fun isApplicableTo(element: KtCallExpression, settings: ConverterSettings?): Boolean {
if (element.typeArgumentList == null) return false
if (element.calleeExpression?.text != COLLECT_FQ_NAME.shortName().identifier) return false
return element.isCalling(COLLECT_FQ_NAME)
}
override fun apply(element: KtCallExpression) {
element.typeArgumentList?.delete()
}
companion object {
private val COLLECT_FQ_NAME = FqName("java.util.stream.Stream.collect")
}
}
internal class RemoveRedundantOverrideVisibilityProcessing :
InspectionLikeProcessingForElement<KtCallableDeclaration>(KtCallableDeclaration::class.java) {
override fun isApplicableTo(element: KtCallableDeclaration, settings: ConverterSettings?): Boolean {
if (!element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false
return element.visibilityModifier() != null
}
override fun apply(element: KtCallableDeclaration) {
val modifier = element.visibilityModifierType() ?: return
element.setVisibility(modifier)
}
}
internal class ReplaceGetterBodyWithSingleReturnStatementWithExpressionBody :
InspectionLikeProcessingForElement<KtPropertyAccessor>(KtPropertyAccessor::class.java) {
private fun KtPropertyAccessor.singleBodyStatementExpression() =
bodyBlockExpression?.statements
?.singleOrNull()
?.safeAs<KtReturnExpression>()
?.takeIf { it.labeledExpression == null }
?.returnedExpression
override fun isApplicableTo(element: KtPropertyAccessor, settings: ConverterSettings?): Boolean {
if (!element.isGetter) return false
return element.singleBodyStatementExpression() != null
}
override fun apply(element: KtPropertyAccessor) {
val body = element.bodyExpression ?: return
val returnedExpression = element.singleBodyStatementExpression() ?: return
val commentSaver = CommentSaver(body)
element.addBefore(KtPsiFactory(element.project).createEQ(), body)
val newBody = body.replaced(returnedExpression)
commentSaver.restore(newBody)
}
}
internal class RemoveRedundantCastToNullableProcessing :
InspectionLikeProcessingForElement<KtBinaryExpressionWithTypeRHS>(KtBinaryExpressionWithTypeRHS::class.java) {
override fun isApplicableTo(element: KtBinaryExpressionWithTypeRHS, settings: ConverterSettings?): Boolean {
if (element.right?.typeElement !is KtNullableType) return false
val context = element.analyze()
val leftType = context.getType(element.left) ?: return false
val rightType = context.get(BindingContext.TYPE, element.right) ?: return false
return !leftType.isMarkedNullable && rightType.isMarkedNullable
}
override fun apply(element: KtBinaryExpressionWithTypeRHS) {
val type = element.right?.typeElement as? KtNullableType ?: return
type.replace(type.innerType ?: return)
}
}
internal class RemoveRedundantSamAdaptersProcessing :
InspectionLikeProcessingForElement<KtCallExpression>(KtCallExpression::class.java) {
override val writeActionNeeded = false
override fun isApplicableTo(element: KtCallExpression, settings: ConverterSettings?): Boolean =
RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element).isNotEmpty()
override fun apply(element: KtCallExpression) {
val callsToBeConverted = RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element)
runWriteAction {
for (call in callsToBeConverted) {
RedundantSamConstructorInspection.replaceSamConstructorCall(call)
}
}
}
}
internal class UninitializedVariableReferenceFromInitializerToThisReferenceProcessing :
InspectionLikeProcessingForElement<KtSimpleNameExpression>(KtSimpleNameExpression::class.java) {
override fun isApplicableTo(element: KtSimpleNameExpression, settings: ConverterSettings?): Boolean {
val anonymousObject = element.getStrictParentOfType<KtClassOrObject>()?.takeIf { it.name == null } ?: return false
val resolved = element.mainReference.resolve() ?: return false
if (resolved.isAncestor(element, strict = true)) {
if (resolved is KtVariableDeclaration && resolved.hasInitializer()) {
if (resolved.initializer?.getChildOfType<KtClassOrObject>() == anonymousObject) {
return true
}
}
}
return false
}
override fun apply(element: KtSimpleNameExpression) {
element.replaced(KtPsiFactory(element.project).createThisExpression())
}
}
internal class UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing :
InspectionLikeProcessingForElement<KtSimpleNameExpression>(KtSimpleNameExpression::class.java) {
override fun isApplicableTo(element: KtSimpleNameExpression, settings: ConverterSettings?): Boolean {
val anonymousObject = element.getStrictParentOfType<KtClassOrObject>() ?: return false
val variable = anonymousObject.getStrictParentOfType<KtVariableDeclaration>() ?: return false
if (variable.nameAsName != element.getReferencedNameAsName()) return false
if (variable.initializer?.getChildOfType<KtClassOrObject>() != anonymousObject) return false
return element.mainReference.resolve() == null
}
override fun apply(element: KtSimpleNameExpression) {
element.replaced(KtPsiFactory(element.project).createThisExpression())
}
}
internal class VarToValProcessing : InspectionLikeProcessingForElement<KtProperty>(KtProperty::class.java) {
private fun KtProperty.hasWriteUsages(): Boolean =
ReferencesSearch.search(this, useScope).any { usage ->
(usage as? KtSimpleNameReference)?.element?.let { nameReference ->
val receiver = nameReference.parent?.safeAs<KtDotQualifiedExpression>()?.receiverExpression
if (nameReference.getStrictParentOfType<KtAnonymousInitializer>() != null
&& (receiver == null || receiver is KtThisExpression)
) return@let false
nameReference.readWriteAccess(useResolveForReadWrite = true).isWrite
} == true
}
override fun isApplicableTo(element: KtProperty, settings: ConverterSettings?): Boolean {
if (!element.isVar) return false
if (!element.isPrivate()) return false
val descriptor = element.resolveToDescriptorIfAny() ?: return false
if (descriptor.overriddenDescriptors.any { it.safeAs<VariableDescriptor>()?.isVar == true }) return false
return !element.hasWriteUsages()
}
override fun apply(element: KtProperty) {
val psiFactory = KtPsiFactory(element.project)
element.valOrVarKeyword.replace(psiFactory.createValKeyword())
}
}
internal class JavaObjectEqualsToEqOperatorProcessing : InspectionLikeProcessingForElement<KtCallExpression>(KtCallExpression::class.java) {
companion object {
val CALL_FQ_NAME = FqName("java.util.Objects.equals")
}
override fun isApplicableTo(element: KtCallExpression, settings: ConverterSettings?): Boolean {
if (element.calleeExpression?.text != CALL_FQ_NAME.shortName().identifier) return false
if (element.valueArguments.size != 2) return false
if (element.valueArguments.any { it.getArgumentExpression() == null }) return false
return element.isCalling(CALL_FQ_NAME)
}
override fun apply(element: KtCallExpression) {
val psiFactory = KtPsiFactory(element.project)
element.getQualifiedExpressionForSelectorOrThis().replace(
psiFactory.createExpressionByPattern(
"($0 == $1)",
element.valueArguments[0].getArgumentExpression() ?: return,
element.valueArguments[1].getArgumentExpression() ?: return
)
)
}
}
internal class RemoveForExpressionLoopParameterTypeProcessing :
InspectionLikeProcessingForElement<KtForExpression>(KtForExpression::class.java) {
override fun isApplicableTo(element: KtForExpression, settings: ConverterSettings?): Boolean {
val typeReference = element.loopParameter?.typeReference ?: return false
return (typeReference.annotationEntries.isEmpty()
&& typeReference.typeElement != null
&& settings?.specifyLocalVariableTypeByDefault != true)
}
override fun apply(element: KtForExpression) {
element.loopParameter?.typeReference = null
}
}
internal class RemoveRedundantConstructorKeywordProcessing :
InspectionLikeProcessingForElement<KtPrimaryConstructor>(KtPrimaryConstructor::class.java) {
override fun isApplicableTo(element: KtPrimaryConstructor, settings: ConverterSettings?): Boolean =
element.containingClassOrObject is KtClass
&& element.getConstructorKeyword() != null
&& element.annotationEntries.isEmpty()
&& element.visibilityModifier() == null
override fun apply(element: KtPrimaryConstructor) {
element.getConstructorKeyword()?.delete()
element.prevSibling
?.safeAs<PsiWhiteSpace>()
?.takeUnless { it.textContains('\n') }
?.delete()
}
}
internal class RemoveRedundantModalityModifierProcessing : InspectionLikeProcessingForElement<KtDeclaration>(KtDeclaration::class.java) {
override fun isApplicableTo(element: KtDeclaration, settings: ConverterSettings?): Boolean {
if (element.hasModifier(KtTokens.FINAL_KEYWORD)) {
return !element.hasModifier(KtTokens.OVERRIDE_KEYWORD)
}
val modalityModifierType = element.modalityModifierType() ?: return false
return modalityModifierType == element.implicitModality()
}
override fun apply(element: KtDeclaration) {
element.removeModifier(element.modalityModifierType() ?: return)
}
}
internal class RemoveRedundantVisibilityModifierProcessing : InspectionLikeProcessingForElement<KtDeclaration>(KtDeclaration::class.java) {
override fun isApplicableTo(element: KtDeclaration, settings: ConverterSettings?) = when {
element.hasModifier(KtTokens.PUBLIC_KEYWORD) && element.hasModifier(KtTokens.OVERRIDE_KEYWORD) ->
false
element.hasModifier(KtTokens.INTERNAL_KEYWORD) && element.containingClassOrObject?.isLocal == true ->
true
element.visibilityModifierType() == element.implicitVisibility() ->
true
else -> false
}
override fun apply(element: KtDeclaration) {
element.removeModifier(element.visibilityModifierType() ?: return)
}
}
internal class RemoveExplicitOpenInInterfaceProcessing : InspectionLikeProcessingForElement<KtClass>(KtClass::class.java) {
override fun isApplicableTo(element: KtClass, settings: ConverterSettings?): Boolean =
element.isValid
&& element.isInterface()
&& element.hasModifier(KtTokens.OPEN_KEYWORD)
override fun apply(element: KtClass) {
element.removeModifier(KtTokens.OPEN_KEYWORD)
}
}
internal class MoveGetterAndSetterAnnotationsToPropertyProcessing : InspectionLikeProcessingForElement<KtProperty>(KtProperty::class.java) {
override fun isApplicableTo(element: KtProperty, settings: ConverterSettings?): Boolean =
element.accessors.isNotEmpty()
override fun apply(element: KtProperty) {
for (accessor in element.accessors.sortedBy { it.isGetter }) {
for (entry in accessor.annotationEntries) {
element.addAnnotationEntry(entry).also {
it.addUseSiteTarget(
if (accessor.isGetter) AnnotationUseSiteTarget.PROPERTY_GETTER
else AnnotationUseSiteTarget.PROPERTY_SETTER,
element.project
)
}
}
accessor.annotationEntries.forEach { it.delete() }
}
}
}
internal class RedundantExplicitTypeInspectionBasedProcessing : InspectionLikeProcessingForElement<KtProperty>(KtProperty::class.java) {
override fun isApplicableTo(element: KtProperty, settings: ConverterSettings?): Boolean =
RedundantExplicitTypeInspection.hasRedundantType(element)
override fun apply(element: KtProperty) {
element.typeReference = null
RemoveExplicitTypeIntention.removeExplicitType(element)
}
}
internal class CanBeValInspectionBasedProcessing : InspectionLikeProcessingForElement<KtDeclaration>(KtDeclaration::class.java) {
override fun isApplicableTo(element: KtDeclaration, settings: ConverterSettings?): Boolean =
CanBeValInspection.canBeVal(element, ignoreNotUsedVals = false)
override fun apply(element: KtDeclaration) {
val project = element.project
if (element !is KtValVarKeywordOwner) return
element.valOrVarKeyword?.replace(KtPsiFactory(project).createValKeyword())
}
}
internal class MayBeConstantInspectionBasedProcessing : InspectionLikeProcessingForElement<KtProperty>(KtProperty::class.java) {
override fun isApplicableTo(element: KtProperty, settings: ConverterSettings?): Boolean =
with(MayBeConstantInspection) {
val status = element.getStatus()
status == MayBeConstantInspection.Status.MIGHT_BE_CONST
|| status == MayBeConstantInspection.Status.JVM_FIELD_MIGHT_BE_CONST
}
override fun apply(element: KtProperty) {
AddConstModifierFix.addConstModifier(element)
}
}
internal class RemoveExplicitGetterInspectionBasedProcessing :
InspectionLikeProcessingForElement<KtPropertyAccessor>(KtPropertyAccessor::class.java) {
override fun isApplicableTo(element: KtPropertyAccessor, settings: ConverterSettings?): Boolean =
element.isRedundantGetter()
override fun apply(element: KtPropertyAccessor) {
removeRedundantGetter(element)
}
}
internal class RemoveExplicitSetterInspectionBasedProcessing :
InspectionLikeProcessingForElement<KtPropertyAccessor>(KtPropertyAccessor::class.java) {
override fun isApplicableTo(element: KtPropertyAccessor, settings: ConverterSettings?): Boolean =
element.isRedundantSetter()
override fun apply(element: KtPropertyAccessor) {
removeRedundantSetter(element)
}
}
internal class ExplicitThisInspectionBasedProcessing :
InspectionLikeProcessingForElement<KtExpression>(KtExpression::class.java) {
override fun isApplicableTo(element: KtExpression, settings: ConverterSettings?): Boolean =
ExplicitThisInspection.hasExplicitThis(element)
override fun apply(element: KtExpression) {
ExplicitThisExpressionFix.removeExplicitThisExpression(
with(ExplicitThisInspection) {
element.thisAsReceiverOrNull() ?: return
}
)
}
}
internal class LiftReturnInspectionBasedProcessing :
InspectionLikeProcessingForElement<KtExpression>(KtExpression::class.java) {
override fun isApplicableTo(element: KtExpression, settings: ConverterSettings?): Boolean =
LiftReturnOrAssignmentInspection.getState(element, false)?.any {
it.liftType == LiftReturnOrAssignmentInspection.Companion.LiftType.LIFT_RETURN_OUT
} ?: false
override fun apply(element: KtExpression) {
BranchedFoldingUtils.foldToReturn(element)
}
}
internal class LiftAssignmentInspectionBasedProcessing :
InspectionLikeProcessingForElement<KtExpression>(KtExpression::class.java) {
override fun isApplicableTo(element: KtExpression, settings: ConverterSettings?): Boolean =
LiftReturnOrAssignmentInspection.getState(element, false)?.any {
it.liftType == LiftReturnOrAssignmentInspection.Companion.LiftType.LIFT_ASSIGNMENT_OUT
} ?: false
override fun apply(element: KtExpression) {
BranchedFoldingUtils.tryFoldToAssignment(element)
}
}
internal class MoveLambdaOutsideParenthesesProcessing :
InspectionLikeProcessingForElement<KtCallExpression>(KtCallExpression::class.java) {
override fun isApplicableTo(element: KtCallExpression, settings: ConverterSettings?): Boolean =
element.canMoveLambdaOutsideParentheses()
override fun apply(element: KtCallExpression) {
element.moveFunctionLiteralOutsideParentheses()
}
}
internal class RemoveOpenModifierOnTopLevelDeclarationsProcessing :
InspectionLikeProcessingForElement<KtDeclaration>(KtDeclaration::class.java) {
override fun isApplicableTo(element: KtDeclaration, settings: ConverterSettings?): Boolean =
element.hasModifier(KtTokens.OPEN_KEYWORD)
&& (element is KtFunction || element is KtProperty)
&& element.parent is KtFile
override fun apply(element: KtDeclaration) {
element.removeModifier(KtTokens.OPEN_KEYWORD)
}
}
| apache-2.0 | d345df978606e31644028212be4de518 | 44.780876 | 140 | 0.738099 | 5.598538 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/FeederApplication.kt | 1 | 7602 | package com.nononsenseapps.feeder
import android.app.Application
import android.content.ContentResolver
import android.content.SharedPreferences
import android.os.Build.VERSION.SDK_INT
import android.widget.Toast
import androidx.core.app.NotificationManagerCompat
import androidx.preference.PreferenceManager
import androidx.work.WorkManager
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.decode.SvgDecoder
import coil.disk.DiskCache
import com.jakewharton.threetenabp.AndroidThreeTen
import com.nononsenseapps.feeder.archmodel.Repository
import com.nononsenseapps.feeder.db.room.AppDatabase
import com.nononsenseapps.feeder.db.room.FeedDao
import com.nononsenseapps.feeder.db.room.FeedItemDao
import com.nononsenseapps.feeder.db.room.ReadStatusSyncedDao
import com.nononsenseapps.feeder.db.room.RemoteFeedDao
import com.nononsenseapps.feeder.db.room.RemoteReadMarkDao
import com.nononsenseapps.feeder.db.room.SyncDeviceDao
import com.nononsenseapps.feeder.db.room.SyncRemoteDao
import com.nononsenseapps.feeder.di.androidModule
import com.nononsenseapps.feeder.di.archModelModule
import com.nononsenseapps.feeder.di.networkModule
import com.nononsenseapps.feeder.model.TTSStateHolder
import com.nononsenseapps.feeder.model.UserAgentInterceptor
import com.nononsenseapps.feeder.notifications.NotificationsWorker
import com.nononsenseapps.feeder.ui.compose.coil.TooLargeImageInterceptor
import com.nononsenseapps.feeder.util.ToastMaker
import com.nononsenseapps.feeder.util.currentlyUnmetered
import com.nononsenseapps.jsonfeed.cachingHttpClient
import java.io.File
import java.security.Security
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.withContext
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.OkHttpClient
import org.conscrypt.Conscrypt
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.bind
import org.kodein.di.direct
import org.kodein.di.instance
import org.kodein.di.singleton
@Suppress("unused")
class FeederApplication : Application(), DIAware, ImageLoaderFactory {
private val applicationCoroutineScope = ApplicationCoroutineScope()
private val ttsStateHolder = TTSStateHolder(this, applicationCoroutineScope)
override val di by DI.lazy {
// import(androidXModule(this@FeederApplication))
bind<Application>() with singleton { this@FeederApplication }
bind<AppDatabase>() with singleton { AppDatabase.getInstance(this@FeederApplication) }
bind<FeedDao>() with singleton { instance<AppDatabase>().feedDao() }
bind<FeedItemDao>() with singleton { instance<AppDatabase>().feedItemDao() }
bind<SyncRemoteDao>() with singleton { instance<AppDatabase>().syncRemoteDao() }
bind<ReadStatusSyncedDao>() with singleton { instance<AppDatabase>().readStatusSyncedDao() }
bind<RemoteReadMarkDao>() with singleton { instance<AppDatabase>().remoteReadMarkDao() }
bind<RemoteFeedDao>() with singleton { instance<AppDatabase>().remoteFeedDao() }
bind<SyncDeviceDao>() with singleton { instance<AppDatabase>().syncDeviceDao() }
import(androidModule)
import(archModelModule)
bind<WorkManager>() with singleton { WorkManager.getInstance(this@FeederApplication) }
bind<ContentResolver>() with singleton { contentResolver }
bind<ToastMaker>() with singleton {
object : ToastMaker {
override suspend fun makeToast(text: String) = withContext(Dispatchers.Main) {
Toast.makeText(this@FeederApplication, text, Toast.LENGTH_SHORT).show()
}
override suspend fun makeToast(resId: Int) {
Toast.makeText(this@FeederApplication, resId, Toast.LENGTH_SHORT).show()
}
}
}
bind<NotificationManagerCompat>() with singleton { NotificationManagerCompat.from(this@FeederApplication) }
bind<SharedPreferences>() with singleton {
PreferenceManager.getDefaultSharedPreferences(
this@FeederApplication
)
}
bind<OkHttpClient>() with singleton {
cachingHttpClient(
cacheDirectory = (externalCacheDir ?: filesDir).resolve("http")
).newBuilder()
.addNetworkInterceptor(UserAgentInterceptor)
.build()
}
bind<ImageLoader>() with singleton {
val repository = instance<Repository>()
val okHttpClient = instance<OkHttpClient>()
.newBuilder()
// This is not used by Coil but no need to risk evicting the real cache
.cache(Cache((externalCacheDir ?: filesDir).resolve("dummy_img"), 1024L))
.addInterceptor { chain ->
chain.proceed(
when (!repository.loadImageOnlyOnWifi.value || currentlyUnmetered(this@FeederApplication)) {
true -> chain.request()
false -> {
// Forces only cached responses to be used - if no cache then 504 is thrown
chain.request().newBuilder()
.cacheControl(
CacheControl.Builder()
.onlyIfCached()
.maxStale(Int.MAX_VALUE, TimeUnit.SECONDS)
.maxAge(Int.MAX_VALUE, TimeUnit.SECONDS)
.build()
)
.build()
}
}
)
}
.build()
ImageLoader.Builder(instance())
.okHttpClient(okHttpClient = okHttpClient)
.diskCache(
DiskCache.Builder()
.directory((externalCacheDir ?: filesDir).resolve("image_cache"))
.maxSizeBytes(250L * 1024 * 1024)
.build()
)
.components {
add(TooLargeImageInterceptor())
add(SvgDecoder.Factory())
if (SDK_INT >= 28) {
add(ImageDecoderDecoder.Factory())
} else {
add(GifDecoder.Factory())
}
}
.build()
}
bind<ApplicationCoroutineScope>() with instance(applicationCoroutineScope)
import(networkModule)
bind<TTSStateHolder>() with instance(ttsStateHolder)
bind<NotificationsWorker>() with singleton { NotificationsWorker(di) }
}
init {
// Install Conscrypt to handle TLSv1.3 pre Android10
Security.insertProviderAt(Conscrypt.newProvider(), 1)
}
override fun onCreate() {
super.onCreate()
AndroidThreeTen.init(this)
staticFilesDir = filesDir
}
override fun onTerminate() {
applicationCoroutineScope.cancel("Application is being terminated")
ttsStateHolder.shutdown()
super.onTerminate()
}
companion object {
// Needed for database migration
lateinit var staticFilesDir: File
}
override fun newImageLoader(): ImageLoader {
return di.direct.instance()
}
}
| gpl-3.0 | 4ed600569f91b2215fb77e58e3fda58c | 41.233333 | 116 | 0.639437 | 5.239145 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ide/browsers/actions/BaseOpenInBrowserAction.kt | 3 | 6328 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.browsers.actions
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.ide.browsers.*
import com.intellij.ide.browsers.impl.WebBrowserServiceImpl
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.util.BitUtil
import com.intellij.util.Url
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.resolvedPromise
import java.awt.event.InputEvent
internal class BaseOpenInBrowserAction(private val browser: WebBrowser) : DumbAwareAction(browser.name, null, browser.icon) {
companion object {
private val LOG = logger<BaseOpenInBrowserAction>()
@JvmStatic
fun doUpdate(event: AnActionEvent): OpenInBrowserRequest? {
val request = createRequest(event.dataContext, isForceFileUrlIfNoUrlProvider = false)
val applicable = request != null && WebBrowserServiceImpl.getProviders(request).findAny().isPresent
event.presentation.isEnabledAndVisible = applicable
return if (applicable) request else null
}
internal fun openInBrowser(request: OpenInBrowserRequest, preferLocalUrl: Boolean = false, browser: WebBrowser? = null) {
try {
val urls = WebBrowserService.getInstance().getUrlsToOpen(request, preferLocalUrl)
if (!urls.isEmpty()) {
chooseUrl(urls)
.onSuccess { url ->
FileDocumentManager.getInstance().saveAllDocuments()
BrowserLauncher.instance.browse(url.toExternalForm(), browser, request.project)
}
}
}
catch (e: WebBrowserUrlProvider.BrowserException) {
Messages.showErrorDialog(e.message, IdeBundle.message("browser.error"))
}
catch (e: Exception) {
LOG.error(e)
}
}
internal fun openInBrowser(event: AnActionEvent, browser: WebBrowser?) {
createRequest(event.dataContext, isForceFileUrlIfNoUrlProvider = true)?.let {
openInBrowser(it, BitUtil.isSet(event.modifiers, InputEvent.SHIFT_MASK), browser)
}
}
}
private fun getBrowser(): WebBrowser? {
if (WebBrowserManager.getInstance().isActive(browser) && browser.path != null) {
return browser
}
else {
return null
}
}
override fun update(e: AnActionEvent) {
val browser = getBrowser()
if (browser == null) {
e.presentation.isEnabledAndVisible = false
return
}
val result: OpenInBrowserRequest?
if (e.place == ActionPlaces.UNKNOWN) {
result = createRequest(e.dataContext, isForceFileUrlIfNoUrlProvider = true)
val isApplicable = result?.isPhysicalFile() ?: false
e.presentation.isEnabledAndVisible = isApplicable
if (!isApplicable) {
return
}
result!!
}
else {
result = doUpdate(e) ?: return
}
var description = templatePresentation.text
if (ActionPlaces.CONTEXT_TOOLBAR == e.place) {
val shortcutInfo = buildString {
val shortcut = KeymapUtil.getPrimaryShortcut("WebOpenInAction")
if (shortcut != null) {
append(KeymapUtil.getShortcutText(shortcut))
}
if (WebBrowserXmlService.getInstance().isHtmlFile(result.file)) {
append(if (shortcut != null) ", " else "")
append(IdeBundle.message("browser.shortcut"))
}
}
if (shortcutInfo.isNotEmpty()) {
description = "$description ($shortcutInfo)"
}
}
e.presentation.text = description
}
override fun actionPerformed(e: AnActionEvent) {
getBrowser()?.let {
openInBrowser(e, it)
}
}
}
private fun createRequest(context: DataContext, isForceFileUrlIfNoUrlProvider: Boolean): OpenInBrowserRequest? {
val editor = CommonDataKeys.EDITOR.getData(context)
if (editor == null) {
var psiFile = CommonDataKeys.PSI_FILE.getData(context)
val virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(context)
val project = CommonDataKeys.PROJECT.getData(context)
if (virtualFile != null && !virtualFile.isDirectory && virtualFile.isValid && project != null && project.isInitialized) {
psiFile = PsiManager.getInstance(project).findFile(virtualFile)
}
if (psiFile != null) {
return createOpenInBrowserRequest(psiFile, isForceFileUrlIfNoUrlProvider)
}
}
else {
val project = editor.project
if (project != null && project.isInitialized) {
val psiFile = CommonDataKeys.PSI_FILE.getData(context) ?: PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
if (psiFile != null) {
return object : OpenInBrowserRequest(psiFile, isForceFileUrlIfNoUrlProvider) {
private val lazyElement by lazy { file.findElementAt(editor.caretModel.offset) }
override val element: PsiElement
get() = lazyElement ?: file
}
}
}
}
return null
}
internal fun chooseUrl(urls: Collection<Url>): Promise<Url> {
if (urls.size == 1) {
return resolvedPromise(urls.first())
}
val result = AsyncPromise<Url>()
JBPopupFactory.getInstance()
.createPopupChooserBuilder(urls.toMutableList())
.setRenderer(SimpleListCellRenderer.create<Url> { label, value, _ ->
// todo icons looks good, but is it really suitable for all URLs providers?
label.icon = AllIcons.Nodes.Servlet
label.text = (value as Url).toDecodedForm()
})
.setTitle(IdeBundle.message("browser.url.popup"))
.setItemChosenCallback { value ->
result.setResult(value)
}
.createPopup()
.showInFocusCenter()
return result
} | apache-2.0 | ef53c8c485348fbeac2d6010598e8e7b | 35.165714 | 140 | 0.707807 | 4.605531 | false | false | false | false |
ursjoss/sipamato | public/public-persistence-jooq/src/test/kotlin/ch/difty/scipamato/publ/persistence/paper/JooqPublicPaperRepoTest.kt | 2 | 2711 | package ch.difty.scipamato.publ.persistence.paper
import ch.difty.scipamato.common.persistence.JooqDbSortMapper
import ch.difty.scipamato.publ.db.tables.Paper
import ch.difty.scipamato.publ.db.tables.records.PaperRecord
import ch.difty.scipamato.publ.entity.PublicPaper
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import io.mockk.mockk
import io.mockk.verify
import org.amshove.kluent.shouldBeEqualTo
import org.jooq.DSLContext
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@Suppress("SpellCheckingInspection")
@ExtendWith(MockKExtension::class)
internal class JooqPublicPaperRepoTest {
@MockK
private lateinit var dslMock: DSLContext
@MockK
private lateinit var sortMapperMock: JooqDbSortMapper<PaperRecord, PublicPaper, Paper>
@MockK
private lateinit var filterConditionMapperMock: PublicPaperFilterConditionMapper
@MockK(relaxed = true)
private lateinit var authorsAbbreviator: AuthorsAbbreviator
@MockK(relaxed = true)
private lateinit var journalExtractor: JournalExtractor
private lateinit var repo: JooqPublicPaperRepo
@BeforeEach
fun setUp() {
repo = object : JooqPublicPaperRepo(
dslMock,
sortMapperMock,
filterConditionMapperMock,
authorsAbbreviator,
journalExtractor
) {
override val mainLanguage get() = "de"
}
}
@AfterEach
fun tearDown() {
confirmVerified(dslMock, sortMapperMock, filterConditionMapperMock)
}
@Test
fun mapping_callsAuthorsAbbreviator_withAuthors() {
val authors = "authors"
val authorsAbbr = "auths"
val pr = mockk<PaperRecord>(relaxed = true)
every { pr.authors } returns authors
every { authorsAbbreviator.abbreviate(authors) } returns authorsAbbr
val pp = repo.map(pr)
pp.authors shouldBeEqualTo authors
pp.authorsAbbreviated shouldBeEqualTo authorsAbbr
verify { authorsAbbreviator.abbreviate(authors) }
}
@Test
fun mapping_callsJournalExtractor_withLocation() {
val location = "location"
val journal = "journal"
val pr = mockk<PaperRecord>(relaxed = true)
every { pr.location } returns location
every { journalExtractor.extractJournal(location) } returns journal
val pp = repo.map(pr)
pp.location shouldBeEqualTo location
pp.journal shouldBeEqualTo journal
verify { journalExtractor.extractJournal(location) }
}
}
| gpl-3.0 | eb6e6000df2b06e0ecc6826193eb890d | 29.122222 | 90 | 0.717816 | 4.62628 | false | false | false | false |
allotria/intellij-community | platform/smRunner/src/com/intellij/execution/testframework/sm/runner/OutputEventSplitter.kt | 3 | 7151 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.testframework.sm.runner
import com.intellij.execution.impl.ConsoleBuffer
import com.intellij.execution.process.ProcessOutputType
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.openapi.util.Key
import jetbrains.buildServer.messages.serviceMessages.ServiceMessage
import java.util.concurrent.atomic.AtomicReference
/**
* External test runner sends plain text along with service messages ([ServiceMessage]) to [process].
* Test runner sends data as stream and flushes it periodically. On each flush [process] is called.
* That means [ServiceMessage] may be [process]ed in the middle.
*
* This class handles such cases by buffering service messages.
* It then calls [onTextAvailable] for text or message. It is guaranteed that each call of [onTextAvailable] either contains
* plain text or begins with [ServiceMessage] and ends with "\n".
*
* Current implementation supports only [ServiceMessage]s that end with new line.
*
* After process ends, call [flush] to process remain.
*
* Class is not thread safe in that matter that you can't call [process] for same stream (i.e. stderr) from different threads,
* but [flush] could be called from any thread.
*
* If [bufferTextUntilNewLine] is set, any output/err (including service messages) is buffered until newline arrives.
* Otherwise, this is done only for service messages.
* It is recommended not to enable [bufferTextUntilNewLine] because it gives user ability to see text as fast as possible.
* In some cases like when there is a separate protocol exists on top of text message that does not support messages
* flushed in random places, this option must be enabled.
*
* If [cutNewLineBeforeServiceMessage] is set, each service message must have "\n" prefix which is cut.
*
*/
abstract class OutputEventSplitter(private val bufferTextUntilNewLine: Boolean = false,
private val cutNewLineBeforeServiceMessage: Boolean = false) {
private val prevRefs: Map<ProcessOutputType, AtomicReference<Output>> =
listOf(ProcessOutputType.STDOUT, ProcessOutputType.STDERR, ProcessOutputType.SYSTEM)
.map { it to AtomicReference<Output>() }.toMap()
private val ProcessOutputType.prevRef get() = prevRefs[baseOutputType.baseOutputType]
private var newLinePending = false
/**
* [outputType] could be one of [ProcessOutputTypes] or any other [ProcessOutputType].
* Only stdout ([ProcessOutputType.isStdout]) accepts Teamcity Messages ([ServiceMessage]).
*
* Stderr and System are flushed automatically unless [bufferTextUntilNewLine],
* Stdout may be buffered until the end of the message.
* Make sure you do not process same type from different threads.
*/
fun process(text: String, outputType: Key<*>) {
val prevRef = (outputType as? ProcessOutputType)?.prevRef
if (prevRef == null) {
flushInternal(text, outputType)
return
}
var mergedText = text
prevRef.getAndSet(null)?.let {
if (it.outputType == outputType) {
mergedText = it.text + text
}
else {
flushInternal(it.text, it.outputType)
}
}
processInternal(mergedText, outputType)?.let {
prevRef.set(Output(it, outputType))
}
}
/**
* For stderr and system [text] is provided as fast as possible unless [bufferTextUntilNewLine].
* For stdout [text] is either TC message that starts from [ServiceMessage.SERVICE_MESSAGE_START] and ends with new line
* or chunk of process output
* */
abstract fun onTextAvailable(text: String, outputType: Key<*>)
private fun processInternal(text: String, outputType: ProcessOutputType): String? {
var from = 0
val processServiceMessages = outputType.isStdout
// new line char and teamcity message start are two reasons to flush previous text
var newLineInd = text.indexOf(NEW_LINE)
var teamcityMessageStartInd = if (processServiceMessages) text.indexOf(SERVICE_MESSAGE_START) else -1
var serviceMessageStarted = false
while (from < text.length) {
val nextFrom = Math.min(if (newLineInd != -1) newLineInd + 1 else Integer.MAX_VALUE,
if (teamcityMessageStartInd != -1) teamcityMessageStartInd else Integer.MAX_VALUE)
if (nextFrom == Integer.MAX_VALUE) {
break
}
if (from < nextFrom) {
flushInternal(text.substring(from, nextFrom), outputType)
}
assert(from != nextFrom || from == 0) {"``from`` is $from and it hasn't been changed since last check. Loop is frozen"}
from = nextFrom
serviceMessageStarted = processServiceMessages && nextFrom == teamcityMessageStartInd
if (serviceMessageStarted) {
teamcityMessageStartInd = text.indexOf(SERVICE_MESSAGE_START, nextFrom + SERVICE_MESSAGE_START.length)
}
if (newLineInd != -1 && nextFrom == newLineInd + 1) {
newLineInd = text.indexOf(NEW_LINE, nextFrom)
}
}
if (from < text.length) {
val unprocessed = text.substring(from)
if (serviceMessageStarted) {
return unprocessed
}
val preserveSuffixLength = when {
bufferTextUntilNewLine -> unprocessed.length
processServiceMessages -> findSuffixLengthToPreserve(unprocessed)
else -> 0
}
if (preserveSuffixLength < unprocessed.length) {
flushInternal(unprocessed.substring(0, unprocessed.length - preserveSuffixLength), outputType)
}
if (preserveSuffixLength > 0) {
return unprocessed.substring(unprocessed.length - preserveSuffixLength)
}
}
return null
}
private fun findSuffixLengthToPreserve(text: String): Int {
for (suffixSize in SERVICE_MESSAGE_START.length - 1 downTo 1) {
if (text.regionMatches(text.length - suffixSize, SERVICE_MESSAGE_START, 0, suffixSize)) {
return suffixSize
}
}
return 0
}
private data class Output(val text: String, val outputType: ProcessOutputType)
/**
* Flush remainder. Call as last step.
*/
fun flush() {
prevRefs.values.forEach { reference ->
reference.getAndSet(null)?.let {
flushInternal(it.text, it.outputType, lastFlush = true)
}
}
}
private fun flushInternal(text: String, key: Key<*>, lastFlush: Boolean = false) {
if (cutNewLineBeforeServiceMessage && key is ProcessOutputType && key.isStdout) {
if (newLinePending) { //Prev. flush was "\n".
if (!text.startsWith(SERVICE_MESSAGE_START) || (lastFlush)) {
onTextAvailable("\n", key)
}
newLinePending = false
}
if (text == "\n" && !lastFlush) {
newLinePending = true
return
}
}
val textToAdd = if (USE_CYCLE_BUFFER) cutLineIfTooLong(text) else text
onTextAvailable(textToAdd, key)
}
}
private val USE_CYCLE_BUFFER = ConsoleBuffer.useCycleBuffer()
private const val SERVICE_MESSAGE_START: String = ServiceMessage.SERVICE_MESSAGE_START
private const val NEW_LINE: Char = '\n'
| apache-2.0 | 37d9cd1134b7be41131f5cb3a0af4e8b | 40.33526 | 140 | 0.70158 | 4.444375 | false | false | false | false |
allotria/intellij-community | java/java-impl/src/com/intellij/codeInsight/completion/ml/JavaContextFeaturesProvider.kt | 2 | 1765 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.completion.ml
import com.intellij.codeInsight.completion.JavaCompletionUtil
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.annotations.NotNull
class JavaContextFeaturesProvider : ContextFeatureProvider {
override fun getName(): String = "java"
override fun calculateFeatures(environment: @NotNull CompletionEnvironment): @NotNull MutableMap<String, MLFeatureValue> {
val features = mutableMapOf<String, MLFeatureValue>()
JavaCompletionFeatures.calculateVariables(environment)
JavaCompletionUtil.getExpectedTypes(environment.parameters)?.forEach {
features["${JavaCompletionFeatures.asJavaType(it).name.toLowerCase()}_expected"] = MLFeatureValue.binary(true)
}
if (JavaCompletionFeatures.isInQualifierExpression(environment)) {
features["is_in_qualifier_expression"] = MLFeatureValue.binary(true)
}
if (JavaCompletionFeatures.isAfterMethodCall(environment)) {
features["is_after_method_call"] = MLFeatureValue.binary(true)
}
PsiTreeUtil.prevVisibleLeaf(environment.parameters.position)?.let { prevLeaf ->
JavaCompletionFeatures.asKeyword(prevLeaf.text)?.let { keyword ->
features["prev_neighbour_keyword"] = MLFeatureValue.categorical(keyword)
if (keyword == JavaCompletionFeatures.JavaKeyword.IMPLEMENTS ||
keyword == JavaCompletionFeatures.JavaKeyword.EXTENDS) {
PsiTreeUtil.prevVisibleLeaf(prevLeaf)?.let { childClass ->
JavaCompletionFeatures.calculateChildClassWords(environment, childClass)
}
}
}
}
return features
}
} | apache-2.0 | f533b40629055fcd0d4d2d8eceac631e | 45.473684 | 140 | 0.751841 | 4.985876 | false | false | false | false |
allotria/intellij-community | plugins/devkit/devkit-core/src/actions/NewThemeAction.kt | 1 | 6307 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.actions
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.fileTemplates.FileTemplateUtil
import com.intellij.ide.ui.UIThemeProvider
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.JBTextField
import com.intellij.ui.layout.*
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.inspections.quickfix.PluginDescriptorChooser
import org.jetbrains.idea.devkit.module.PluginModuleType
import org.jetbrains.idea.devkit.util.DescriptorUtil
import org.jetbrains.idea.devkit.util.PsiUtil
import java.util.*
import javax.swing.JComponent
//TODO better undo support
class NewThemeAction: AnAction() {
private val THEME_JSON_TEMPLATE = "ThemeJson.json"
private val THEME_PROVIDER_EP_NAME = UIThemeProvider.EP_NAME.name
@Suppress("UsePropertyAccessSyntax") // IdeView#getOrChooseDirectory is not a getter
override fun actionPerformed(e: AnActionEvent) {
val view = e.getData(LangDataKeys.IDE_VIEW) ?: return
val dir = view.getOrChooseDirectory() ?: return
val module = e.getRequiredData(LangDataKeys.MODULE)
val project = module.project
val dialog = NewThemeDialog(project)
dialog.show()
if (dialog.exitCode == DialogWrapper.OK_EXIT_CODE) {
val file = createThemeJson(dialog.name.text, dialog.isDark.isSelected, project, dir, module)
view.selectElement(file)
FileEditorManager.getInstance(project).openFile(file.virtualFile, true)
registerTheme(dir, file, module)
}
}
override fun update(e: AnActionEvent) {
val module = e.getData(LangDataKeys.MODULE)
e.presentation.isEnabled = module != null && (PsiUtil.isPluginModule(module) || PluginModuleType.get(module) is PluginModuleType)
}
@Suppress("HardCodedStringLiteral")
private fun createThemeJson(themeName: String,
isDark: Boolean,
project: Project,
dir: PsiDirectory,
module: Module): PsiFile {
val fileName = getThemeJsonFileName(themeName)
val colorSchemeFilename = getThemeColorSchemeFileName(themeName)
val template = FileTemplateManager.getInstance(project).getJ2eeTemplate(THEME_JSON_TEMPLATE)
val editorSchemeProps = Properties()
editorSchemeProps.setProperty("NAME", themeName)
editorSchemeProps.setProperty("PARENT_SCHEME", if (isDark) "Darcula" else "Default")
val editorSchemeTemplate = FileTemplateManager.getInstance(project).getJ2eeTemplate("ThemeEditorColorScheme.xml")
val colorScheme = FileTemplateUtil.createFromTemplate(editorSchemeTemplate, colorSchemeFilename, editorSchemeProps, dir)
val props = Properties()
props.setProperty("NAME", themeName)
props.setProperty("IS_DARK", isDark.toString())
props.setProperty("COLOR_SCHEME_NAME", getSourceRootRelativeLocation(module, colorScheme as PsiFile))
val created = FileTemplateUtil.createFromTemplate(template, fileName, props, dir)
assert(created is PsiFile)
return created as PsiFile
}
private fun getThemeJsonFileName(themeName: String): String {
return FileUtil.sanitizeFileName(themeName) + ".theme.json"
}
private fun getThemeColorSchemeFileName(themeName: String): String {
return FileUtil.sanitizeFileName(themeName) + ".xml"
}
private fun registerTheme(dir: PsiDirectory, file: PsiFile, module: Module) {
val relativeLocation = getSourceRootRelativeLocation(module, file) ?: return
val pluginXml = DevkitActionsUtil.choosePluginModuleDescriptor(dir) ?: return
DescriptorUtil.checkPluginXmlsWritable(module.project, pluginXml)
val domFileElement = DescriptorUtil.getIdeaPluginFileElement(pluginXml)
WriteCommandAction.writeCommandAction(module.project, pluginXml).run<Throwable> {
val extensions = PluginDescriptorChooser.findOrCreateExtensionsForEP(domFileElement, THEME_PROVIDER_EP_NAME)
val extensionTag = extensions.addExtension(THEME_PROVIDER_EP_NAME).xmlTag
extensionTag.setAttribute("id", getRandomId())
extensionTag.setAttribute("path", relativeLocation)
}
}
private fun getSourceRootRelativeLocation(module: Module, file: PsiFile): String? {
val rootManager = ModuleRootManager.getInstance(module)
val sourceRoots = rootManager.getSourceRoots(false)
val virtualFile = file.virtualFile
var relativeLocation : String? = null
for (sourceRoot in sourceRoots) {
if (!VfsUtil.isAncestor(sourceRoot,virtualFile,true)) continue
relativeLocation = VfsUtil.getRelativeLocation(virtualFile, sourceRoot) ?: continue
break
}
return "/${relativeLocation}"
}
private fun getRandomId() = UUID.randomUUID().toString()
class NewThemeDialog(project: Project) : DialogWrapper(project) {
val name = JBTextField()
val isDark = CheckBox(DevKitBundle.message("new.theme.dialog.is.dark.checkbox.text"), true)
init {
title = DevKitBundle.message("new.theme.dialog.title")
init()
}
override fun createCenterPanel(): JComponent? {
return panel {
row(DevKitBundle.message("new.theme.dialog.name.text.field.text")) {
cell {
name(growPolicy = GrowPolicy.MEDIUM_TEXT)
.focused()
//TODO max name length, maybe some other restrictions?
.withErrorOnApplyIf(DevKitBundle.message("new.theme.dialog.name.empty")) { it.text.isBlank() }
}
}
row("") {
cell { isDark() }
}
}
}
}
}
| apache-2.0 | bbf02504f14c3d4ccd828dfebb73a25c | 41.046667 | 140 | 0.743143 | 4.620513 | false | false | false | false |
Kotlin/kotlinx.coroutines | benchmarks/src/jmh/kotlin/benchmarks/ChannelSinkDepthBenchmark.kt | 1 | 2635 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.*
import kotlin.coroutines.*
@Warmup(iterations = 7, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(2)
open class ChannelSinkDepthBenchmark {
private val tl = ThreadLocal.withInitial({ 42 })
private val unconfinedOneElement = Dispatchers.Unconfined + tl.asContextElement()
@Benchmark
fun depth1(): Int = runBlocking {
run(1, unconfinedOneElement)
}
@Benchmark
fun depth10(): Int = runBlocking {
run(10, unconfinedOneElement)
}
@Benchmark
fun depth100(): Int = runBlocking {
run(100, unconfinedOneElement)
}
@Benchmark
fun depth1000(): Int = runBlocking {
run(1000, unconfinedOneElement)
}
private suspend inline fun run(callTraceDepth: Int, context: CoroutineContext): Int {
return Channel
.range(1, 10_000, context)
.filter(callTraceDepth, context) { it % 4 == 0 }
.fold(0) { a, b -> a + b }
}
private fun Channel.Factory.range(start: Int, count: Int, context: CoroutineContext) =
GlobalScope.produce(context) {
for (i in start until (start + count))
send(i)
}
// Migrated from deprecated operators, are good only for stressing channels
private fun ReceiveChannel<Int>.filter(
callTraceDepth: Int,
context: CoroutineContext = Dispatchers.Unconfined,
predicate: suspend (Int) -> Boolean
): ReceiveChannel<Int> =
GlobalScope.produce(context, onCompletion = { cancel() }) {
deeplyNestedFilter(this, callTraceDepth, predicate)
}
private suspend fun ReceiveChannel<Int>.deeplyNestedFilter(
sink: ProducerScope<Int>,
depth: Int,
predicate: suspend (Int) -> Boolean
) {
if (depth <= 1) {
for (e in this) {
if (predicate(e)) sink.send(e)
}
} else {
deeplyNestedFilter(sink, depth - 1, predicate)
require(true) // tail-call
}
}
private suspend inline fun <E, R> ReceiveChannel<E>.fold(initial: R, operation: (acc: R, E) -> R): R {
var accumulator = initial
consumeEach {
accumulator = operation(accumulator, it)
}
return accumulator
}
}
| apache-2.0 | 69c0d5a9a7e9058d59156bcd7dd440c9 | 27.956044 | 106 | 0.62277 | 4.25 | false | false | false | false |
zdary/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/ui/grammar/GrazieSettingsPanel.kt | 2 | 1909 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.ide.ui.grammar
import com.intellij.grazie.GrazieConfig
import com.intellij.grazie.ide.ui.components.dsl.msg
import com.intellij.grazie.ide.ui.grammar.tabs.exceptions.GrazieExceptionsTab
import com.intellij.grazie.ide.ui.grammar.tabs.rules.GrazieRulesTab
import com.intellij.grazie.ide.ui.grammar.tabs.scope.GrazieScopeTab
import com.intellij.openapi.Disposable
import com.intellij.openapi.options.ConfigurableUi
import com.intellij.ui.components.JBTabbedPane
import com.intellij.util.ui.JBUI
import javax.swing.JComponent
internal class GrazieSettingsPanel : ConfigurableUi<GrazieConfig>, Disposable {
private val scope = GrazieScopeTab()
private val rules = GrazieRulesTab()
private val exceptions = GrazieExceptionsTab()
override fun isModified(settings: GrazieConfig): Boolean = rules.isModified(settings.state) ||
scope.isModified(settings.state) ||
exceptions.isModified(settings.state)
override fun apply(settings: GrazieConfig) {
GrazieConfig.update { state ->
exceptions.apply(scope.apply(rules.apply(state)))
}
rules.reset(settings.state)
}
override fun reset(settings: GrazieConfig) {
rules.reset(settings.state)
scope.reset(settings.state)
exceptions.reset(settings.state)
}
override fun getComponent(): JComponent = JBTabbedPane().apply {
this.tabComponentInsets = JBUI.insetsTop(8)
add(msg("grazie.settings.grammar.tabs.scope"), scope.component)
add(msg("grazie.settings.grammar.tabs.rules"), rules.component)
add(msg("grazie.settings.grammar.tabs.exceptions"), exceptions.component)
}
override fun dispose() = rules.dispose()
}
| apache-2.0 | 99ab0b251ed49fd1a37d2cf631568219 | 40.5 | 140 | 0.72813 | 4.270694 | false | true | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/RepositoryLocationCommittedChangesPanel.kt | 1 | 3618 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.committed
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task.Backgroundable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages.showErrorDialog
import com.intellij.openapi.vcs.CommittedChangesProvider
import com.intellij.openapi.vcs.RepositoryLocation
import com.intellij.openapi.vcs.VcsDataKeys.REMOTE_HISTORY_CHANGED_LISTENER
import com.intellij.openapi.vcs.VcsDataKeys.REMOTE_HISTORY_LOCATION
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList
import com.intellij.util.AsynchConsumer
import com.intellij.util.BufferedListConsumer
import com.intellij.util.Consumer
private val LOG = logger<RepositoryLocationCommittedChangesPanel<*>>()
internal class RepositoryLocationCommittedChangesPanel<S : ChangeBrowserSettings>(
project: Project,
val provider: CommittedChangesProvider<*, S>,
val repositoryLocation: RepositoryLocation,
extraActions: DefaultActionGroup
) : CommittedChangesPanel(project) {
@Volatile
private var isDisposed = false
var maxCount: Int = 0
var settings: S = provider.createDefaultSettings()
var isLoading: Boolean = false
private set
init {
setup(extraActions, provider.createActions(browser, repositoryLocation))
}
override fun refreshChanges() = LoadCommittedChangesTask().queue()
override fun getData(dataId: String): Any? =
when {
REMOTE_HISTORY_CHANGED_LISTENER.`is`(dataId) -> Consumer<String> { refreshChanges() }
REMOTE_HISTORY_LOCATION.`is`(dataId) -> repositoryLocation
else -> super.getData(dataId)
}
override fun dispose() {
isDisposed = true
}
private inner class LoadCommittedChangesTask : Backgroundable(project, "Loading Changes", true) {
private var error: VcsException? = null
init {
browser.reset()
isLoading = true
browser.setLoading(true)
}
override fun run(indicator: ProgressIndicator) =
try {
val appender = { changeLists: List<CommittedChangeList> ->
runInEdt(ModalityState.stateForComponent(browser)) {
if (project.isDisposed) return@runInEdt
browser.append(changeLists)
}
}
val bufferedAppender = BufferedListConsumer(30, appender, -1)
provider.loadCommittedChanges(settings, repositoryLocation, maxCount, object : AsynchConsumer<CommittedChangeList> {
override fun consume(changeList: CommittedChangeList) {
if (isDisposed) indicator.cancel()
ProgressManager.checkCanceled()
bufferedAppender.consumeOne(changeList)
}
override fun finished() = bufferedAppender.flush()
})
}
catch (e: VcsException) {
LOG.info(e)
error = e
}
override fun onSuccess() {
error?.let {
showErrorDialog(myProject, "Error refreshing view: ${it.messages.joinToString("\n")}", "Committed Changes")
}
}
override fun onFinished() {
isLoading = false
browser.setLoading(false)
}
}
} | apache-2.0 | f2279d056336818dd025bd8674aefbe0 | 32.82243 | 140 | 0.735489 | 4.668387 | false | false | false | false |
leafclick/intellij-community | plugins/settings-repository/src/IcsSettings.kt | 1 | 2997 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.Time
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.io.sanitizeFileName
import com.intellij.util.io.write
import java.nio.file.Path
private const val DEFAULT_COMMIT_DELAY = 10 * Time.MINUTE
class MyPrettyPrinter : DefaultPrettyPrinter() {
init {
_arrayIndenter = NopIndenter.instance
}
override fun createInstance() = MyPrettyPrinter()
override fun writeObjectFieldValueSeparator(jg: JsonGenerator) {
jg.writeRaw(": ")
}
override fun writeEndObject(jg: JsonGenerator, nrOfEntries: Int) {
if (!_objectIndenter.isInline) {
--_nesting
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(jg, _nesting)
}
jg.writeRaw('}')
}
override fun writeEndArray(jg: JsonGenerator, nrOfValues: Int) {
if (!_arrayIndenter.isInline) {
--_nesting
}
jg.writeRaw(']')
}
}
fun saveSettings(settings: IcsSettings, settingsFile: Path) {
val serialized = ObjectMapper().writer(MyPrettyPrinter()).writeValueAsBytes(settings)
if (serialized.size <= 2) {
settingsFile.delete()
}
else {
settingsFile.write(serialized)
}
}
fun loadSettings(settingsFile: Path): IcsSettings {
if (!settingsFile.exists()) {
return IcsSettings()
}
val settings = ObjectMapper().readValue(settingsFile.toFile(), IcsSettings::class.java)
if (settings.commitDelay <= 0) {
settings.commitDelay = DEFAULT_COMMIT_DELAY
}
return settings
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class IcsSettings {
var commitDelay = DEFAULT_COMMIT_DELAY
var doNoAskMapProject = false
var readOnlySources: List<ReadonlySource> = SmartList()
var autoSync = true
var includeHostIntoCommitMessage = true
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class ReadonlySource(var url: String? = null, var active: Boolean = true) {
val path: String?
@JsonIgnore
get() {
var fileName = PathUtilRt.getFileName(url ?: return null)
val suffix = ".git"
if (fileName.endsWith(suffix)) {
fileName = fileName.substring(0, fileName.length - suffix.length)
}
// the convention is that the .git extension should be used for bare repositories
return "${sanitizeFileName(fileName)}.${Integer.toHexString(url!!.hashCode())}.git"
}
} | apache-2.0 | c11ab69ee1dcd44ded4bbb9206aa4c10 | 29.907216 | 140 | 0.737404 | 4.174095 | false | false | false | false |
leafclick/intellij-community | java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ObsoleteLibraryFilesRemover.kt | 1 | 1787 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.configuration
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import java.util.*
class ObsoleteLibraryFilesRemover(private val project: Project) {
private val oldRoots = LinkedHashSet<VirtualFile>()
fun registerObsoleteLibraryRoots(roots: Collection<VirtualFile>) {
oldRoots += roots
}
fun deleteFiles() {
val index = ProjectFileIndex.getInstance(project)
//do not suggest to delete library files located outside project roots: they may be used in other projects or aren't stored in VCS
val toDelete = oldRoots.filter { it.isValid && !index.isInLibrary(it) && index.isInContent(VfsUtil.getLocalFile(it)) }
oldRoots.clear()
if (toDelete.isNotEmpty()) {
val many = toDelete.size > 1
if (Messages.showYesNoDialog(project, "The following ${if (many) "files aren't" else "file isn't"} used anymore:\n" +
"${toDelete.joinToString("\n") { it.presentableUrl }}\n" +
"Do you want to delete ${if (many) "them" else "it"}?\n" +
"You might not be able to fully undo this operation!",
"Delete Unused Files", null) == Messages.YES) {
runWriteAction {
toDelete.forEach {
VfsUtil.getLocalFile(it).delete(this)
}
}
}
}
}
} | apache-2.0 | d1c29970d33571c71bbe86d7e836b0e4 | 42.609756 | 140 | 0.651371 | 4.582051 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/accounts/GithubProjectDefaultAccountHolder.kt | 1 | 1787 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.accounts
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import org.jetbrains.plugins.github.util.GithubNotifications
/**
* Handles default Github account for project
*
* TODO: auto-detection
*/
@State(name = "GithubDefaultAccount", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
internal class GithubProjectDefaultAccountHolder(private val project: Project) : PersistentStateComponent<AccountState> {
var account: GithubAccount? = null
init {
ApplicationManager.getApplication().messageBus.connect(project).subscribe(GithubAccountManager.ACCOUNT_REMOVED_TOPIC, object : AccountRemovedListener {
override fun accountRemoved(removedAccount: GithubAccount) {
if (account == removedAccount) account = null
}
})
}
override fun getState(): AccountState {
return AccountState().apply { defaultAccountId = account?.id }
}
override fun loadState(state: AccountState) {
account = state.defaultAccountId?.let(::findAccountById)
}
private fun findAccountById(id: String): GithubAccount? {
val account = service<GithubAccountManager>().accounts.find { it.id == id }
if (account == null) runInEdt {
GithubNotifications.showWarning(project, "Missing Default GitHub Account", "",
GithubNotifications.getConfigureAction(project))
}
return account
}
}
internal class AccountState {
var defaultAccountId: String? = null
}
| apache-2.0 | cc6feec67a47c180dc997e2e2e09b59d | 36.229167 | 155 | 0.742026 | 4.86921 | false | false | false | false |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/common/matchers/RecyclerViewAdapterSizeMatcher.kt | 1 | 885 | @file:Suppress("unused")
package com.agoda.kakao.common.matchers
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.matcher.BoundedMatcher
import org.hamcrest.Description
/**
* Matches RecyclerView with count of children
*
* @param size of children count in RecyclerView
*/
class RecyclerViewAdapterSizeMatcher(private val size: Int) : BoundedMatcher<View, RecyclerView>(RecyclerView::class.java) {
private var itemCount: Int = 0
override fun matchesSafely(view: RecyclerView) = run {
itemCount = view.adapter?.itemCount ?: 0
itemCount == size
}
override fun describeTo(description: Description) {
description
.appendText("RecyclerView with ")
.appendValue(size)
.appendText(" item(s), but got with ")
.appendValue(itemCount)
}
}
| apache-2.0 | 05927a3a8baed410d49f2b6a76844831 | 27.548387 | 124 | 0.700565 | 4.68254 | false | false | false | false |
AndroidX/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/layoutanimation/AnimatedContentWithContentKeyDemo.kt | 3 | 3802 | /*
* 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.animation.demos.layoutanimation
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Preview
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun AnimatedContentWithContentKeyDemo() {
val model: ScreenModel = remember { ScreenModel() }
val transition = updateTransition(model.target)
Box {
val holder = rememberSaveableStateHolder()
transition.AnimatedContent(
Modifier.clickable { model.toggleTarget() },
contentAlignment = Alignment.Center,
contentKey = { it.type }
) {
if (it.type == MyScreen.Type.Count) {
holder.SaveableStateProvider(it.type) {
var count by rememberSaveable { mutableStateOf(0) }
Column(
Modifier.fillMaxSize(),
Arrangement.Center,
Alignment.CenterHorizontally
) {
Button(onClick = { count++ }) {
Text("+1")
}
Spacer(Modifier.size(20.dp))
Text("Count: $count", fontSize = 20.sp)
}
}
} else {
Box(Modifier.fillMaxSize().background(Color.LightGray))
}
}
Text(
"Tap anywhere to change content.\n Current content: ${model.target.type}",
Modifier.align(Alignment.BottomCenter)
)
}
}
sealed class MyScreen {
enum class Type { Count, Blank }
abstract val type: Type
}
class CountScreen : MyScreen() {
override val type = Type.Count
}
class BlankScreen : MyScreen() {
override val type = Type.Blank
}
class ScreenModel {
fun toggleTarget() {
if (target.type == MyScreen.Type.Count) {
target = BlankScreen()
} else {
target = CountScreen()
}
}
var target: MyScreen by mutableStateOf(CountScreen())
private set
} | apache-2.0 | 43bf8a9a09b262bbd79f1770434866cb | 33.572727 | 86 | 0.677012 | 4.728856 | false | false | false | false |
miketrewartha/positional | buildSrc/src/main/kotlin/KeyStore.kt | 1 | 979 | import org.gradle.api.Project
import java.io.File
import java.util.*
class KeyStore(project: Project) {
val file: File by lazy { project.file(properties.getProperty(PROPERTIES_KEY_STORE_FILE)) }
val keyAlias: String by lazy { properties.getProperty(PROPERTIES_KEY_ALIAS) }
val keyPassword: String by lazy { properties.getProperty(PROPERTIES_KEY_PASSWORD) }
val password: String by lazy { properties.getProperty(PROPERTIES_KEY_STORE_PASSWORD) }
private val properties: Properties by lazy {
Properties().apply { load(project.file(PROPERTIES_FILE_PATH).inputStream()) }
}
companion object {
private const val PROPERTIES_FILE_PATH = "upload_keystore.properties"
private const val PROPERTIES_KEY_ALIAS = "keyAlias"
private const val PROPERTIES_KEY_PASSWORD = "keyPassword"
private const val PROPERTIES_KEY_STORE_FILE = "storeFile"
private const val PROPERTIES_KEY_STORE_PASSWORD = "storePassword"
}
} | mit | 88c0bf8be894c160befdc8bb839101ca | 41.608696 | 94 | 0.723187 | 4.201717 | false | false | false | false |
charlesng/SampleAppArch | app/src/main/java/com/cn29/aac/binding/SpinnerBindingUtil.kt | 1 | 1709 | package com.cn29.aac.binding
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.appcompat.widget.AppCompatSpinner
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
/**
* Created by Charles Ng on 7/9/2017.
*/
object SpinnerBindingUtil {
@BindingAdapter(value = ["selectedValue", "selectedValueAttrChanged"],
requireAll = false)
fun bindSpinnerData(pAppCompatSpinner: AppCompatSpinner,
newSelectedValue: String?,
newTextAttrChanged: InverseBindingListener) {
pAppCompatSpinner.onItemSelectedListener = object :
OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?,
view: View,
position: Int,
id: Long) {
newTextAttrChanged.onChange()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
if (newSelectedValue != null) {
val pos = (pAppCompatSpinner.adapter as ArrayAdapter<String?>).getPosition(
newSelectedValue)
pAppCompatSpinner.setSelection(pos, true)
}
}
@InverseBindingAdapter(attribute = "selectedValue",
event = "selectedValueAttrChanged")
fun captureSelectedValue(pAppCompatSpinner: AppCompatSpinner): String {
return pAppCompatSpinner.selectedItem as String
}
} | apache-2.0 | 48af4a81ccbcbf39004cd82550a2d2b0 | 37.863636 | 87 | 0.635459 | 5.734899 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/setup/AvatarSetupFragment.kt | 1 | 12286 | package com.habitrpg.android.habitica.ui.fragments.setup
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.data.SetupCustomizationRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.models.SetupCustomization
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.AvatarView
import com.habitrpg.android.habitica.ui.SpeechBubbleView
import com.habitrpg.android.habitica.ui.activities.SetupActivity
import com.habitrpg.android.habitica.ui.adapter.setup.CustomizationSetupAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.helpers.bindOptionalView
import com.habitrpg.android.habitica.ui.helpers.resetViews
import com.habitrpg.android.habitica.ui.views.setup.AvatarCategoryView
import io.reactivex.functions.Consumer
import java.util.*
import javax.inject.Inject
class AvatarSetupFragment : BaseFragment() {
@Inject
lateinit var customizationRepository: SetupCustomizationRepository
@Inject
lateinit var userRepository: UserRepository
@Inject
lateinit var inventoryRepository: InventoryRepository
var activity: SetupActivity? = null
var width: Int = 0
private val avatarView: AvatarView? by bindOptionalView(R.id.avatarView)
private val customizationList: RecyclerView? by bindOptionalView(R.id.customization_list)
private val subCategoryTabs: TabLayout? by bindOptionalView(R.id.subcategory_tabs)
private val bodyButton: AvatarCategoryView? by bindOptionalView(R.id.body_button)
private val skinButton: AvatarCategoryView? by bindOptionalView(R.id.skin_button)
private val hairButton: AvatarCategoryView? by bindOptionalView(R.id.hair_button)
private val extrasButton: AvatarCategoryView? by bindOptionalView(R.id.extras_button)
private val caretView: ImageView? by bindOptionalView(R.id.caret_view)
private val speechBubbleView: SpeechBubbleView? by bindOptionalView(R.id.speech_bubble)
private val randomizeButton: Button? by bindOptionalView(R.id.randomize_button)
internal var adapter: CustomizationSetupAdapter? = null
private var user: User? = null
private var subcategories: List<String> = emptyList()
private var activeButton: AvatarCategoryView? = null
private var activeCategory: String? = null
private var activeSubCategory: String? = null
private var random = Random()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return container?.inflate(R.layout.fragment_setup_avatar)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
resetViews()
this.adapter = CustomizationSetupAdapter()
this.adapter?.userSize = this.user?.preferences?.size ?: "slim"
adapter?.updateUserEvents?.flatMap { userRepository.updateUser(user, it) }?.subscribeWithErrorHandler(Consumer {})?.let { compositeSubscription.add(it) }
adapter?.equipGearEvents?.flatMap { inventoryRepository.equip(user, "equipped", it) }?.subscribeWithErrorHandler(Consumer {})?.let { compositeSubscription.add(it) }
this.adapter?.user = this.user
val layoutManager = LinearLayoutManager(activity)
layoutManager.orientation = LinearLayoutManager.HORIZONTAL
this.customizationList?.layoutManager = layoutManager
this.customizationList?.adapter = this.adapter
this.subCategoryTabs?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
val position = tab.position
if (position < subcategories.size) {
activeSubCategory = subcategories[position]
}
loadCustomizations()
}
override fun onTabUnselected(tab: TabLayout.Tab) { /* no-on */ }
override fun onTabReselected(tab: TabLayout.Tab) { /* no-on */ }
})
bodyButton?.setOnClickListener { selectedBodyCategory() }
skinButton?.setOnClickListener { selectedSkinCategory() }
hairButton?.setOnClickListener { selectedHairCategory() }
extrasButton?.setOnClickListener { selectedExtrasCategory() }
randomizeButton?.setOnClickListener { randomizeCharacter() }
this.selectedBodyCategory()
if (this.user != null) {
this.updateAvatar()
}
}
override fun onResume() {
super.onResume()
if (this.user != null) {
this.updateAvatar()
}
this.selectedBodyCategory()
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser && context != null) {
speechBubbleView?.animateText(context?.getString(R.string.avatar_setup_description) ?: "")
}
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun loadCustomizations() {
val user = this.user ?: return
val activeCategory = this.activeCategory ?: return
this.adapter?.setCustomizationList(customizationRepository.getCustomizations(activeCategory, activeSubCategory, user))
}
fun setUser(user: User?) {
this.user = user
if (avatarView != null) {
updateAvatar()
}
if (this.adapter != null) {
this.adapter?.user = user
this.adapter?.notifyDataSetChanged()
loadCustomizations()
}
}
private fun updateAvatar() {
user?.let {
avatarView?.setAvatar(it)
}
}
private fun selectedBodyCategory() {
activateButton(bodyButton)
this.activeCategory = SetupCustomizationRepository.CATEGORY_BODY
this.subCategoryTabs?.removeAllTabs()
this.subcategories = listOf(SetupCustomizationRepository.SUBCATEGORY_SIZE, SetupCustomizationRepository.SUBCATEGORY_SHIRT)
subCategoryTabs?.newTab()?.setText(R.string.avatar_size)?.let { this.subCategoryTabs?.addTab(it) }
subCategoryTabs?.newTab()?.setText(R.string.avatar_shirt)?.let { this.subCategoryTabs?.addTab(it) }
loadCustomizations()
}
private fun selectedSkinCategory() {
activateButton(skinButton)
this.activeCategory = SetupCustomizationRepository.CATEGORY_SKIN
this.subCategoryTabs?.removeAllTabs()
this.subcategories = listOf(SetupCustomizationRepository.SUBCATEGORY_COLOR)
subCategoryTabs?.newTab()?.setText(R.string.avatar_skin_color)?.let { this.subCategoryTabs?.addTab(it) }
loadCustomizations()
}
private fun selectedHairCategory() {
activateButton(hairButton)
this.activeCategory = SetupCustomizationRepository.CATEGORY_HAIR
this.subCategoryTabs?.removeAllTabs()
this.subcategories = listOf(SetupCustomizationRepository.SUBCATEGORY_BANGS, SetupCustomizationRepository.SUBCATEGORY_COLOR, SetupCustomizationRepository.SUBCATEGORY_PONYTAIL)
subCategoryTabs?.newTab()?.setText(R.string.avatar_hair_bangs)?.let { this.subCategoryTabs?.addTab(it) }
subCategoryTabs?.newTab()?.setText(R.string.avatar_hair_color)?.let { this.subCategoryTabs?.addTab(it) }
subCategoryTabs?.newTab()?.setText(R.string.avatar_hair_ponytail)?.let { this.subCategoryTabs?.addTab(it) }
loadCustomizations()
}
private fun selectedExtrasCategory() {
activateButton(extrasButton)
this.activeCategory = SetupCustomizationRepository.CATEGORY_EXTRAS
this.subCategoryTabs?.removeAllTabs()
this.subcategories = listOf(SetupCustomizationRepository.SUBCATEGORY_GLASSES, SetupCustomizationRepository.SUBCATEGORY_FLOWER, SetupCustomizationRepository.SUBCATEGORY_WHEELCHAIR)
subCategoryTabs?.newTab()?.setText(R.string.avatar_glasses)?.let { this.subCategoryTabs?.addTab(it) }
subCategoryTabs?.newTab()?.setText(R.string.avatar_flower)?.let { this.subCategoryTabs?.addTab(it) }
subCategoryTabs?.newTab()?.setText(R.string.avatar_wheelchair)?.let { this.subCategoryTabs?.addTab(it) }
loadCustomizations()
}
private fun randomizeCharacter() {
val user = this.user ?: return
val updateData = HashMap<String, Any>()
updateData["preferences.size"] = chooseRandomKey(customizationRepository.getCustomizations(SetupCustomizationRepository.CATEGORY_BODY, SetupCustomizationRepository.SUBCATEGORY_SIZE, user), false)
updateData["preferences.shirt"] = chooseRandomKey(customizationRepository.getCustomizations(SetupCustomizationRepository.CATEGORY_BODY, SetupCustomizationRepository.SUBCATEGORY_SHIRT, user), false)
updateData["preferences.skin"] = chooseRandomKey(customizationRepository.getCustomizations(SetupCustomizationRepository.CATEGORY_SKIN, SetupCustomizationRepository.SUBCATEGORY_COLOR, user), false)
updateData["preferences.hair.color"] = chooseRandomKey(customizationRepository.getCustomizations(SetupCustomizationRepository.CATEGORY_HAIR, SetupCustomizationRepository.SUBCATEGORY_COLOR, user), false)
updateData["preferences.hair.base"] = chooseRandomKey(customizationRepository.getCustomizations(SetupCustomizationRepository.CATEGORY_HAIR, SetupCustomizationRepository.SUBCATEGORY_PONYTAIL, user), false)
updateData["preferences.hair.bangs"] = chooseRandomKey(customizationRepository.getCustomizations(SetupCustomizationRepository.CATEGORY_HAIR, SetupCustomizationRepository.SUBCATEGORY_BANGS, user), false)
updateData["preferences.hair.flower"] = chooseRandomKey(customizationRepository.getCustomizations(SetupCustomizationRepository.CATEGORY_EXTRAS, SetupCustomizationRepository.SUBCATEGORY_FLOWER, user), true)
updateData["preferences.chair"] = chooseRandomKey(customizationRepository.getCustomizations(SetupCustomizationRepository.CATEGORY_EXTRAS, SetupCustomizationRepository.SUBCATEGORY_WHEELCHAIR, user), true)
compositeSubscription.add(userRepository.updateUser(user, updateData).subscribeWithErrorHandler(Consumer {}))
}
@Suppress("ReturnCount")
private fun chooseRandomKey(customizations: List<SetupCustomization>, weighFirstOption: Boolean): String {
if (customizations.isEmpty()) {
return ""
}
if (weighFirstOption) {
if (random.nextInt(10) > 3) {
return customizations[0].key
}
}
return customizations[random.nextInt(customizations.size)].key
}
private fun activateButton(button: AvatarCategoryView?) {
if (this.activeButton != null) {
this.activeButton?.setActive(false)
}
this.activeButton = button
this.activeButton?.setActive(true)
val location = IntArray(2)
val params = this.caretView?.layoutParams as? RelativeLayout.LayoutParams
this.activeButton?.getLocationOnScreen(location)
val r = resources
val px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40f, r.displayMetrics).toInt()
params?.marginStart = location[0] + px
this.caretView?.layoutParams = params
}
}
| gpl-3.0 | fdb2dfa7339d14547c635a1b3bb5fbee | 48.559671 | 213 | 0.722611 | 4.814263 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/mesh/simplification/TermCriterion.kt | 1 | 998 | package de.fabmax.kool.modules.mesh.simplification
import de.fabmax.kool.modules.mesh.HalfEdgeMesh
import kotlin.math.round
/**
* Determines when to stop simplification of a mesh.
*
* @author fabmax
*/
interface TermCriterion {
fun init(mesh: HalfEdgeMesh) { }
fun isFinished(mesh: HalfEdgeMesh, nextError: Double): Boolean
}
fun terminateOnFaceCountRel(factor: Double) = object : TermCriterion {
var targetFaceCnt = Int.MAX_VALUE
override fun init(mesh: HalfEdgeMesh) { targetFaceCnt = round(mesh.faceCount * factor).toInt() }
override fun isFinished(mesh: HalfEdgeMesh, nextError: Double) = mesh.faceCount <= targetFaceCnt
}
fun terminateOnFaceCountAbs(targetFaceCnt: Int) = object : TermCriterion {
override fun isFinished(mesh: HalfEdgeMesh, nextError: Double) = mesh.faceCount <= targetFaceCnt
}
fun terminateOnError(targetError: Double) = object : TermCriterion {
override fun isFinished(mesh: HalfEdgeMesh, nextError: Double) = nextError > targetError
}
| apache-2.0 | 59c876fc7bcd7c080b4deed870ab6e99 | 34.642857 | 100 | 0.757515 | 3.669118 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSampleEntityImpl.kt | 1 | 8923 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
import java.util.UUID
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSampleEntityImpl : ChildSampleEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(SampleEntity::class.java, ChildSampleEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
@JvmField
var _data: String? = null
override val data: String
get() = _data!!
override val parentEntity: SampleEntity?
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildSampleEntityData?) : ModifiableWorkspaceEntityBase<ChildSampleEntity>(), ChildSampleEntity.Builder {
constructor() : this(ChildSampleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSampleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field ChildSampleEntity#data should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildSampleEntity
this.entitySource = dataSource.entitySource
this.data = dataSource.data
if (parents != null) {
this.parentEntity = parents.filterIsInstance<SampleEntity>().singleOrNull()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var parentEntity: SampleEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)] as? SampleEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SampleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): ChildSampleEntityData = result ?: super.getEntityData() as ChildSampleEntityData
override fun getEntityClass(): Class<ChildSampleEntity> = ChildSampleEntity::class.java
}
}
class ChildSampleEntityData : WorkspaceEntityData<ChildSampleEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSampleEntity> {
val modifiable = ChildSampleEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildSampleEntity {
val entity = ChildSampleEntityImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSampleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildSampleEntity(data, entitySource) {
this.parentEntity = parents.filterIsInstance<SampleEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSampleEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSampleEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 7c7d3f6c3a3ea5201af17e93fc70de50 | 35.125506 | 149 | 0.702678 | 5.3948 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/utils.kt | 1 | 1410 | // 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
import org.jetbrains.kotlin.lexer.KtKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeAsciiOnly
fun <T> List<T>.replace(element: T, replacer: T): List<T> {
val mutableList = toMutableList()
val index = indexOf(element)
mutableList[index] = replacer
return mutableList
}
fun String.asGetterName() =
takeIf { JvmAbi.isGetterName(it) }
?.removePrefix("get")
?.takeIf {
it.isNotEmpty() && it.first().isUpperCase()
|| it.startsWith("is") && it.length > 2 && it[2].isUpperCase()
}?.decapitalizeAsciiOnly()
?.escaped()
fun String.asSetterName() =
takeIf { JvmAbi.isSetterName(it) }
?.removePrefix("set")
?.takeIf { it.isNotEmpty() && it.first().isUpperCase() }
?.decapitalizeAsciiOnly()
?.escaped()
fun String.isPossiblyGetterOrSetterName() =
asGetterName() != null || asSetterName() != null
private val KEYWORDS = KtTokens.KEYWORDS.types.map { (it as KtKeywordToken).value }.toSet()
fun String.escaped() =
if (this in KEYWORDS || '$' in this) "`$this`"
else this
| apache-2.0 | 396278a247646ac94355e4bd44aca3f8 | 33.390244 | 158 | 0.671631 | 4.028571 | false | false | false | false |
chibatching/NearbySample | app/src/main/kotlin/com/chibatching/nearbysample/MainActivity.kt | 1 | 9004 | package com.chibatching.nearbysample
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentSender
import android.content.res.Configuration
import android.inputmethodservice.InputMethodService
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.AbsListView
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.common.api.ResultCallback
import com.google.android.gms.common.api.Status
import com.google.android.gms.nearby.Nearby
import com.google.android.gms.nearby.messages.Message
import com.google.android.gms.nearby.messages.MessageListener
import com.google.android.gms.nearby.messages.Strategy
import kotlinx.android.synthetic.activity_main.*
import kotlinx.android.synthetic.item_message_list.view.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.properties.Delegates
public class MainActivity : AppCompatActivity() {
companion object {
val TAG = "MainActivity"
val REQUEST_RESOLVE_ERROR = 1
val ENCODE = "UTF-8"
val NAMESPACE = "nearby-sample"
}
// Nearby connection callback
val callbacks = NearbyConnectionCallbacks()
// Nearby connection failed listener
val failedListener = NearbyConnectionFailedListener()
// Google Api Client for Nearby Message
val googleApiClient: GoogleApiClient by Delegates.lazy {
GoogleApiClient.Builder(this)
.addApi(Nearby.MESSAGES_API)
.addConnectionCallbacks(callbacks)
.addOnConnectionFailedListener(failedListener)
.build()
}
// Nearby Message strategy
val strategy = Strategy.Builder()
.setDiscoveryMode(Strategy.DISCOVERY_MODE_DEFAULT)
.setDistanceType(Strategy.DISCOVERY_MODE_DEFAULT)
.setTtlSeconds(Strategy.TTL_SECONDS_DEFAULT)
.build()
// Listener on message received
val messageListener = object : MessageListener() {
override fun onFound(message: Message?) {
Log.d(TAG, "onFound: ${message?.toString()}")
if (message != null) {
addNewMessage(ChatMessage.fromJson(String(message.getContent(), ENCODE)))
}
}
}
val messageAdapter: ArrayAdapter<ChatMessage> by Delegates.lazy {
MessageListAdapter(this, R.layout.item_message_list, messageList)
}
val messageList = ArrayList<ChatMessage>()
val simpleDateFormat = SimpleDateFormat("HH:mm")
var mResolvingError = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sendButton.setOnClickListener {
// Make sending message when send button clicked
val chatMessage = ChatMessage(editText.getText().toString(), System.currentTimeMillis())
editText.setText("")
textInputLayout.setHint(getString(R.string.hint_sending))
if (getCurrentFocus() != null) {
// Hide ime
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0)
}
// Publish message
val message = Message(chatMessage.toString().toByteArray(ENCODE), ChatMessage.TYPE_USER_CHAT)
Nearby.Messages.publish(googleApiClient, message, strategy)
.setResultCallback(NearbyResultCallback("send", {
// When send succeeded, show my message
textInputLayout.setHint(getString(R.string.hint_input))
addNewMessage(chatMessage)
}))
Log.d(TAG, "Send message: ${message.toString()}")
Log.d(TAG, "Send chat: ${String(message.getContent(), ENCODE)}")
}
listView.setAdapter(messageAdapter)
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL)
listView.setStackFromBottom(true)
}
override fun onStart() {
super.onStart()
if (!googleApiClient.isConnected()) {
googleApiClient.connect()
}
}
override fun onStop() {
if (googleApiClient.isConnected()) {
Nearby.Messages.unsubscribe(googleApiClient, messageListener)
}
googleApiClient.disconnect()
super.onStop()
}
// This is called in response to a button tap in the Nearby permission dialog.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false
if (resultCode == Activity.RESULT_OK) {
Log.d(TAG, "Start subscribe")
Nearby.Messages.subscribe(googleApiClient, messageListener)
} else {
Log.d(TAG, "Failed to resolve error with code $resultCode")
}
}
}
// Add new message to message list and update list view
private fun addNewMessage(message: ChatMessage) {
if (!messageList.contains(message)) {
messageList.add(message)
Collections.sort(messageList)
[email protected] {
messageAdapter.notifyDataSetChanged()
}
}
}
// Callbacks for Nearby Connection
private inner class NearbyConnectionCallbacks : GoogleApiClient.ConnectionCallbacks {
override fun onConnected(connectionHint: Bundle?) {
Log.d(TAG, "onConnected: $connectionHint")
Nearby.Messages.getPermissionStatus(googleApiClient)
.setResultCallback(NearbyResultCallback("getPermissionStatus", {
Log.d(TAG, "Start subscribe")
Nearby.Messages.subscribe(googleApiClient, messageListener)
}))
}
override fun onConnectionSuspended(p0: Int) {
}
}
// Listener when Nearby Connection failed
private class NearbyConnectionFailedListener : GoogleApiClient.OnConnectionFailedListener {
override fun onConnectionFailed(p0: ConnectionResult?) {
Log.d(TAG, "onConnectionFailed")
}
}
// Message sending/receiving callback
private inner class NearbyResultCallback(
val method: String, val runOnSuccess: () -> Unit) : ResultCallback<Status> {
override fun onResult(status: Status) {
if (status.isSuccess()) {
Log.d(TAG, "$method succeeded.")
[email protected] { runOnSuccess() }
} else {
// Currently, the only resolvable error is that the device is not opted
// in to Nearby. Starting the resolution displays an opt-in dialog.
if (status.hasResolution()) {
if (!mResolvingError) {
try {
status.startResolutionForResult(this@MainActivity, REQUEST_RESOLVE_ERROR)
mResolvingError = true
} catch (e: IntentSender.SendIntentException) {
Toast.makeText(this@MainActivity, "$method failed with exception: " + e, Toast.LENGTH_SHORT).show()
}
} else {
// This will be encountered on initial startup because we do
// both publish and subscribe together. So having a toast while
// resolving dialog is in progress is confusing, so just log it.
Log.d(TAG, "$method failed with status: $status while resolving error.")
}
} else {
Log.d(TAG, "$method failed with: $status resolving error: $mResolvingError")
}
}
}
}
private inner class MessageListAdapter(context: Context, val resId: Int, array: ArrayList<ChatMessage>) :
ArrayAdapter<ChatMessage>(context, resId, array) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
var view: View? = convertView
if (view == null) {
view = getLayoutInflater().inflate(resId, null, false)
}
val message = getItem(position)
view?.messageText?.setText(message.text)
view?.timestampText?.setText(simpleDateFormat.format(Date(message.timestamp)))
return view
}
}
}
| apache-2.0 | 0406573993d0266adf1238fb47e43aea | 39.742081 | 127 | 0.633718 | 5.198614 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/frames/HsStackFrame.kt | 1 | 5640 | package org.jetbrains.haskell.debugger.frames
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.ui.SimpleTextAttributes
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.openapi.application.ApplicationManager
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.XDebuggerUtil
import com.intellij.openapi.vfs.LocalFileSystem
import java.io.File
import org.jetbrains.haskell.debugger.parser.LocalBinding
import java.util.ArrayList
import com.intellij.ui.ColoredTextContainer
import com.intellij.icons.AllIcons
import com.intellij.xdebugger.XDebuggerBundle
import org.jetbrains.haskell.debugger.parser.HsStackFrameInfo
import org.jetbrains.haskell.debugger.procdebuggers.ProcessDebugger
abstract class HsStackFrame(val debugger: ProcessDebugger,
val stackFrameInfo: HsStackFrameInfo) : XStackFrame() {
companion object {
private val STACK_FRAME_EQUALITY_OBJECT = Object()
}
var obsolete: Boolean = true
override fun getEqualityObject(): Any? = STACK_FRAME_EQUALITY_OBJECT
protected var bindingsList: XValueChildrenList? = null
init {
setBindingsList(stackFrameInfo.bindings)
}
protected fun setBindingsList(bindings: List<LocalBinding>?) {
if (bindings != null) {
bindingsList = XValueChildrenList()
for (binding in bindings) {
bindingsList?.add(HsDebugValue(binding))
}
}
}
/**
* This method always returns null because we need to switch off default debug highlighting provided by
* ExecutionPointHighlighter inside XDebuggerManagerImpl. Custom highlighting provided by
* HsExecutionPointHighlighter inside HsDebugSessionListener. Also, see hackSourcePosition property below
*
* @see com.intellij.xdebugger.impl.XDebuggerManagerImpl
*/
override fun getSourcePosition(): XSourcePosition? = null
private var _sourcePositionSet: Boolean = false
private var _hackSourcePosition: XSourcePosition? = null
/**
* This property holds XSourcePosition value. Use it instead of getSourcePosition()
*/
val hackSourcePosition: XSourcePosition?
get() {
if (!_sourcePositionSet) {
_hackSourcePosition = if (stackFrameInfo.filePosition == null) null else
XDebuggerUtil.getInstance()!!.createPosition(
LocalFileSystem.getInstance()?.findFileByIoFile(File(stackFrameInfo.filePosition.filePath)),
stackFrameInfo.filePosition.normalizedStartLine)
_sourcePositionSet = true
}
return _hackSourcePosition
}
/**
* Returns evaluator (to use 'Evaluate expression' and other such tools)
*/
override fun getEvaluator(): XDebuggerEvaluator? = HsDebuggerEvaluator(debugger)
/**
* Makes stack frame appearance customization in frames list. Sets function name, source file name and part of code
* (span) that this frame represents
*/
override fun customizePresentation(component: ColoredTextContainer) {
val position = hackSourcePosition
if (position != null) {
if (stackFrameInfo.functionName != null) {
component.append(stackFrameInfo.functionName, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES)
component.append(" (", SimpleTextAttributes.REGULAR_ATTRIBUTES)
}
component.append(position.file.name + ":", SimpleTextAttributes.REGULAR_ATTRIBUTES)
setSourceSpan(component)
if (stackFrameInfo.functionName != null) {
component.append(")", SimpleTextAttributes.REGULAR_ATTRIBUTES)
}
component.setIcon(AllIcons.Debugger.StackFrame)
} else {
component.append(XDebuggerBundle.message("invalid.frame") ?: "<invalid frame>",
SimpleTextAttributes.ERROR_ATTRIBUTES)
}
}
/**
* Creates HsDebugValue instances for local bindings in stackFrameInfo.bindings and adds them in passed node. These
* added HsDebugValue instances are shown in 'Variables' panel of 'Debug' tool window.
*/
override fun computeChildren(node: XCompositeNode) {
if (node.isObsolete) {
return
}
ApplicationManager.getApplication()!!.executeOnPooledThread(object : Runnable {
override fun run() {
try {
if (bindingsList == null || obsolete) {
tryGetBindings()
obsolete = false
}
if (bindingsList != null) {
node.addChildren(bindingsList as XValueChildrenList, true)
}
} catch (e: Exception) {
e.printStackTrace()
node.setErrorMessage("Unable to display frame variables")
}
}
})
}
protected abstract fun tryGetBindings()
/**
* Sets the bounds of code in source file this frame represents"
*/
private fun setSourceSpan(component: ColoredTextContainer) {
val srcSpan: String
if (stackFrameInfo.filePosition != null) {
srcSpan = stackFrameInfo.filePosition.spanToString()
} else {
srcSpan = "<exception thrown>"
}
component.append(srcSpan, SimpleTextAttributes.REGULAR_ATTRIBUTES)
}
}
| apache-2.0 | 3309bd80f8438b1b849a02d142aff8f9 | 39 | 120 | 0.657801 | 5.470417 | false | false | false | false |
androidx/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/gestures/TouchSlopDragGestureDetectorDemo.kt | 3 | 3718 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos.gestures
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
/**
* Simple [detectVerticalDragGestures] and [detectHorizontalDragGestures] demo.
*/
@Composable
fun DragGestureFilterDemo() {
val verticalColor = Color(0xfff44336)
val horizontalColor = Color(0xff2196f3)
val offset = remember { mutableStateOf(Offset.Zero) }
val canStartVertically = remember { mutableStateOf(true) }
val color =
if (canStartVertically.value) {
verticalColor
} else {
horizontalColor
}
val (offsetX, offsetY) =
with(LocalDensity.current) { offset.value.x.toDp() to offset.value.y.toDp() }
Column {
Text(
"Demonstrates standard dragging (when a slop has to be exceeded before dragging can " +
"start) and customization of the direction in which dragging can occur."
)
Text(
"When the box is blue, it can only be dragged horizontally. When the box is red, it" +
" can only be dragged vertically."
)
Box(
Modifier.offset(offsetX, offsetY)
.fillMaxSize()
.wrapContentSize(Alignment.Center)
.size(192.dp)
.pointerInput(Unit) {
if (canStartVertically.value) {
detectVerticalDragGestures(
onDragEnd = { canStartVertically.value = !canStartVertically.value }
) { _, dragDistance ->
offset.value =
Offset(x = offset.value.x, y = offset.value.y + dragDistance)
}
} else {
detectHorizontalDragGestures(
onDragEnd = { canStartVertically.value = !canStartVertically.value }
) { _, dragDistance ->
offset.value =
Offset(x = offset.value.x + dragDistance, y = offset.value.y)
}
}
}
.background(color)
)
}
}
| apache-2.0 | c92cb941829f9e2665819056005e992c | 37.729167 | 99 | 0.64497 | 4.860131 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/style/TextForegroundStyle.kt | 3 | 4835 | /*
* 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.
*/
@file:JvmName("TextDrawStyleKt")
package androidx.compose.ui.text.style
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ShaderBrush
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.isSpecified
import androidx.compose.ui.graphics.lerp as lerpColor
import androidx.compose.ui.text.lerpDiscrete
import androidx.compose.ui.util.lerp
/**
* An internal interface to represent possible ways to draw Text e.g. color, brush. This interface
* aims to unify unspecified versions of complementary drawing styles. There are some guarantees
* as following;
*
* - If [color] is not [Color.Unspecified], brush is null.
* - If [brush] is not null, color is [Color.Unspecified].
* - Both [color] can be [Color.Unspecified] and [brush] null, indicating that nothing is specified.
* - [SolidColor] brushes are stored as regular [Color].
*/
internal interface TextForegroundStyle {
val color: Color
val brush: Brush?
val alpha: Float
fun merge(other: TextForegroundStyle): TextForegroundStyle {
// This control prevents Color or Unspecified TextForegroundStyle to override an existing
// Brush. It is a temporary measure to prevent Material Text composables to remove given
// Brush from a TextStyle.
// TODO(b/230787077): Just return other.takeOrElse { this } when Brush is stable.
return when {
other is BrushStyle && this is BrushStyle ->
BrushStyle(other.value, other.alpha.takeOrElse { this.alpha })
other is BrushStyle && this !is BrushStyle -> other
other !is BrushStyle && this is BrushStyle -> this
else -> other.takeOrElse { this }
}
}
fun takeOrElse(other: () -> TextForegroundStyle): TextForegroundStyle {
return if (this != Unspecified) this else other()
}
object Unspecified : TextForegroundStyle {
override val color: Color
get() = Color.Unspecified
override val brush: Brush?
get() = null
override val alpha: Float
get() = Float.NaN
}
companion object {
fun from(color: Color): TextForegroundStyle {
return if (color.isSpecified) ColorStyle(color) else Unspecified
}
fun from(brush: Brush?, alpha: Float): TextForegroundStyle {
return when (brush) {
null -> Unspecified
is SolidColor -> from(brush.value.modulate(alpha))
is ShaderBrush -> BrushStyle(brush, alpha)
}
}
}
}
private data class ColorStyle(
val value: Color
) : TextForegroundStyle {
init {
require(value.isSpecified) {
"ColorStyle value must be specified, use TextForegroundStyle.Unspecified instead."
}
}
override val color: Color
get() = value
override val brush: Brush?
get() = null
override val alpha: Float
get() = color.alpha
}
private data class BrushStyle(
val value: ShaderBrush,
override val alpha: Float
) : TextForegroundStyle {
override val color: Color
get() = Color.Unspecified
override val brush: Brush
get() = value
}
/**
* If both TextForegroundStyles do not represent a Brush, lerp the color values. Otherwise, lerp
* start to end discretely.
*/
internal fun lerp(
start: TextForegroundStyle,
stop: TextForegroundStyle,
fraction: Float
): TextForegroundStyle {
return if ((start !is BrushStyle && stop !is BrushStyle)) {
TextForegroundStyle.from(lerpColor(start.color, stop.color, fraction))
} else if (start is BrushStyle && stop is BrushStyle) {
TextForegroundStyle.from(
lerpDiscrete(start.brush, stop.brush, fraction),
lerp(start.alpha, stop.alpha, fraction)
)
} else {
lerpDiscrete(start, stop, fraction)
}
}
internal fun Color.modulate(alpha: Float): Color = when {
alpha.isNaN() || alpha >= 1f -> this
else -> this.copy(alpha = this.alpha * alpha)
}
private fun Float.takeOrElse(block: () -> Float): Float {
return if (this.isNaN()) block() else this
} | apache-2.0 | b5a0cf66cccd1c94f3a75967200be1e2 | 31.675676 | 100 | 0.668459 | 4.290151 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/roots/impl/BundledResourceUsageCollector.kt | 4 | 6223 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.impl
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.NonUrgentExecutor
import com.intellij.util.io.URLUtil
import com.intellij.util.io.exists
import com.intellij.util.io.isDirectory
import org.jetbrains.concurrency.*
import java.nio.file.Path
/**
* Reports references to resources bundled with IDE or plugin distribution from users' projects (e.g. libraries which include IDE_HOME/lib/junit.jar).
*/
internal class BundledResourceUsageCollector : ProjectUsagesCollector() {
companion object {
val GROUP = EventLogGroup("bundled.resource.reference", 1)
/**
* Records path to a file located under 'lib' subdirectory of IDE installation directory and referenced from a library.
*/
@JvmField
val IDE_FILE = GROUP.registerEvent("ide.file", EventFields.StringValidatedByCustomRule<BundledResourcePathValidationRule>("path"))
/**
* Records path to a file located in an installation directory for a plugin and referenced from a library.
*/
@JvmField
val PLUGIN_FILE = GROUP.registerEvent("plugin.file", EventFields.PluginInfo, EventFields.StringValidatedByCustomRule<BundledResourcePathValidationRule>("path"))
}
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(project: Project, indicator: ProgressIndicator?): CancellablePromise<Set<MetricEvent>> {
var action = ReadAction.nonBlocking<Set<VirtualFile>> { collectLibraryFiles(project) }
if (indicator != null) {
action = action.wrapProgress(indicator)
}
@Suppress("UNCHECKED_CAST")
return action
.expireWith(project)
.submit(NonUrgentExecutor.getInstance())
.thenAsync { files ->
runAsync {
files.mapNotNullTo(LinkedHashSet()) { convertToMetric(it.path.substringBefore(URLUtil.JAR_SEPARATOR)) }
}
} as CancellablePromise<Set<MetricEvent>>
}
private fun collectLibraryFiles(project: Project): Set<VirtualFile> {
val usedLibraries = LinkedHashSet<Library>()
OrderEnumerator.orderEntries(project).librariesOnly().forEachLibrary { usedLibraries.add(it) }
val files = LinkedHashSet<VirtualFile>()
usedLibraries.flatMapTo(files) { library ->
library.getFiles(OrderRootType.CLASSES).asList()
}
return files
}
private val pluginByKindAndDirectory by lazy {
PluginManagerCore.getLoadedPlugins()
.filter { it.pluginPath.isDirectory() }
.associateBy { it.kind to it.pluginPath.fileName.toString() }
}
private fun convertToMetric(path: String): MetricEvent? {
if (FileUtil.isAncestor(ideLibPath, path, false)) {
val relativePath = FileUtil.getRelativePath(ideLibPath, path, '/')!!
return IDE_FILE.metric(relativePath)
}
for (kind in PluginKind.values()) {
if (FileUtil.isAncestor(kind.homePath, path, true)) {
val relativePath = FileUtil.getRelativePath(kind.homePath, path, '/')!!
val firstName = relativePath.substringBefore('/')
val pathInPlugin = relativePath.substringAfter('/')
val plugin = pluginByKindAndDirectory[kind to firstName]
if (plugin != null) {
val pluginInfo = getPluginInfoByDescriptor(plugin)
if (pluginInfo.isSafeToReport()) {
return PLUGIN_FILE.metric(pluginInfo, pathInPlugin)
}
}
}
}
return null
}
}
private enum class PluginKind {
Bundled {
override val homePath: String by lazy { FileUtil.toSystemIndependentName(PathManager.getPreInstalledPluginsPath()) }
},
Custom {
override val homePath: String by lazy { FileUtil.toSystemIndependentName(PathManager.getPluginsPath()) }
};
abstract val homePath: String
}
private val IdeaPluginDescriptor.kind: PluginKind
get() = if (isBundled) PluginKind.Bundled else PluginKind.Custom
private val ideLibPath by lazy { FileUtil.toSystemIndependentName(PathManager.getLibPath()) }
internal class BundledResourcePathValidationRule : CustomValidationRule() {
private val pluginKindAndDirectoryById by lazy {
PluginManagerCore.getLoadedPlugins()
.filter { it.pluginPath.isDirectory() }
.associateBy({ it.pluginId.idString }, { it.kind to it.pluginPath.fileName.toString() })
}
override fun getRuleId(): String {
return "bundled_resource_path"
}
override fun doValidate(data: String, context: EventContext): ValidationResultType {
if (hasPluginField(context)) {
if (!isReportedByJetBrainsPlugin(context)) {
return ValidationResultType.REJECTED
}
val (kind, pluginDirectoryName) = pluginKindAndDirectoryById[context.eventData["plugin"]] ?: return ValidationResultType.REJECTED
if (Path.of(kind.homePath, pluginDirectoryName, data).exists()) {
return ValidationResultType.ACCEPTED
}
return ValidationResultType.REJECTED
}
if (Path.of(ideLibPath, data).exists()) {
return ValidationResultType.ACCEPTED
}
return ValidationResultType.REJECTED
}
} | apache-2.0 | 88e23aa1038a89b93c0faeb1d984f133 | 40.493333 | 164 | 0.749317 | 4.757645 | false | false | false | false |
jwren/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/importing/AbstractOpenProjectProvider.kt | 3 | 5073 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.importing
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.externalSystem.ExternalSystemManager
import com.intellij.openapi.externalSystem.autolink.UnlinkedProjectNotificationAware
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.ui.getPresentablePath
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.apache.commons.lang.StringUtils
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
@ApiStatus.Experimental
abstract class AbstractOpenProjectProvider : OpenProjectProvider {
protected open val systemId: ProjectSystemId by lazy {
/**
* Tries to resolve external system id
* Note: Implemented approach is super heuristics.
* Please, override [systemId] to avoid discrepancy with real id.
*/
LOG.warn("Class ${javaClass.name} have to override AbstractOpenProjectProvider.systemId. " +
"Resolving of systemId will be removed in future releases.")
val readableName = StringUtils.splitByCharacterTypeCamelCase(javaClass.simpleName).first()
val manager = ExternalSystemManager.EP_NAME.findFirstSafe {
StringUtils.equalsIgnoreCase(StringUtils.splitByCharacterTypeCamelCase(it.javaClass.simpleName).first(), readableName)
}
manager?.systemId ?: ProjectSystemId(readableName.toUpperCase())
}
protected abstract fun isProjectFile(file: VirtualFile): Boolean
@Deprecated("redundant method", replaceWith = ReplaceWith("linkToExistingProject(projectFile, project)"))
protected open fun linkAndRefreshProject(projectDirectory: Path, project: Project) {
throw UnsupportedOperationException("use linkToExistingProject(VirtualFile, Project) instead")
}
override fun canOpenProject(file: VirtualFile): Boolean {
return if (file.isDirectory) file.children.any(::isProjectFile) else isProjectFile(file)
}
override fun openProject(projectFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
LOG.debug("Open project from $projectFile")
val projectDirectory = getProjectDirectory(projectFile)
if (focusOnOpenedSameProject(projectDirectory.toNioPath())) {
return null
}
val nioPath = projectDirectory.toNioPath()
val isValidIdeaProject = isValidProjectPath(nioPath)
val options = OpenProjectTask(
isNewProject = !isValidIdeaProject,
forceOpenInNewFrame = forceOpenInNewFrame,
projectToClose = projectToClose,
runConfigurators = false,
beforeOpen = { project ->
if (isValidIdeaProject) {
UnlinkedProjectNotificationAware.enableNotifications(project, systemId)
}
else {
project.putUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT, true)
project.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, true)
ApplicationManager.getApplication().invokeAndWait {
linkToExistingProject(projectFile, project)
}
updateLastProjectLocation(nioPath)
}
true
}
)
return ProjectManagerEx.getInstanceEx().openProject(nioPath, options)
}
override fun linkToExistingProject(projectFile: VirtualFile, project: Project) {
LOG.debug("Import project from $projectFile")
val projectDirectory = getProjectDirectory(projectFile)
linkAndRefreshProject(projectDirectory.toNioPath(), project)
}
fun linkToExistingProject(projectFilePath: String, project: Project) {
val localFileSystem = LocalFileSystem.getInstance()
val projectFile = localFileSystem.refreshAndFindFileByPath(projectFilePath)
if (projectFile == null) {
val shortPath = getPresentablePath(projectFilePath)
throw IllegalArgumentException(ExternalSystemBundle.message("error.project.does.not.exist", systemId.readableName, shortPath))
}
linkToExistingProject(projectFile, project)
}
private fun focusOnOpenedSameProject(projectDirectory: Path): Boolean {
for (project in ProjectManager.getInstance().openProjects) {
if (isSameProject(projectDirectory, project)) {
focusProjectWindow(project, false)
return true
}
}
return false
}
private fun getProjectDirectory(file: VirtualFile): VirtualFile {
return if (file.isDirectory) file else file.parent
}
companion object {
protected val LOG = logger<AbstractOpenProjectProvider>()
}
} | apache-2.0 | bba2226e97770c7565bd6ab9aa6d3053 | 42.367521 | 158 | 0.769564 | 5.192426 | false | false | false | false |
mewebstudio/Kotlin101 | src/Functions/OperatorOverloading.kt | 1 | 545 | package Kotlin101.Functions.OperatorOverloading
fun main (Args : Array<String>){
var batman = SuperPower()
batman.say()
+batman
batman.say()
-batman
batman.say()
var robin = SuperPower()
robin.say()
}
public class SuperPower(){
var power : Int = 1
var action = "Neutral"
fun plus(){
power++
action = "+"
}
fun minus(){
power--
action = "-"
}
fun say(){
println(action + " " + power)
}
override fun toString() : String = "$power"
} | bsd-3-clause | 5bc1559bd935aafcdafa717701d11c36 | 15.058824 | 47 | 0.53211 | 3.811189 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/InstanceFactory.kt | 1 | 5680 | package com.cognifide.gradle.aem.common.instance
import com.cognifide.gradle.aem.AemExtension
import com.cognifide.gradle.common.utils.Formats
import com.cognifide.gradle.common.utils.Patterns
class InstanceFactory(val aem: AemExtension) {
fun defaultPair() = listOf(defaultAuthor(), defaultPublish())
fun defaultAuthor() = remote(InstanceUrl.HTTP_AUTHOR_DEFAULT)
fun defaultPublish() = remote(InstanceUrl.HTTP_PUBLISH_DEFAULT)
fun remote(httpUrl: String, configurer: Instance.() -> Unit = {}): Instance {
return Instance(aem).apply {
val instanceUrl = InstanceUrl.parse(httpUrl)
this.httpUrl = instanceUrl.httpUrl
this.user = instanceUrl.user
this.password = instanceUrl.password
this.env = instanceUrl.env
this.id = instanceUrl.id
configurer()
validate()
}
}
fun local(httpUrl: String, configurer: LocalInstance.() -> Unit = {}): LocalInstance {
return LocalInstance(aem).apply {
val instanceUrl = InstanceUrl.parse(httpUrl)
if (instanceUrl.user != LocalInstance.USER) {
throw LocalInstanceException("User '${instanceUrl.user}' (other than 'admin') is not allowed while using local instance(s).")
}
this.httpUrl = instanceUrl.httpUrl
this.password = instanceUrl.password
this.id = instanceUrl.id
this.debugPort = instanceUrl.debugPort
this.env = instanceUrl.env
configurer()
validate()
}
}
fun parse(str: String, configurer: Instance.() -> Unit = {}): List<Instance> {
return (Formats.toList(str) ?: listOf()).map { remote(it, configurer) }
}
fun parseProperties() = parseProperties(aem.project.rootProject.properties)
fun parseProperties(allProps: Map<String, *>): List<Instance> {
val instanceNames = allProps.filterKeys { prop ->
!prop.startsWith("$NAME_DEFAULT.") && (ALL_PROPS.any {
Regex("^instance.$NAME_REGEX.$it\$").matches(prop) })
}.keys.mapNotNull { p ->
val name = p.split(".")[1]
val nameParts = name.split("-")
if (nameParts.size != 2) {
aem.logger.warn("Instance name has invalid format '$name' in property '$p'.")
return@mapNotNull null
}
name
}.distinct()
return instanceNames.sorted().fold(mutableListOf()) { result, name ->
val defaultProps = prefixedProperties(allProps, NAME_DEFAULT)
val props = defaultProps + prefixedProperties(allProps, "instance.$name")
result.add(singleFromProperties(name, props, result))
result
}
}
private fun prefixedProperties(allProps: Map<String, *>, prefix: String) = allProps.filterKeys {
Patterns.wildcard(it, "$prefix.*")
}.entries.fold(mutableMapOf<String, String>()) { result, e ->
val (key, value) = e
val prop = key.substringAfter("$prefix.")
result.apply { put(prop, value as String) }
}
private fun singleFromProperties(name: String, props: Map<String, String>, others: List<Instance>): Instance {
return when (props["type"]?.let { PhysicalType.of(it) } ?: PhysicalType.REMOTE) {
PhysicalType.LOCAL -> localFromProperties(name, props, others)
PhysicalType.REMOTE -> remoteFromProperties(name, props, others)
}
}
private fun localFromProperties(name: String, props: Map<String, String>, others: List<Instance>): LocalInstance {
val httpUrl = props["httpUrl"] ?: httpUrlProperty(name, others)
return local(httpUrl) {
this.name = name
props["enabled"]?.let { this.enabled = it.toBoolean() }
props["password"]?.let { this.password = it }
props["jvmOpts"]?.let { this.jvmOpts = it.split(" ") }
props["startOpts"]?.let { this.startOpts = it.split(" ") }
props["runModes"]?.let { this.runModes = it.split(",") }
props["debugPort"]?.let { this.debugPort = it.toInt() }
props["debugAddress"]?.let { this.debugAddress = it }
props["openPath"]?.let { this.openPath = it }
this.properties.putAll(props.filterKeys { !LOCAL_PROPS.contains(it) })
}
}
private fun remoteFromProperties(name: String, props: Map<String, String>, others: List<Instance>): Instance {
val httpUrl = props["httpUrl"] ?: httpUrlProperty(name, others)
return remote(httpUrl) {
this.name = name
props["enabled"]?.let { this.enabled = it.toBoolean() }
props["user"]?.let { this.user = it }
props["password"]?.let { this.password = it }
this.properties.putAll(props.filterKeys { !REMOTE_PROPS.contains(it) })
}
}
private fun httpUrlProperty(name: String, others: List<Instance>): String {
val type = IdType.byId(name.split("-")[1])
val port = others.filter { it.type == type }.map { it.httpPort }.maxOrNull()?.let { it + 1 } ?: type.httpPortDefault
return "${InstanceUrl.HTTP_HOST_DEFAULT}:$port"
}
companion object {
const val NAME_DEFAULT = "instance.default"
const val NAME_REGEX = "[\\w_]+-[\\w_]+"
val LOCAL_PROPS = listOf("httpUrl", "enabled", "type", "password", "jvmOpts", "startOpts", "runModes",
"debugPort", "debugAddress", "openPath")
val REMOTE_PROPS = listOf("httpUrl", "enabled", "type", "user", "password")
val ALL_PROPS = (LOCAL_PROPS + REMOTE_PROPS).toSet()
}
}
| apache-2.0 | d5ede39d476a00976c029545cd96cc0a | 40.764706 | 141 | 0.601408 | 4.29003 | false | false | false | false |
blan4/MangaReader | app/src/main/java/org/seniorsigan/mangareader/ui/MangaActivity.kt | 1 | 4015 | package org.seniorsigan.mangareader.ui
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.FloatingActionButton
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import org.jetbrains.anko.find
import org.jetbrains.anko.onClick
import org.jetbrains.anko.onUiThread
import org.seniorsigan.mangareader.App
import org.seniorsigan.mangareader.INTENT_MANGA
import org.seniorsigan.mangareader.R
import org.seniorsigan.mangareader.models.MangaItem
import org.seniorsigan.mangareader.ui.widgets.SimpleImageViewFacade
class MangaActivity : AppCompatActivity() {
private lateinit var toolbar: Toolbar
private lateinit var collapsingToolbar: CollapsingToolbarLayout
private lateinit var fab: FloatingActionButton
private lateinit var description: TextView
private lateinit var coverView: SimpleImageViewFacade
private var renderBookmarkMenu: (MangaItem) -> Unit = {}
private var saveOrRemove: () -> Unit = {}
private val searchEngine: String = "readmanga"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_manga)
toolbar = find<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
collapsingToolbar = find<CollapsingToolbarLayout>(R.id.toolbar_layout)
fab = find<FloatingActionButton>(R.id.fab)
description = find<TextView>(R.id.manga_description)
coverView = SimpleImageViewFacade(this, findViewById(R.id.manga_cover))
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val mangaIntent = intent.getSerializableExtra(INTENT_MANGA) as MangaItem?
if (mangaIntent != null) {
render(mangaIntent)
App.mangaSearchController.find(searchEngine, mangaIntent.url, { response ->
onUiThread {
render(response.data)
}
})
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_manga, menu)
renderBookmarkMenu = renderBookmarkMenuLazy(menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
finish()
true
}
R.id.action_add_bookmark -> {
saveOrRemove()
true
}
R.id.action_remove_bookmark -> {
saveOrRemove()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun renderBookmarkMenuLazy(menu: Menu) = { manga: MangaItem ->
App.bookmarkManager.find(manga, { bookmark ->
if (bookmark == null) {
menu.findItem(R.id.action_add_bookmark).isVisible = true
menu.findItem(R.id.action_remove_bookmark).isVisible = false
} else {
menu.findItem(R.id.action_add_bookmark).isVisible = false
menu.findItem(R.id.action_remove_bookmark).isVisible = true
}
})
}
private fun saveOrRemoveLazy(manga: MangaItem) = {
App.bookmarkManager.saveOrRemove(manga)
renderBookmarkMenu(manga)
}
private fun render(manga: MangaItem?) {
if (manga == null) return
saveOrRemove = saveOrRemoveLazy(manga)
description.text = manga.description
supportActionBar?.title = manga.title
collapsingToolbar.title = manga.title
coverView.load(manga.coverURL)
renderBookmarkMenu(manga)
fab.onClick { view ->
startActivity(with(Intent(this, ChaptersActivity::class.java), {
putExtra(INTENT_MANGA, manga)
this
}))
}
}
}
| mit | 86642ae299fc1a4c67e10a61fa4300ea | 35.5 | 87 | 0.655542 | 4.774078 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/ScriptGenerator.kt | 4 | 3940 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.wm.impl.FocusManagerImpl
import com.intellij.testGuiFramework.generators.ComponentCodeGenerator
import com.intellij.testGuiFramework.generators.Generators
import com.intellij.testGuiFramework.recorder.ui.KeyUtil
import com.intellij.ui.KeyStrokeAdapter
import java.awt.Component
import java.awt.Point
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import javax.swing.KeyStroke.getKeyStrokeForEvent
/**
* @author Sergey Karashevich
*/
object ScriptGenerator {
private val generators: List<ComponentCodeGenerator<*>> = Generators.getGenerators()
fun processTyping(keyEvent: KeyEvent) {
ContextChecker.checkContext(FocusManagerImpl.getGlobalInstance().focusOwner, keyEvent)
Typer.type(keyEvent)
}
fun processKeyActionEvent(action: AnAction, event: AnActionEvent) {
val keyEvent = event.inputEvent as KeyEvent
val actionId = event.actionManager.getId(action)
if (actionId != null) {
if (ignore(actionId)) return
addToScript("""//invokeAction("$actionId")""")
}
val keyStroke = getKeyStrokeForEvent(keyEvent)
val keyStrokeStr = KeyStrokeAdapter.toString(keyStroke)
if (ignore(keyStrokeStr)) return
addToScript("""shortcut("$keyStrokeStr")""")
}
fun clickComponent(component: Component, convertedPoint: Point, mouseEvent: MouseEvent) {
if (!isPopupList(component)) {
ContextChecker.checkContext(component, mouseEvent)
}
val suitableGenerator = generators.filter { generator -> generator.accept(component) }.sortedByDescending(
ComponentCodeGenerator<*>::priority).firstOrNull() ?: return
val code = suitableGenerator.generateCode(component, mouseEvent, convertedPoint)
addToScript(code)
}
fun processMainMenuActionEvent(action: AnAction, event: AnActionEvent) {
val prohibitedPlaces = setOf("NavBarToolbar", "MainToolbar", "DebuggerToolbar")
val actionId: String? = ActionManager.getInstance().getId(action)
if (actionId == null) return
if (event.place != "MainMenu") {
if (prohibitedPlaces.contains(event.place)) return
addToScript("//invokeAction(\"$actionId\")")
return
}
addToScript("""invokeMainMenu("$actionId")""")
}
fun addToScript(code: String) {
Typer.flushBuffer()
Writer.writeWithIndent(code)
}
private fun isPopupList(component: Component) = component.javaClass.name.toLowerCase().contains("listpopup")
private fun ignore(actionOrShortCut: String): Boolean {
val ignoreActions = listOf("EditorBackSpace")
val ignoreShortcuts = listOf("space")
return ignoreActions.contains(actionOrShortCut) || ignoreShortcuts.contains(actionOrShortCut)
}
}
private object Typer {
private val strBuffer = StringBuilder()
fun type(keyEvent: KeyEvent) {
if(keyEvent.keyCode == KeyEvent.VK_BACK_SPACE && !strBuffer.isEmpty()){
strBuffer.setLength(strBuffer.length - 1)
} else {
strBuffer.append(KeyUtil.patch(keyEvent.keyChar))
}
}
fun flushBuffer() {
if (strBuffer.isEmpty()) return
Writer.writeWithIndent("""typeText("${strBuffer}")""")
strBuffer.setLength(0)
}
} | apache-2.0 | 0462d6b39905f56993ee6a88b2f3ed46 | 34.827273 | 110 | 0.74467 | 4.565469 | false | false | false | false |
MaTriXy/gradle-play-publisher-1 | common/validation/src/main/kotlin/com/github/triplet/gradle/common/validation/RuntimeValidationPlugin.kt | 1 | 873 | package com.github.triplet.gradle.common.validation
import com.android.Version
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.util.GradleVersion
import org.gradle.util.VersionNumber
internal class RuntimeValidationPlugin : Plugin<Project> {
override fun apply(project: Project) {
check(project === project.rootProject)
val agpVersion = try {
VersionNumber.parse(Version.ANDROID_GRADLE_PLUGIN_VERSION)
} catch (e: NoClassDefFoundError) {
null
}
val validator = RuntimeValidator(
GradleVersion.current(), MIN_GRADLE_VERSION, agpVersion, MIN_AGP_VERSION)
validator.validate()
}
private companion object {
val MIN_GRADLE_VERSION = GradleVersion.version("6.5")
val MIN_AGP_VERSION = VersionNumber.parse("4.1.0-beta01")
}
}
| mit | 55bbb5b2c927dca7c6ae367555058086 | 30.178571 | 89 | 0.683849 | 4.237864 | false | false | false | false |
Sugarya/GoertzPro | app/src/main/java/com/sugary/goertzpro/widget/popup/BottomPopupBuilder.kt | 1 | 2779 | package com.sugary.goertzpro.widget.popup
import android.graphics.drawable.BitmapDrawable
import android.view.*
import android.widget.PopupWindow
import com.sugary.goertzpro.R
import java.lang.IllegalArgumentException
/**
* Created by Ethan Ruan on 2018/12/29.
* 底部弹窗
*/
class BottomPopupBuilder {
init {
}
private lateinit var mPopupWindow: PopupWindow
private val mProperty: BottomPopupProperty = BottomPopupProperty()
var isOutsideTouchable: Boolean = true
set(value) {
field = value
mProperty.isOutsideTouchable = value
}
var popupAlpha: Float = 1f
set(value) {
field = value
mProperty.popupAlpha = value
}
var contentView: View? = null
set(value) {
field = value
mProperty.contentView = value
}
var window: Window? = null
set(value) {
field = value
mProperty.window = value
}
var newPopupEveryShow: Boolean = false
fun createAndShow(parentView: View): PopupWindow {
if(!newPopupEveryShow || (newPopupEveryShow && !this::mPopupWindow.isInitialized)){
val contentViewFromProperty = mProperty.contentView
?: throw IllegalArgumentException("Please setup the property of contentView")
mPopupWindow = PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
setBackgroundDrawable(BitmapDrawable())
isFocusable = true
isTouchable = true
isOutsideTouchable = mProperty.isOutsideTouchable
animationStyle = R.style.PopupWindowAnimation
contentView = contentViewFromProperty
setOnDismissListener {
setBackgroundAlpha(1f)
}
}
}
if (mPopupWindow.isShowing) {
mPopupWindow.dismiss()
}
val popupAlphaFromProperty = mProperty.popupAlpha
setBackgroundAlpha(popupAlphaFromProperty)
mPopupWindow.showAtLocation(parentView, Gravity.BOTTOM, 0, 0)
return mPopupWindow
}
/**
* 设置window背景透明度
*
* @param alpha
*/
private fun setBackgroundAlpha(alpha: Float) {
mProperty.window?.let {
it.attributes.alpha = alpha
it.attributes = it.attributes
}
}
/**
* 关闭弹窗
*/
fun dismiss(){
if(this::mPopupWindow.isInitialized){
mPopupWindow.dismiss()
}
}
}
data class BottomPopupProperty(var isOutsideTouchable: Boolean = true, var contentView: View? = null, var window: Window? = null, var popupAlpha: Float = 1f)
| apache-2.0 | 37b8cded51664f0ccc15ab286e87e75b | 25.432692 | 157 | 0.611495 | 4.805944 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/notes/book/BookPrefaceFragment.kt | 1 | 5282 | package com.orgzly.android.ui.notes.book
import android.content.Context
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.App
import com.orgzly.android.BookUtils
import com.orgzly.android.data.DataRepository
import com.orgzly.android.db.entity.Book
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.ui.CommonFragment
import com.orgzly.android.ui.main.SharedMainActivityViewModel
import com.orgzly.android.util.LogUtils
import com.orgzly.databinding.FragmentBookPrefaceBinding
import javax.inject.Inject
/**
* Book's preface and settings.
*/
class BookPrefaceFragment : CommonFragment() {
private lateinit var binding: FragmentBookPrefaceBinding
private var bookId: Long = 0
private var book: Book? = null
private var listener: Listener? = null
@Inject
lateinit var dataRepository: DataRepository
private lateinit var sharedMainActivityViewModel: SharedMainActivityViewModel
override fun onAttach(context: Context) {
super.onAttach(context)
App.appComponent.inject(this)
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, activity)
listener = activity as Listener
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedInstanceState)
sharedMainActivityViewModel =
ViewModelProvider(requireActivity())[SharedMainActivityViewModel::class.java]
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedInstanceState)
binding = FragmentBookPrefaceBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (AppPreferences.isFontMonospaced(context)) {
binding.fragmentBookPrefaceContent.setTypeface(Typeface.MONOSPACE)
}
binding.fragmentBookPrefaceContent.setOnUserTextChangeListener { str ->
binding.fragmentBookPrefaceContent.setSourceText(str)
}
/* Parse arguments - set content. */
requireArguments().apply {
require(containsKey(ARG_BOOK_ID)) { "No book id passed" }
require(containsKey(ARG_BOOK_PREFACE)) { "No book preface passed" }
bookId = getLong(ARG_BOOK_ID)
binding.fragmentBookPrefaceContent.setSourceText(getString(ARG_BOOK_PREFACE))
}
book = dataRepository.getBook(bookId)
topToolbarToDefault()
}
private fun topToolbarToDefault() {
binding.topToolbar.run {
setNavigationOnClickListener {
listener?.onBookPrefaceEditCancelRequest()
}
setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.delete -> {
save("")
}
R.id.done -> {
val source = binding.fragmentBookPrefaceContent.getSourceText()
save(source?.toString().orEmpty())
}
}
true
}
setOnClickListener {
binding.fragmentBookPrefaceContainer.scrollTo(0, 0)
}
title = BookUtils.getFragmentTitleForBook(book)
subtitle = getString(R.string.preface_in_book)
}
}
override fun onPause() {
super.onPause()
sharedMainActivityViewModel.unlockDrawer()
}
override fun onResume() {
super.onResume()
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG)
sharedMainActivityViewModel.setCurrentFragment(FRAGMENT_TAG)
sharedMainActivityViewModel.lockDrawer()
}
override fun onDetach() {
super.onDetach()
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG)
listener = null
}
private fun save(preface: String) {
book?.let {
listener?.onBookPrefaceEditSaveRequest(it, preface)
}
}
interface Listener {
fun onBookPrefaceEditSaveRequest(book: Book, preface: String)
fun onBookPrefaceEditCancelRequest()
}
companion object {
private val TAG = BookPrefaceFragment::class.java.name
/** Name used for [android.app.FragmentManager]. */
val FRAGMENT_TAG: String = BookPrefaceFragment::class.java.name
private const val ARG_BOOK_ID = "book_id"
private const val ARG_BOOK_PREFACE = "book_preface"
fun getInstance(bookId: Long, bookPreface: String?): BookPrefaceFragment {
val fragment = BookPrefaceFragment()
/* Set arguments for a fragment. */
val args = Bundle()
args.putLong(ARG_BOOK_ID, bookId)
args.putString(ARG_BOOK_PREFACE, bookPreface)
fragment.arguments = args
return fragment
}
}
}
| gpl-3.0 | 0de21587a34008a0d8421df0dc2862e3 | 28.021978 | 115 | 0.654866 | 4.86372 | false | false | false | false |
kaminomobile/AndroidVersion | plugin/src/main/kotlin/si/kamino/gradle/extensions/VersionExtension.kt | 1 | 1939 | package si.kamino.gradle.extensions
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.Nested
import si.kamino.gradle.extensions.code.BaseVersionCode
import si.kamino.gradle.extensions.code.StaticVersionCode
import si.kamino.gradle.extensions.name.AbsVersionName
import si.kamino.gradle.extensions.name.BaseVersionName
import si.kamino.gradle.extensions.name.ExtendingVersion
import java.io.Serializable
import javax.inject.Inject
abstract class VersionExtension @Inject constructor(private val objectFactory: ObjectFactory) : Serializable {
@get:Nested
var versionName: AbsVersionName = objectFactory.newInstance(BaseVersionName::class.java)
@get:Nested
var versionCode: BaseVersionCode = objectFactory.newInstance(StaticVersionCode::class.java)
@get:Nested
val variants: NamedDomainObjectContainer<ExtendingVersion> = objectFactory.domainObjectContainer(ExtendingVersion::class.java)
fun versionName(action: Action<BaseVersionName>) {
val instance = versionName
if (instance is BaseVersionName) {
action.execute(instance)
} else {
error("Incorrect version name type")
}
}
fun <T : AbsVersionName> versionName(clazz: Class<T>, action: Action<T>) {
val instance = objectFactory.newInstance(clazz)
action.execute(instance)
versionName = instance
}
fun versionCode(action: Action<StaticVersionCode>) {
val instance = versionCode
if (instance is StaticVersionCode) {
action.execute(instance)
} else {
error("Incorrect version code type")
}
}
fun <T : BaseVersionCode> versionCode(clazz: Class<T>, action: Action<T>) {
val instance = objectFactory.newInstance(clazz)
action.execute(instance)
versionCode = instance
}
}
| mit | ab9ffaa3a24cf1bf192c34d5b55197b5 | 33.017544 | 130 | 0.7246 | 4.530374 | false | false | false | false |
square/sqldelight | drivers/native-driver/src/nativeTest/kotlin/com/squareup/sqldelight/drivers/native/connectionpool/WalConcurrencyTest.kt | 1 | 5636 | package com.squareup.sqldelight.drivers.native.connectionpool
import co.touchlab.testhelp.concurrency.ThreadOperations
import co.touchlab.testhelp.concurrency.sleep
import com.squareup.sqldelight.Query
import com.squareup.sqldelight.TransacterImpl
import com.squareup.sqldelight.db.SqlCursor
import com.squareup.sqldelight.drivers.native.NativeSqliteDriver
import com.squareup.sqldelight.internal.copyOnWriteList
import kotlin.native.concurrent.AtomicInt
import kotlin.native.concurrent.TransferMode
import kotlin.native.concurrent.Worker
import kotlin.native.concurrent.freeze
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Testing multiple read and transaction pool connections. These were
* written when it a was a single pool, so this will need some refactor.
* The reader pool is much more likely to be multiple with a single transaction pool
* connection, which removes a lot of the potential concurrency issues, but introduces new things
* we should probably test.
*/
class WalConcurrencyTest : BaseConcurrencyTest() {
@BeforeTest
fun setup() {
initDriver(DbType.RegularWal)
}
/**
* This is less important now that we have a separate reader pool again, but will revisit.
*/
@Test
fun writeNotBlockRead() {
assertEquals(countRows(), 0)
val transacter: TransacterImpl = object : TransacterImpl(driver) {}
val worker = Worker.start()
val counter = AtomicInt(0)
val transactionStarted = AtomicInt(0)
val block = {
transacter.transaction {
insertTestData(TestData(1L, "arst 1"))
transactionStarted.increment()
sleep(1500)
counter.increment()
}
}
val future = worker.execute(TransferMode.SAFE, { block.freeze() }) { it() }
// When ready, transaction started but sleeping
waitFor { transactionStarted.value > 0 }
// These three should run before transaction is done (not blocking)
assertEquals(counter.value, 0)
assertEquals(0L, countRows())
assertEquals(counter.value, 0)
future.result
worker.requestTermination()
}
/**
* Reader pool stress test
*/
@Test
fun manyReads() = runConcurrent {
val transacter: TransacterImpl = object : TransacterImpl(driver) {}
val dataSize = 2_000
transacter.transaction {
repeat(dataSize) {
insertTestData(TestData(it.toLong(), "Data $it"))
}
}
val ops = ThreadOperations {}
val totalCount = AtomicInt(0)
val queryRuns = 100
repeat(queryRuns) {
ops.exe {
totalCount.addAndGet(testDataQuery().executeAsList().size)
}
}
ops.run(6)
assertEquals(totalCount.value, dataSize * queryRuns)
val readerPool = (driver as NativeSqliteDriver).readerPool
// Make sure we actually created all of the connections
assertTrue(readerPool.entryCount() > 1, "Reader pool size ${readerPool.entryCount()}")
}
private val mapper = { cursor: SqlCursor ->
TestData(
cursor.getLong(0)!!, cursor.getString(1)!!
)
}
private fun testDataQuery(): Query<TestData> {
return object : Query<TestData>(copyOnWriteList(), mapper) {
override fun execute(): SqlCursor {
return driver.executeQuery(0, "SELECT * FROM test", 0)
}
}
}
@Test
fun writeBlocksWrite() {
val transacter: TransacterImpl = object : TransacterImpl(driver) {}
val worker = Worker.start()
val counter = AtomicInt(0)
val transactionStarted = AtomicInt(0)
val block = {
transacter.transaction {
insertTestData(TestData(1L, "arst 1"))
transactionStarted.increment()
sleep(1500)
counter.increment()
}
}
val future = worker.execute(TransferMode.SAFE, { block.freeze() }) { it() }
// Transaction with write started but sleeping
waitFor { transactionStarted.value > 0 }
assertEquals(counter.value, 0)
insertTestData(TestData(2L, "arst 2")) // This waits on transaction to wrap up
assertEquals(counter.value, 1) // Counter would be zero if write didn't block (see above)
future.result
worker.requestTermination()
}
@Test
fun multipleWritesDontTimeOut() {
val transacter: TransacterImpl = object : TransacterImpl(driver) {}
val worker = Worker.start()
val transactionStarted = AtomicInt(0)
val block = {
transacter.transaction {
insertTestData(TestData(1L, "arst 1"), driver)
transactionStarted.increment()
sleep(1500)
insertTestData(TestData(5L, "arst 1"), driver)
}
}
val future = worker.execute(TransferMode.SAFE, { block.freeze() }) { it() }
// When we get here, first transaction has run a write command, and is sleeping
waitFor { transactionStarted.value > 0 }
transacter.transaction {
insertTestData(TestData(2L, "arst 2"), driver)
}
future.result
worker.requestTermination()
}
/**
* Just a bunch of inserts on multiple threads. More of a stress test.
*/
@Test
fun multiWrite() {
val ops = ThreadOperations {}
val times = 10_000
val transacter: TransacterImpl = object : TransacterImpl(driver) {}
repeat(times) { index ->
ops.exe {
transacter.transaction {
insertTestData(TestData(index.toLong(), "arst $index"))
val id2 = index.toLong() + times
insertTestData(TestData(id2, "arst $id2"))
val id3 = index.toLong() + times + times
insertTestData(TestData(id3, "arst $id3"))
}
}
}
ops.run(10)
assertEquals(countRows(), times.toLong() * 3)
}
}
| apache-2.0 | ab6bc5ebdc10ddff91a4faa56cceac7f | 28.051546 | 97 | 0.677431 | 4.266465 | false | true | false | false |
andersonFaro9/AppAbcAprender | app/src/main/java/com/kot/faro/myapplication/fruitsmath/MathOrangeSeteActivity.kt | 1 | 2565 | package com.kot.faro.myapplication.fruitsmath
import Interfacesforportugues.ButtonsForMath
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import com.kot.faro.myapplication.*
import com.kot.faro.myapplication.animaismath.MathTwoBearActivity
class MathOrangeSeteActivity : AppCompatActivity(), ButtonsForMath {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_math_orange_sete)
goNumberSevenOrange()
goNumberFiveOrangeSeven()
goNumbersixOrangeSeven()
getSupportActionBar()?.setDisplayHomeAsUpEnabled(true)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) : Boolean {
when (item.itemId) {
R.id.letras_frutas -> {
val intent = Intent(this@MathOrangeSeteActivity, GrapeActivity::class.java)
startActivity (intent)
return true
}
R.id.menu_inicial -> {
val intent = Intent(this@MathOrangeSeteActivity, MenuActivity::class.java)
startActivity (intent)
return true
}
R.id.letras_animais -> {
val intent = Intent(this@MathOrangeSeteActivity, PortuguesBearActivity::class.java)
startActivity (intent)
return true
}
R.id.sobre -> {
val intent = Intent(this@MathOrangeSeteActivity, SobreActivity::class.java)
startActivity (intent)
return true
}
R.id.dev -> {
val intent = Intent(this@MathOrangeSeteActivity, DevsActivity::class.java)
startActivity (intent)
return true
}
R.id.matematica_animais -> {
val intent = Intent(this@MathOrangeSeteActivity, MathTwoBearActivity::class.java)
startActivity (intent)
return true
}
R.id.matematica_frutas -> {
val intent = Intent(this@MathOrangeSeteActivity, MathOrangeFourActivity::class.java)
startActivity (intent)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
| apache-2.0 | 291a8b3de83807f4f7149220c27bbc9e | 24.909091 | 100 | 0.603119 | 4.830508 | false | false | false | false |
Szewek/Minecraft-Flux | src/main/java/szewek/mcflux/special/SpecialEvent.kt | 1 | 2307 | package szewek.mcflux.special
import com.google.gson.JsonObject
import net.minecraft.init.Items
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.nbt.JsonToNBT
import net.minecraft.nbt.NBTException
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.ResourceLocation
import szewek.mcflux.util.MCFluxReport
class SpecialEvent private constructor(val description: String, internal val colorBox: Int, internal val colorRibbon: Int, private val items: Array<SpecialItem>, val endTime: Long) {
fun createItems(): Array<ItemStack> {
val iss = arrayOfNulls<ItemStack>(items.size)
for (i in items.indices) {
if (items[i].item != Items.AIR) {
val stk = ItemStack(items[i].item!!, items[i].amount.toInt(), items[i].meta.toInt())
if (items[i].tag != null) {
stk.tagCompound = items[i].tag!!.copy()
}
iss[i] = stk
} else {
iss[i] = ItemStack.EMPTY
}
}
@Suppress("UNCHECKED_CAST")
return iss as Array<ItemStack>
}
internal class SpecialItem(val name: String, val amount: Byte, val meta: Short, t: String?) {
val item = Item.REGISTRY.getObject(ResourceLocation(name)) ?: Items.AIR
val tag: NBTTagCompound?
init {
if (t != null && item != Items.AIR) {
var nbt: NBTTagCompound?
try {
nbt = JsonToNBT.getTagFromJson(t)
} catch (e: NBTException) {
MCFluxReport.sendException(e, "NBT Decoding")
nbt = null
}
tag = nbt
} else
tag = null
}
}
companion object {
@Suppress("UNCHECKED_CAST")
@JvmStatic
internal fun fromJSON(jo: JsonObject): SpecialEvent? {
var ev: SpecialEvent? = null
try {
val d = jo["desc"].asString
val cb = jo["box"].asInt
val cr = jo["ribbon"].asInt
val et = jo["ends"].asLong
val ja = jo["items"].asJsonArray
val sis = arrayOfNulls<SpecialItem>(ja.size())
for (i in 0 until ja.size()) {
val ji = ja[i].asJsonArray
var m: Short = 0
var t: String? = null
if (ji.size() > 2)
m = ji[2].asShort
if (ji.size() > 3)
t = ji[3].asString
sis[i] = SpecialItem(ji[0].asString, ji[1].asByte, m, t)
}
ev = SpecialEvent(d, cb, cr, sis as Array<SpecialItem>, et)
} catch (e: Exception) {
MCFluxReport.sendException(e, "JSON decoding")
}
return ev
}
}
}
| mit | 3e5a6063ccab2d4b2b26f16ee5fe8d09 | 26.795181 | 182 | 0.654096 | 3.168956 | false | false | false | false |
deinspanjer/json-logic-java | src/main/kotlin/com/jsonlogic/JsEngine.kt | 1 | 986 | @file:Suppress("unused")
package com.jsonlogic
import jdk.nashorn.api.scripting.NashornScriptEngineFactory
import java.io.InputStream
import java.io.SequenceInputStream
import java.util.*
import javax.script.Invocable
import javax.script.ScriptContext
import javax.script.ScriptEngine
private val engine: ScriptEngine = NashornScriptEngineFactory().getScriptEngine("-strict=true", "--optimistic-types=true", "--language=es6", "-timezone=UTC")
private val js: Invocable = engine as Invocable
object JsEngine : ScriptEngine by engine, Invocable by js {
val GLOBAL_SCOPE = ScriptContext.GLOBAL_SCOPE
val ENGINE_SCOPE = ScriptContext.ENGINE_SCOPE
init {
engine.eval(
SequenceInputStream(Collections.enumeration(listOf<InputStream>(
javaClass.getResourceAsStream("/nashorn-polyfill.js"),
"\n//# sourceURL=src/main/resources/nashorn-polyfill.js".byteInputStream()
))).reader())
}
}
| mit | 69cab23581dcfc85b44f69470083066a | 34.214286 | 157 | 0.716024 | 4.421525 | false | false | false | false |
Takhion/android-extras-delegates | library/src/main/java/me/eugeniomarletti/extras/intent/base/Array.kt | 1 | 3770 | @file:Suppress("NOTHING_TO_INLINE")
package me.eugeniomarletti.extras.intent.base
import android.os.Parcelable
import me.eugeniomarletti.extras.intent.IntentExtra
inline fun IntentExtra.ParcelableArray(name: String? = null, customPrefix: String? = null) =
ParcelableArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.ParcelableArray(defaultValue: Array<Parcelable?>, name: String? = null, customPrefix: String? = null) =
ParcelableArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.CharSequenceArray(name: String? = null, customPrefix: String? = null) =
CharSequenceArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.CharSequenceArray(defaultValue: Array<CharSequence?>, name: String? = null, customPrefix: String? = null) =
CharSequenceArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.StringArray(name: String? = null, customPrefix: String? = null) =
StringArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.StringArray(defaultValue: Array<String?>, name: String? = null, customPrefix: String? = null) =
StringArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.ByteArray(name: String? = null, customPrefix: String? = null) =
ByteArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.ByteArray(defaultValue: ByteArray, name: String? = null, customPrefix: String? = null) =
ByteArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.CharArray(name: String? = null, customPrefix: String? = null) =
CharArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.CharArray(defaultValue: CharArray, name: String? = null, customPrefix: String? = null) =
CharArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.IntArray(name: String? = null, customPrefix: String? = null) =
IntArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.IntArray(defaultValue: IntArray, name: String? = null, customPrefix: String? = null) =
IntArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.ShortArray(name: String? = null, customPrefix: String? = null) =
ShortArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.ShortArray(defaultValue: ShortArray, name: String? = null, customPrefix: String? = null) =
ShortArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.LongArray(name: String? = null, customPrefix: String? = null) =
LongArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.LongArray(defaultValue: LongArray, name: String? = null, customPrefix: String? = null) =
LongArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.DoubleArray(name: String? = null, customPrefix: String? = null) =
DoubleArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.DoubleArray(defaultValue: DoubleArray, name: String? = null, customPrefix: String? = null) =
DoubleArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.FloatArray(name: String? = null, customPrefix: String? = null) =
FloatArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.FloatArray(defaultValue: FloatArray, name: String? = null, customPrefix: String? = null) =
FloatArray({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.BooleanArray(name: String? = null, customPrefix: String? = null) =
BooleanArray({ it }, { it }, name, customPrefix)
inline fun IntentExtra.BooleanArray(defaultValue: BooleanArray, name: String? = null, customPrefix: String? = null) =
BooleanArray({ it ?: defaultValue }, { it }, name, customPrefix) | mit | 9a1eb089b8f75d46ef79f62fd2af6594 | 51.375 | 130 | 0.71061 | 4.198218 | false | false | false | false |
AlmasB/FXGL | fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/view/ChildViewComponent.kt | 1 | 1360 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.dsl.components.view
import com.almasb.fxgl.entity.component.Component
import javafx.beans.property.DoubleProperty
import javafx.beans.property.SimpleDoubleProperty
import javafx.scene.Group
/**
*
* @author Almas Baimagambetov ([email protected])
*/
abstract class ChildViewComponent
@JvmOverloads constructor(x: Double = 0.0,
y: Double = 0.0,
val isTransformApplied: Boolean = true) : Component() {
private val propX: DoubleProperty = SimpleDoubleProperty(x)
private val propY: DoubleProperty = SimpleDoubleProperty(y)
var x: Double
get() = propX.value
set(value) { propX.value = value }
var y: Double
get() = propY.value
set(value) { propY.value = value }
val viewRoot = Group()
init {
viewRoot.translateXProperty().bind(propX)
viewRoot.translateYProperty().bind(propY)
}
override fun onAdded() {
entity.viewComponent.addChild(viewRoot, isTransformApplied)
}
override fun onRemoved() {
viewRoot.translateXProperty().unbind()
viewRoot.translateYProperty().unbind()
entity.viewComponent.removeChild(viewRoot)
}
} | mit | 7ded313d0c8431eb0d3d991701a2b739 | 26.22 | 81 | 0.663971 | 4.263323 | false | false | false | false |
fython/shadowsocks-android | mobile/src/main/java/com/github/shadowsocks/plugin/PluginManager.kt | 1 | 9954 | /*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[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 com.github.shadowsocks.plugin
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.ContentResolver
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.net.Uri
import android.os.Bundle
import android.util.Base64
import android.util.Log
import com.github.shadowsocks.App.Companion.app
import com.github.shadowsocks.utils.Commandline
import eu.chainfire.libsuperuser.Shell
import java.io.File
import java.io.FileNotFoundException
object PluginManager {
/**
* Trusted signatures by the app. Third-party fork should add their public key to their fork if the developer wishes
* to publish or has published plugins for this app. You can obtain your public key by executing:
*
* $ keytool -export -alias key-alias -keystore /path/to/keystore.jks -rfc
*
* If you don't plan to publish any plugin but is developing/has developed some, it's not necessary to add your
* public key yet since it will also automatically trust packages signed by the same signatures, e.g. debug keys.
*/
val trustedSignatures by lazy {
app.info.signatures.toSet() +
Signature(Base64.decode( // @Mygod
"""
|MIIDWzCCAkOgAwIBAgIEUzfv8DANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJD
|TjEOMAwGA1UECBMFTXlnb2QxDjAMBgNVBAcTBU15Z29kMQ4wDAYDVQQKEwVNeWdv
|ZDEOMAwGA1UECxMFTXlnb2QxDjAMBgNVBAMTBU15Z29kMCAXDTE0MDUwMjA5MjQx
|OVoYDzMwMTMwOTAyMDkyNDE5WjBdMQswCQYDVQQGEwJDTjEOMAwGA1UECBMFTXln
|b2QxDjAMBgNVBAcTBU15Z29kMQ4wDAYDVQQKEwVNeWdvZDEOMAwGA1UECxMFTXln
|b2QxDjAMBgNVBAMTBU15Z29kMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
|AQEAjm5ikHoP3w6zavvZU5bRo6Birz41JL/nZidpdww21q/G9APA+IiJMUeeocy0
|L7/QY8MQZABVwNq79LXYWJBcmmFXM9xBPgDqQP4uh9JsvazCI9bvDiMn92mz9HiS
|Sg9V4KGg0AcY0r230KIFo7hz+2QBp1gwAAE97myBfA3pi3IzJM2kWsh4LWkKQMfL
|M6KDhpb4mdDQnHlgi4JWe3SYbLtpB6whnTqjHaOzvyiLspx1tmrb0KVxssry9KoX
|YQzl56scfE/QJX0jJ5qYmNAYRCb4PibMuNSGB2NObDabSOMAdT4JLueOcHZ/x9tw
|agGQ9UdymVZYzf8uqc+29ppKdQIDAQABoyEwHzAdBgNVHQ4EFgQUBK4uJ0cqmnho
|6I72VmOVQMvVCXowDQYJKoZIhvcNAQELBQADggEBABZQ3yNESQdgNJg+NRIcpF9l
|YSKZvrBZ51gyrC7/2ZKMpRIyXruUOIrjuTR5eaONs1E4HI/uA3xG1eeW2pjPxDnO
|zgM4t7EPH6QbzibihoHw1MAB/mzECzY8r11PBhDQlst0a2hp+zUNR8CLbpmPPqTY
|RSo6EooQ7+NBejOXysqIF1q0BJs8Y5s/CaTOmgbL7uPCkzArB6SS/hzXgDk5gw6v
|wkGeOtzcj1DlbUTvt1s5GlnwBTGUmkbLx+YUje+n+IBgMbohLUDYBtUHylRVgMsc
|1WS67kDqeJiiQZvrxvyW6CZZ/MIGI+uAkkj3DqJpaZirkwPgvpcOIrjZy0uFvQM=
""", Base64.DEFAULT)) +
Signature(Base64.decode( // @madeye
"""
|MIICQzCCAaygAwIBAgIETV9OhjANBgkqhkiG9w0BAQUFADBmMQswCQYDVQQGEwJjbjERMA8GA1UE
|CBMIU2hhbmdoYWkxDzANBgNVBAcTBlB1ZG9uZzEUMBIGA1UEChMLRnVkYW4gVW5pdi4xDDAKBgNV
|BAsTA1BQSTEPMA0GA1UEAxMGTWF4IEx2MB4XDTExMDIxOTA1MDA1NFoXDTM2MDIxMzA1MDA1NFow
|ZjELMAkGA1UEBhMCY24xETAPBgNVBAgTCFNoYW5naGFpMQ8wDQYDVQQHEwZQdWRvbmcxFDASBgNV
|BAoTC0Z1ZGFuIFVuaXYuMQwwCgYDVQQLEwNQUEkxDzANBgNVBAMTBk1heCBMdjCBnzANBgkqhkiG
|9w0BAQEFAAOBjQAwgYkCgYEAq6lA8LqdeEI+es9SDX85aIcx8LoL3cc//iRRi+2mFIWvzvZ+bLKr
|4Wd0rhu/iU7OeMm2GvySFyw/GdMh1bqh5nNPLiRxAlZxpaZxLOdRcxuvh5Nc5yzjM+QBv8ECmuvu
|AOvvT3UDmA0AMQjZqSCmxWIxc/cClZ/0DubreBo2st0CAwEAATANBgkqhkiG9w0BAQUFAAOBgQAQ
|Iqonxpwk2ay+Dm5RhFfZyG9SatM/JNFx2OdErU16WzuK1ItotXGVJaxCZv3u/tTwM5aaMACGED5n
|AvHaDGCWynY74oDAopM4liF/yLe1wmZDu6Zo/7fXrH+T03LBgj2fcIkUfN1AA4dvnBo8XWAm9VrI
|1iNuLIssdhDz3IL9Yg==
""", Base64.DEFAULT))
}
private var receiver: BroadcastReceiver? = null
private var cachedPlugins: Map<String, Plugin>? = null
fun fetchPlugins(): Map<String, Plugin> {
return synchronized(this) {
if (receiver == null) receiver = app.listenForPackageChanges {
synchronized(this) {
receiver = null
cachedPlugins = null
}
}
if (cachedPlugins == null) {
val pm = app.packageManager
cachedPlugins = (pm.queryIntentContentProviders(Intent(PluginContract.ACTION_NATIVE_PLUGIN),
PackageManager.GET_META_DATA).map { NativePlugin(it) } + NoPlugin).associate { it.id to it }
}
cachedPlugins!!
}
}
private fun buildUri(id: String) = Uri.Builder()
.scheme(PluginContract.SCHEME)
.authority(PluginContract.AUTHORITY)
.path('/' + id)
.build()
fun buildIntent(id: String, action: String): Intent = Intent(action, buildUri(id))
// the following parts are meant to be used by :bg
@Throws(Throwable::class)
fun init(options: PluginOptions): String? {
if (options.id.isEmpty()) return null
var throwable: Throwable? = null
try {
val path = initNative(options)
if (path != null) return path
} catch (t: Throwable) {
t.printStackTrace()
if (throwable == null) throwable = t
}
// add other plugin types here
throw if (throwable != null) throwable else
FileNotFoundException(app.getString(com.github.shadowsocks.R.string.plugin_unknown, options.id))
}
private fun initNative(options: PluginOptions): String? {
val providers = app.packageManager.queryIntentContentProviders(
Intent(PluginContract.ACTION_NATIVE_PLUGIN, buildUri(options.id)), 0)
check(providers.size == 1)
val uri = Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(providers[0].providerInfo.authority)
.build()
val cr = app.contentResolver
return try {
initNativeFast(cr, options, uri)
} catch (t: Throwable) {
t.printStackTrace()
Log.w("PluginManager", "Initializing native plugin fast mode failed. Falling back to slow mode.")
initNativeSlow(cr, options, uri)
}
}
private fun initNativeFast(cr: ContentResolver, options: PluginOptions, uri: Uri): String {
val out = Bundle()
out.putString(PluginContract.EXTRA_OPTIONS, options.id)
val result = cr.call(uri, PluginContract.METHOD_GET_EXECUTABLE, null, out)
.getString(PluginContract.EXTRA_ENTRY)
check(File(result).canExecute())
return result
}
@SuppressLint("Recycle")
private fun initNativeSlow(cr: ContentResolver, options: PluginOptions, uri: Uri): String? {
var initialized = false
fun entryNotFound(): Nothing = throw IndexOutOfBoundsException("Plugin entry binary not found")
val list = ArrayList<String>()
val pluginDir = File(app.deviceContext.filesDir, "plugin")
(cr.query(uri, arrayOf(PluginContract.COLUMN_PATH, PluginContract.COLUMN_MODE), null, null, null)
?: return null).use { cursor ->
if (!cursor.moveToFirst()) entryNotFound()
pluginDir.deleteRecursively()
if (!pluginDir.mkdirs()) throw FileNotFoundException("Unable to create plugin directory")
val pluginDirPath = pluginDir.absolutePath + '/'
do {
val path = cursor.getString(0)
val file = File(pluginDir, path)
check(file.absolutePath.startsWith(pluginDirPath))
cr.openInputStream(uri.buildUpon().path(path).build()).use { inStream ->
file.outputStream().use { outStream -> inStream.copyTo(outStream) }
}
list += Commandline.toString(arrayOf("chmod", cursor.getString(1), file.absolutePath))
if (path == options.id) initialized = true
} while (cursor.moveToNext())
}
if (!initialized) entryNotFound()
Shell.SH.run(list)
return File(pluginDir, options.id).absolutePath
}
}
| gpl-3.0 | 488d20db1c69a0f6bdd7226f11aad159 | 51.946809 | 120 | 0.614225 | 3.700372 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.